pegjs/lib/compiler.js
David Majda e4b5588327 Plugin API: Split compiler passes into stages
The compiler passes are now split into three stages:

  * check -- passes that check for various error conditions

  * transform -- passes that transform the AST (e.g. to perform
    optimizations)

  * generate -- passes that are related to code generation

Splitting the passes into stages is important for plugins. For example,
if a plugin wants to add a new optimization pass, it can add it at the
end of the "transform" stage without any knowledge about other passes it
contains. Similarly, if it wants to generate something else than the
default code generator does from the AST, it can just replace all passes
in the "generate" stage by its own one(s).

More generally, the stages make it possible to write plugins that do not
depend on names and actions of specific passes (which I consider
internal and subject of change), just on the definition of stages (which
I consider a public API with to which semver rules apply).

Implements part of GH-106.
2013-01-13 19:08:06 +01:00

60 lines
1.7 KiB
JavaScript

var utils = require("./utils");
module.exports = {
/*
* Compiler passes.
*
* Each pass is a function that is passed the AST. It can perform checks on it
* or modify it as needed. If the pass encounters a semantic error, it throws
* |PEG.GrammarError|.
*/
passes: {
check: {
reportMissingRules: require("./compiler/passes/report-missing-rules"),
reportLeftRecursion: require("./compiler/passes/report-left-recursion")
},
transform: {
removeProxyRules: require("./compiler/passes/remove-proxy-rules")
},
generate: {
generateBytecode: require("./compiler/passes/generate-bytecode"),
generateJavascript: require("./compiler/passes/generate-javascript")
}
},
/*
* Generates a parser from a specified grammar AST. Throws |PEG.GrammarError|
* if the AST contains a semantic error. Note that not all errors are detected
* during the generation and some may protrude to the generated parser and
* cause its malfunction.
*/
compile: function(ast, passes) {
var options = arguments.length > 2 ? utils.clone(arguments[2]) : {},
stage;
/*
* Extracted into a function just to silence JSHint complaining about
* creating functions in a loop.
*/
function runPass(pass) {
pass(ast, options);
}
utils.defaults(options, {
allowedStartRules: [ast.rules[0].name],
cache: false,
optimize: "speed",
output: "parser"
});
for (stage in passes) {
utils.each(passes[stage], runPass);
}
switch (options.output) {
case "parser": return eval(ast.code);
case "source": return ast.code;
}
}
};