2015-06-08 20:21:19 +02:00
|
|
|
"use strict";
|
|
|
|
|
2016-09-17 15:08:47 +02:00
|
|
|
let GrammarError = require("../../grammar-error");
|
2016-09-22 09:25:31 +02:00
|
|
|
let asts = require("../asts");
|
|
|
|
let visitor = require("../visitor");
|
2012-11-10 09:47:22 +01:00
|
|
|
|
2016-09-17 16:28:28 +02:00
|
|
|
// 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.
|
2016-07-29 18:06:16 +02:00
|
|
|
function reportInfiniteRecursion(ast) {
|
2016-09-08 16:04:36 +02:00
|
|
|
let visitedRules = [];
|
2015-08-07 14:34:19 +02:00
|
|
|
|
2016-09-08 16:04:36 +02:00
|
|
|
let check = visitor.build({
|
2016-10-07 17:03:10 +02:00
|
|
|
rule(node) {
|
2015-08-07 14:34:19 +02:00
|
|
|
visitedRules.push(node.name);
|
|
|
|
check(node.expression);
|
|
|
|
visitedRules.pop(node.name);
|
2014-06-04 07:23:34 +02:00
|
|
|
},
|
|
|
|
|
2016-10-07 17:03:10 +02:00
|
|
|
sequence(node) {
|
2016-09-09 13:27:24 +02:00
|
|
|
node.elements.every(element => {
|
2015-08-17 10:58:37 +02:00
|
|
|
check(element);
|
2015-03-31 19:02:59 +02:00
|
|
|
|
2015-09-04 17:35:37 +02:00
|
|
|
return !asts.alwaysConsumesOnSuccess(ast, element);
|
2015-03-31 19:02:59 +02:00
|
|
|
});
|
2014-06-04 07:23:34 +02:00
|
|
|
},
|
|
|
|
|
2016-10-07 17:03:10 +02:00
|
|
|
rule_ref(node) {
|
2016-09-14 10:03:59 +02:00
|
|
|
if (visitedRules.indexOf(node.name) !== -1) {
|
2015-09-11 15:06:57 +02:00
|
|
|
visitedRules.push(node.name);
|
|
|
|
|
2014-06-04 07:23:34 +02:00
|
|
|
throw new GrammarError(
|
2016-07-03 18:01:39 +02:00
|
|
|
"Possible infinite loop when parsing (left recursion: "
|
2015-09-11 15:06:57 +02:00
|
|
|
+ visitedRules.join(" -> ")
|
|
|
|
+ ").",
|
2015-04-06 10:34:07 +02:00
|
|
|
node.location
|
2014-06-04 07:23:34 +02:00
|
|
|
);
|
|
|
|
}
|
2015-03-31 19:02:59 +02:00
|
|
|
|
2015-08-07 14:34:19 +02:00
|
|
|
check(asts.findRule(ast, node.name));
|
2014-06-04 07:23:34 +02:00
|
|
|
}
|
2012-04-19 14:23:21 +02:00
|
|
|
});
|
|
|
|
|
2015-08-07 14:34:19 +02:00
|
|
|
check(ast);
|
2014-05-04 14:11:44 +02:00
|
|
|
}
|
|
|
|
|
2016-07-29 18:06:16 +02:00
|
|
|
module.exports = reportInfiniteRecursion;
|