You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.9 KiB
JavaScript
75 lines
1.9 KiB
JavaScript
12 years ago
|
var utils = require("../../utils");
|
||
|
|
||
12 years ago
|
/*
|
||
|
* Removes proxy rules -- that is, rules that only delegate to other rule.
|
||
|
*/
|
||
12 years ago
|
module.exports = function(ast) {
|
||
12 years ago
|
function isProxyRule(node) {
|
||
|
return node.type === "rule" && node.expression.type === "rule_ref";
|
||
|
}
|
||
|
|
||
|
function replaceRuleRefs(ast, from, to) {
|
||
|
function nop() {}
|
||
|
|
||
|
function replaceInExpression(node, from, to) {
|
||
|
replace(node.expression, from, to);
|
||
|
}
|
||
|
|
||
|
function replaceInSubnodes(propertyName) {
|
||
|
return function(node, from, to) {
|
||
12 years ago
|
utils.each(node[propertyName], function(subnode) {
|
||
12 years ago
|
replace(subnode, from, to);
|
||
|
});
|
||
|
};
|
||
|
}
|
||
|
|
||
12 years ago
|
var replace = utils.buildNodeVisitor({
|
||
12 years ago
|
grammar: replaceInSubnodes("rules"),
|
||
|
rule: replaceInExpression,
|
||
12 years ago
|
named: replaceInExpression,
|
||
12 years ago
|
choice: replaceInSubnodes("alternatives"),
|
||
|
sequence: replaceInSubnodes("elements"),
|
||
|
labeled: replaceInExpression,
|
||
|
simple_and: replaceInExpression,
|
||
|
simple_not: replaceInExpression,
|
||
|
semantic_and: nop,
|
||
|
semantic_not: nop,
|
||
|
optional: replaceInExpression,
|
||
|
zero_or_more: replaceInExpression,
|
||
|
one_or_more: replaceInExpression,
|
||
|
action: replaceInExpression,
|
||
|
|
||
|
rule_ref:
|
||
|
function(node, from, to) {
|
||
|
if (node.name === from) {
|
||
|
node.name = to;
|
||
|
}
|
||
|
},
|
||
|
|
||
|
literal: nop,
|
||
12 years ago
|
"class": nop,
|
||
|
any: nop
|
||
12 years ago
|
});
|
||
|
|
||
|
replace(ast, from, to);
|
||
|
}
|
||
|
|
||
|
var indices = [];
|
||
|
|
||
12 years ago
|
utils.each(ast.rules, function(rule, i) {
|
||
12 years ago
|
if (isProxyRule(rule)) {
|
||
|
replaceRuleRefs(ast, rule.name, rule.expression.name);
|
||
|
if (rule.name === ast.startRule) {
|
||
|
ast.startRule = rule.expression.name;
|
||
|
}
|
||
|
indices.push(i);
|
||
|
}
|
||
|
});
|
||
|
|
||
|
indices.reverse();
|
||
|
|
||
12 years ago
|
utils.each(indices, function(index) {
|
||
12 years ago
|
ast.rules.splice(index, 1);
|
||
|
});
|
||
|
};
|