importPackage(java.io); importPackage(java.lang); /* * Rhino does not have __FILE__ or anything similar so we have to pass the * script path from the outside. */ load(arguments[0] + "/../lib/peg.js"); var FILE_STDIN = "-"; var FILE_STDOUT = "-"; function readFile(file) { var f = new BufferedReader(new InputStreamReader( file === FILE_STDIN ? System["in"] : new FileInputStream(file) )); var result = ""; var line = ""; try { while ((line = f.readLine()) !== null) { result += line + "\n"; } } finally { f.close(); } return result; } function writeFile(file, text) { var f = new BufferedWriter(new OutputStreamWriter( file === FILE_STDOUT ? System.out : new FileOutputStream(file) )); try { f.write(text); } finally { f.close(); } } function isOption(arg) { return /-.+/.test(arg); } function printVersion() { print("PEG.js 0.1"); } function printHelp() { print("Usage: pegjs [options] [--] [] []"); print(""); print("Generates a parser from the PEG grammar specified in the and"); print("writes it to the ."); print(""); print("If the is omitted, its name is generated by changing the"); print(" extension to \".js\". If both and are"); print("omitted, standard input and output are used."); print(""); print("Options:"); print(" -e, --export-var name of the variable where the parser object"); print(" will be stored (default: \"exports.parser\")"); print(" -v, --version print version information and exit"); print(" -h, --help print help and exit"); } function nextArg() { args.shift(); } function exitSuccess() { quit(0); } function exitFailure() { quit(1); } function abort(message) { System.out.println(message); exitFailure(); } /* This makes the generated parser a CommonJS module by default. */ var exportVar = "exports.parser"; /* * The trimmed first argument is the script path -- see the beginning of this * file. */ var args = Array.prototype.slice.call(arguments, 1); while (args.length > 0 && isOption(args[0])) { switch (args[0]) { case "-e": case "--export-var": nextArg(); exportVar = args[0]; break; case "--version": printVersion(); exitSuccess(); break; case "-v": case "--version": printVersion(); exitSuccess(); break; case "-h": case "--help": printHelp(); exitSuccess(); break; case "--": nextArg(); break; default: abort("Unknown option: " + args[0] + "."); } nextArg(); } switch (args.length) { case 0: var inputFile = FILE_STDIN; var outputFile = FILE_STDOUT; break; case 1: var inputFile = args[0]; var outputFile = args[0].replace(/\.[^.]*$/, ".js"); break; case 2: var inputFile = args[0]; var outputFile = args[1]; break; default: abort("Too many arguments."); } var input = readFile(inputFile); try { var parser = PEG.buildParser(input); } catch (e) { if (e.line !== undefined && e.column !== undefined) { abort(e.line + ":" + e.column + ": " + e.message); } else { abort(e.message); } } writeFile(outputFile, exportVar + " = " + parser.toSource() + ";\n");