pegjs/lib/compiler/passes/report-left-recursion.js
David Majda 95ce20ed92 Extract the |matchesEmpty| visitor from the |reportLeftRecursion| pass
Beside the recursion detector, the visitor will also be used by infinite
loop detector.

Note the newly created |asts.matchesEmpty| function re-creates the
visitor each time it is called, which makes it slower than necessary.
This could have been worked around in various ways but I chose to defer
that optimization because real-world performance impact is small.
2015-04-01 12:20:48 +02:00

49 lines
1.3 KiB
JavaScript

var arrays = require("../../utils/arrays"),
GrammarError = require("../../grammar-error"),
asts = require("../asts"),
visitor = require("../visitor");
/*
* Reports left recursion in the grammar, which prevents infinite recursion in
* the generated parser.
*
* Both direct and indirect recursion is detected. The pass also correctly
* reports cases like this:
*
* start = "a"? start
*
* In general, if a rule reference can be reached without consuming any input,
* it can lead to left recursion.
*/
function reportLeftRecursion(ast) {
var check = visitor.build({
rule: function(node, visitedRules) {
check(node.expression, visitedRules.concat(node.name));
},
sequence: function(node, visitedRules) {
arrays.every(node.elements, function(element) {
if (element.type === "rule_ref") {
check(element, visitedRules);
}
return asts.matchesEmpty(ast, element);
});
},
rule_ref: function(node, visitedRules) {
if (arrays.contains(visitedRules, node.name)) {
throw new GrammarError(
"Left recursion detected for rule \"" + node.name + "\"."
);
}
check(asts.findRule(ast, node.name), visitedRules);
}
});
check(ast, []);
}
module.exports = reportLeftRecursion;