2014-05-08 11:48:56 +02:00
|
|
|
var arrays = require("../../utils/arrays"),
|
|
|
|
GrammarError = require("../../grammar-error"),
|
|
|
|
asts = require("../asts"),
|
|
|
|
visitor = require("../visitor");
|
2012-11-10 09:47:22 +01:00
|
|
|
|
2012-04-19 14:23:21 +02:00
|
|
|
/* Checks that no left recursion is present. */
|
2014-05-04 14:11:44 +02:00
|
|
|
function reportLeftRecursion(ast) {
|
2012-04-19 14:23:21 +02:00
|
|
|
function nop() {}
|
|
|
|
|
|
|
|
function checkExpression(node, appliedRules) {
|
|
|
|
check(node.expression, appliedRules);
|
|
|
|
}
|
|
|
|
|
|
|
|
function checkSubnodes(propertyName) {
|
|
|
|
return function(node, appliedRules) {
|
2014-05-08 11:48:56 +02:00
|
|
|
arrays.each(node[propertyName], function(subnode) {
|
2012-04-19 14:23:21 +02:00
|
|
|
check(subnode, appliedRules);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2014-05-08 14:51:17 +02:00
|
|
|
var check = visitor.build({
|
2012-04-19 14:23:21 +02:00
|
|
|
grammar: checkSubnodes("rules"),
|
|
|
|
|
|
|
|
rule:
|
|
|
|
function(node, appliedRules) {
|
|
|
|
check(node.expression, appliedRules.concat(node.name));
|
|
|
|
},
|
|
|
|
|
2012-06-24 16:55:30 +02:00
|
|
|
named: checkExpression,
|
2012-04-19 14:23:21 +02:00
|
|
|
choice: checkSubnodes("alternatives"),
|
2012-06-26 20:28:06 +02:00
|
|
|
action: checkExpression,
|
2012-04-19 14:23:21 +02:00
|
|
|
|
|
|
|
sequence:
|
|
|
|
function(node, appliedRules) {
|
|
|
|
if (node.elements.length > 0) {
|
|
|
|
check(node.elements[0], appliedRules);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
labeled: checkExpression,
|
2012-12-01 15:46:14 +01:00
|
|
|
text: checkExpression,
|
2012-04-19 14:23:21 +02:00
|
|
|
simple_and: checkExpression,
|
|
|
|
simple_not: checkExpression,
|
|
|
|
semantic_and: nop,
|
|
|
|
semantic_not: nop,
|
|
|
|
optional: checkExpression,
|
|
|
|
zero_or_more: checkExpression,
|
|
|
|
one_or_more: checkExpression,
|
|
|
|
|
|
|
|
rule_ref:
|
|
|
|
function(node, appliedRules) {
|
2014-05-08 11:48:56 +02:00
|
|
|
if (arrays.contains(appliedRules, node.name)) {
|
2012-12-07 23:32:58 +01:00
|
|
|
throw new GrammarError(
|
2012-04-19 14:23:21 +02:00
|
|
|
"Left recursion detected for rule \"" + node.name + "\"."
|
|
|
|
);
|
|
|
|
}
|
2014-05-08 14:46:11 +02:00
|
|
|
check(asts.findRule(ast, node.name), appliedRules);
|
2012-04-19 14:23:21 +02:00
|
|
|
},
|
|
|
|
|
|
|
|
literal: nop,
|
2012-06-25 21:46:47 +02:00
|
|
|
"class": nop,
|
|
|
|
any: nop
|
2012-04-19 14:23:21 +02:00
|
|
|
});
|
|
|
|
|
|
|
|
check(ast, []);
|
2014-05-04 14:11:44 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = reportLeftRecursion;
|