Permalink
Browse files

Extract |buildNodeVisitor|

  • Loading branch information...
1 parent 1279e87 commit 4d50a37b14ef4b7c254de0b66eafc8e5771037f0 @dmajda dmajda committed Aug 17, 2010
Showing with 20 additions and 22 deletions.
  1. +4 −10 src/checks.js
  2. +2 −6 src/emitter.js
  3. +2 −6 src/passes.js
  4. +12 −0 src/utils.js
View
@@ -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, []);
}
View
@@ -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);
};
View
@@ -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);
}
View
@@ -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));
+ }
+}

0 comments on commit 4d50a37

Please sign in to comment.