Extract |buildNodeVisitor|

redux
David Majda 14 years ago
parent 1279e87766
commit 4d50a37b14

@ -16,7 +16,7 @@ PEG.compiler.checks = [
return function(node) { each(node[propertyName], check); };
}
var checkFunctions = {
var check = buildNodeVisitor({
grammar:
function(node) {
for (var name in node.rules) {
@ -49,9 +49,7 @@ PEG.compiler.checks = [
literal: nop,
any: nop,
"class": nop
};
function check(node) { checkFunctions[node.type](node); }
});
check(ast);
},
@ -64,7 +62,7 @@ PEG.compiler.checks = [
check(node.expression, appliedRules);
}
var checkFunctions = {
var check = buildNodeVisitor({
grammar:
function(node, appliedRules) {
for (var name in node.rules) {
@ -114,11 +112,7 @@ PEG.compiler.checks = [
literal: nop,
any: nop,
"class": nop
};
function check(node, appliedRules) {
checkFunctions[node.type](node, appliedRules);
}
});
check(ast, []);
}

@ -90,7 +90,7 @@ PEG.compiler.emitter = function(ast) {
}
};
var emitFunctions = {
var emit = buildNodeVisitor({
grammar: function(node) {
var initializerCode = node.initializer !== null
? emit(node.initializer)
@ -710,11 +710,7 @@ PEG.compiler.emitter = function(ast) {
}
);
}
};
function emit(node, resultVar) {
return emitFunctions[node.type](node, resultVar);
}
});
return emit(ast);
};

@ -28,7 +28,7 @@ PEG.compiler.passes = [
};
}
var replaceFunctions = {
var replace = buildNodeVisitor({
grammar:
function(node, from, to) {
for (var name in node.rules) {
@ -59,11 +59,7 @@ PEG.compiler.passes = [
literal: nop,
any: nop,
"class": nop
};
function replace(node, from, to) {
replaceFunctions[node.type](node, from, to);
}
});
replace(ast, from, to);
}

@ -73,3 +73,15 @@ function quoteForRegexpClass(s) {
.replace(/\u2029/g, '\\u2029') // paragraph separator
.replace(/\n/g, '\\n') // line feed
}
/*
* Builds a node visitor -- a function which takes a node and any number of
* other parameters, calls an appropriate function according to the node type,
* passes it all its parameters and returns its value. The functions for various
* node types are passed in a parameter to |buildNodeVisitor| as a hash.
*/
function buildNodeVisitor(functions) {
return function(node) {
functions[node.type].apply(null, arguments));
}
}

Loading…
Cancel
Save