2015-06-08 20:21:19 +02:00
|
|
|
"use strict";
|
|
|
|
|
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
|
|
|
|
2015-04-01 10:07:01 +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.
|
|
|
|
*/
|
2014-05-04 14:11:44 +02:00
|
|
|
function reportLeftRecursion(ast) {
|
2015-08-07 14:34:19 +02:00
|
|
|
var visitedRules = [];
|
|
|
|
|
2014-05-08 14:51:17 +02:00
|
|
|
var check = visitor.build({
|
2015-08-07 14:34:19 +02:00
|
|
|
rule: function(node) {
|
|
|
|
visitedRules.push(node.name);
|
|
|
|
check(node.expression);
|
|
|
|
visitedRules.pop(node.name);
|
2014-06-04 07:23:34 +02:00
|
|
|
},
|
|
|
|
|
2015-08-07 14:34:19 +02:00
|
|
|
sequence: function(node) {
|
2015-03-31 19:02:59 +02:00
|
|
|
arrays.every(node.elements, function(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
|
|
|
},
|
|
|
|
|
2015-08-07 14:34:19 +02:00
|
|
|
rule_ref: function(node) {
|
2015-04-01 10:08:45 +02:00
|
|
|
if (arrays.contains(visitedRules, node.name)) {
|
2015-09-11 15:06:57 +02:00
|
|
|
visitedRules.push(node.name);
|
|
|
|
|
2014-06-04 07:23:34 +02:00
|
|
|
throw new GrammarError(
|
2015-09-11 15:06:57 +02:00
|
|
|
"Possible left recursion detected ("
|
|
|
|
+ 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
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = reportLeftRecursion;
|