Skip to content

Instantly share code, notes, and snippets.

@mcasimir
Created January 17, 2012 18:00
Show Gist options
  • Save mcasimir/1627855 to your computer and use it in GitHub Desktop.
Save mcasimir/1627855 to your computer and use it in GitHub Desktop.
Passing parameters to PEG.js Parser
{
var thisParser = this;
function resolveSymbol(parser, sym){
return (parser.symbols || {})[sym];
}
function flatten(array){
var flat = [];
for (var i = 0, l = array.length; i < l; i++){
var type = Object.prototype.toString.call(array[i]).split(' ').pop().split(']').shift().toLowerCase();
if (type) { flat = flat.concat(/^(array|collection|arguments|object)$/.test(type) ? flatten(array[i]) : array[i]); }
}
return flat;
}
}
start
= Variable
Variable
= symbol:([A-z_\$][A-z0-9_\$]*) {
return {
value: resolveSymbol(thisParser, flatten(symbol).join(""))
}
}
var FileSystem = require('fs');
var Path = require('path');
var PegJs = require("pegjs");
var grammar = FileSystem.readFileSync(Path.resolve(__dirname, "./grammar.pegjs")).toString();
var parser = PegJs.buildParser(grammar).toString());
parser.symbols = {x: 5};
parser.parse("x");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment