pegjs/lib/compiler/passes/remove-proxy-rules.js
David Majda 898a7b5a2d Simplify visitors by providing default visit functions
The |visitor.build| function now supplies default visit functions for
visitors it builds. These functions don't do anything beside traversing
the tree and passing arguments around to child visit functions.

Having the default visit functions allowed to simplify several visitors.
2014-06-04 07:41:00 +02:00

41 lines
931 B
JavaScript

var arrays = require("../../utils/arrays"),
visitor = require("../visitor");
/*
* Removes proxy rules -- that is, rules that only delegate to other rule.
*/
function removeProxyRules(ast, options) {
function isProxyRule(node) {
return node.type === "rule" && node.expression.type === "rule_ref";
}
function replaceRuleRefs(ast, from, to) {
var replace = visitor.build({
rule_ref: function(node) {
if (node.name === from) {
node.name = to;
}
}
});
replace(ast);
}
var indices = [];
arrays.each(ast.rules, function(rule, i) {
if (isProxyRule(rule)) {
replaceRuleRefs(ast, rule.name, rule.expression.name);
if (!arrays.contains(options.allowedStartRules, rule.name)) {
indices.push(i);
}
}
});
indices.reverse();
arrays.each(indices, function(i) { ast.rules.splice(i, 1); });
}
module.exports = removeProxyRules;