From 76f5c88073af8e62e0b576c1762f9de30a6ed24a Mon Sep 17 00:00:00 2001 From: David Majda Date: Fri, 11 Jan 2013 20:55:33 +0100 Subject: [PATCH] Plugin API: Implement the |plugins| option for |PEG.buildParser| The |plugins| option allows users to use plugins that change how PEG.js operates. A plugin is any JavaScript object with a |use| method. After the user calls |PEG.buildParser|, this method is called for each plugin with the following two parameters: * PEG.js config that describes used grammar parser and compiler passes used to generate the parser * options passed by user to |PEG.buildParser| The plugin is expected to change the config as needed, possibly based on the options passed by user. It can e.g. change the used grammar parser, change the compiler passes (including adding its own), etc. This way it can extend PEG.js in a flexible way. Implements part of GH-106. --- README.md | 1 + lib/peg.js | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 4151146..68b1f4c 100644 --- a/README.md +++ b/README.md @@ -110,6 +110,7 @@ object to `PEG.buildParser`. The following options are supported: (default: `"parser"`) * `optimize`— selects between optimizing the generated parser for parsing speed (`"speed"`) or code size (`"size"`) (default: `"speed"`) + * `plugins` — plugins to use Using the Parser ---------------- diff --git a/lib/peg.js b/lib/peg.js index 56efd57..0410c29 100644 --- a/lib/peg.js +++ b/lib/peg.js @@ -19,10 +19,19 @@ module.exports = { * errors are detected during the generation and some may protrude to the * generated parser and cause its malfunction. */ - buildParser: function(grammar, options) { + buildParser: function(grammar) { + var options = arguments.length > 1 ? utils.clone(arguments[1]) : {}, + plugins = "plugins" in options ? options.plugins : [], + config = { + parser: this.parser, + passes: utils.values(this.compiler.passes) + }; + + utils.each(plugins, function(p) { p.use(config, options); }); + return this.compiler.compile( - this.parser.parse(grammar), - utils.values(this.compiler.passes), + config.parser.parse(grammar), + config.passes, options ); }