From 851681d66324a5aed3e9e4899502ac6c2f9afbeb Mon Sep 17 00:00:00 2001 From: David Majda Date: Sun, 20 Jan 2013 10:11:08 +0100 Subject: [PATCH] Implement the --extra-options and --extra-options-file options These are mainly useful to pass additional options to plugins. --- README.md | 4 ++++ bin/pegjs | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/README.md b/README.md index 4191d52..5f2c611 100644 --- a/README.md +++ b/README.md @@ -79,6 +79,10 @@ You can tweak the generated parser with several options: allowed to start parsing from (default: the first rule in the grammar) * `--plugin` — makes PEG.js use a specified plugin (can be specified multiple times) + * `--extra-options` — additional options (in JSON format) to pass to + `PEG.buildParser` + * `--extra-options-file` — file with additional options (in JSON format) to + pass to `PEG.buildParser` ### JavaScript API diff --git a/bin/pegjs b/bin/pegjs index 0fbd723..8d76fbe 100755 --- a/bin/pegjs +++ b/bin/pegjs @@ -34,6 +34,10 @@ function printHelp() { util.puts(" (default: speed)"); util.puts(" --plugin use a specified plugin (can be specified"); util.puts(" multiple times)"); + util.puts(" --extra-options additional options (in JSON format) to pass"); + util.puts(" to PEG.buildParser"); + util.puts(" --extra-options-file file with additional options (in JSON"); + util.puts(" format) to pass to PEG.buildParser"); util.puts(" -v, --version print version information and exit"); util.puts(" -h, --help print help and exit"); } @@ -51,6 +55,23 @@ function abort(message) { exitFailure(); } +function addExtraOptions(options, json) { + try { + var extraOptions = JSON.parse(json); + } catch (e) { + if (!(e instanceof SyntaxError)) { throw e; } + + abort("Error parsing JSON: " + e.message); + } + if (typeof extraOptions !== "object") { + abort("The JSON with extra options has to represent an object."); + } + + for (var key in extraOptions) { + options[key] = extraOptions[key]; + } +} + /* Arguments */ var args = process.argv.slice(2); // Trim "node" and the script path. @@ -135,6 +156,27 @@ while (args.length > 0 && isOption(args[0])) { options.plugins.push(module); break; + case "--extra-options": + nextArg(); + if (args.length === 0) { + abort("Missing parameter of the --extra-options option."); + } + addExtraOptions(options, args[0]); + break; + + case "--extra-options-file": + nextArg(); + if (args.length === 0) { + abort("Missing parameter of the --extra-options-file option."); + } + try { + var json = fs.readFileSync(args[0]); + } catch(e) { + abort("Can't read from file \"" + args[0] + "\"."); + } + addExtraOptions(options, json); + break; + case "-v": case "--version": printVersion();