Skip to content

Instantly share code, notes, and snippets.

@nightscape
Created August 16, 2012 18:27
Show Gist options
  • Save nightscape/3372398 to your computer and use it in GitHub Desktop.
Save nightscape/3372398 to your computer and use it in GitHub Desktop.
S-Expression grammar for PEG.js
/*
* Grammar to generate an S-Expressions parser for Javascript using http://pegjs.majda.cz/
*/
start
= expression*
integer "integer"
= digits:[0-9]+ { return parseInt(digits.join(""), 10); }
expression
= (space? '(' body:body ')' space?) { return body; }
body
= body:(expression / identifier / float / integer / string / space )* { return body.filter(function(a) { return (a != ""); }) }
float
= ('+' / '-')? [0-9]+ (('.' [0-9]+) / ('e' [0-9]+))
string
= '"' content:([^"\\] / "\\" . )* '"' {
function concat(o,i){
var r=[];
for(var p in o){
r.push(o[p]);
}
return r.join("");
}
return concat(content);
}
identifier
= identifier:([a-zA-Z\=\*:] [a-zA-Z0-9_\=\*-:]*) {
function concat(o,i){
var r=[];
for(var p in o){
r.push(o[p]);
}
return r.join("");
}
return identifier.map(function(a) {return concat(a)}).join("");
}
space
= [\s\n ]+ { return ""; }
comment
= "#" .*
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment