-
-
Save janvarev/a13ac89935da45ac63892d234687ca25 to your computer and use it in GitHub Desktop.
S-Expression grammar for PEG.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Grammar to generate an S-Expressions parser for Javascript using http://pegjs.majda.cz/ | |
* Example: (+ 1 2) (car (quote (1 2 "test"))) | |
* Features: | |
- backslash symbols ("quote\"here"), | |
- one-line comments starts from ";" | |
- add "__" for identifiers - convert (car (quote (1 2 "three"))) to ["__car",["__quote",[1,2,"three"]]] | |
-- to change behavior replace | |
return "__"+identifier.map(function(a) {return concat(a)}).join(""); | |
to | |
return identifier.map(function(a) {return concat(a)}).join(""); | |
*/ | |
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 / comment )* { return body.filter(function(a) { return (a != ""); }) } | |
float | |
= ('+' / '-')? [0-9]+ (('.' [0-9]+) / ('e' [0-9]+)) | |
/* ----- 7. Strings with quotation - from JSON parsing ----- */ | |
string "string" | |
= quotation_mark chars:char* quotation_mark { return chars.join(""); } | |
char | |
= unescaped | |
/ escape | |
sequence:( | |
'"' | |
/ "\\" | |
/ "/" | |
) | |
{ return sequence; } | |
escape = "\\" | |
quotation_mark = '"' | |
unescaped = [\x20-\x21\x23-\x5B\x5D-\u10FFFF] | |
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\t ]+ { return ""; } | |
comment | |
= (";" chars:char* [\n\r]) { return ""; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment