2015-06-08 20:21:19 +02:00
|
|
|
"use strict";
|
|
|
|
|
2016-08-19 17:07:31 +02:00
|
|
|
var objects = require("../utils/objects");
|
2014-06-04 07:23:34 +02:00
|
|
|
|
2014-05-08 11:48:56 +02:00
|
|
|
/* Simple AST node visitor builder. */
|
|
|
|
var visitor = {
|
2014-05-08 14:51:17 +02:00
|
|
|
build: function(functions) {
|
2014-06-04 07:23:34 +02:00
|
|
|
function visit(node) {
|
2014-05-08 11:48:56 +02:00
|
|
|
return functions[node.type].apply(null, arguments);
|
2014-06-04 07:23:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
function visitNop() { }
|
|
|
|
|
|
|
|
function visitExpression(node) {
|
|
|
|
var extraArgs = Array.prototype.slice.call(arguments, 1);
|
|
|
|
|
|
|
|
visit.apply(null, [node.expression].concat(extraArgs));
|
|
|
|
}
|
|
|
|
|
|
|
|
function visitChildren(property) {
|
|
|
|
return function(node) {
|
|
|
|
var extraArgs = Array.prototype.slice.call(arguments, 1);
|
|
|
|
|
2016-08-19 17:07:31 +02:00
|
|
|
node[property].forEach(function(child) {
|
2014-06-04 07:23:34 +02:00
|
|
|
visit.apply(null, [child].concat(extraArgs));
|
|
|
|
});
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
var DEFAULT_FUNCTIONS = {
|
|
|
|
grammar: function(node) {
|
|
|
|
var extraArgs = Array.prototype.slice.call(arguments, 1);
|
|
|
|
|
|
|
|
if (node.initializer) {
|
|
|
|
visit.apply(null, [node.initializer].concat(extraArgs));
|
|
|
|
}
|
|
|
|
|
2016-08-19 17:07:31 +02:00
|
|
|
node.rules.forEach(function(rule) {
|
2014-06-04 07:23:34 +02:00
|
|
|
visit.apply(null, [rule].concat(extraArgs));
|
|
|
|
});
|
|
|
|
},
|
|
|
|
|
|
|
|
initializer: visitNop,
|
|
|
|
rule: visitExpression,
|
|
|
|
named: visitExpression,
|
|
|
|
choice: visitChildren("alternatives"),
|
|
|
|
action: visitExpression,
|
|
|
|
sequence: visitChildren("elements"),
|
|
|
|
labeled: visitExpression,
|
|
|
|
text: visitExpression,
|
|
|
|
simple_and: visitExpression,
|
|
|
|
simple_not: visitExpression,
|
|
|
|
optional: visitExpression,
|
|
|
|
zero_or_more: visitExpression,
|
|
|
|
one_or_more: visitExpression,
|
2016-03-11 16:18:29 +01:00
|
|
|
group: visitExpression,
|
2014-06-07 14:06:42 +02:00
|
|
|
semantic_and: visitNop,
|
|
|
|
semantic_not: visitNop,
|
2014-06-04 07:23:34 +02:00
|
|
|
rule_ref: visitNop,
|
|
|
|
literal: visitNop,
|
|
|
|
"class": visitNop,
|
|
|
|
any: visitNop
|
|
|
|
};
|
|
|
|
|
|
|
|
objects.defaults(functions, DEFAULT_FUNCTIONS);
|
|
|
|
|
|
|
|
return visit;
|
2014-05-08 11:48:56 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
module.exports = visitor;
|