Skip to content

Instantly share code, notes, and snippets.

@jhusain
Created October 29, 2016 03:29
Show Gist options
  • Save jhusain/c70adc81dcb2e2ed77f8f90296ef5fde to your computer and use it in GitHub Desktop.
Save jhusain/c70adc81dcb2e2ed77f8f90296ef5fde to your computer and use it in GitHub Desktop.
PEG grammer for pattern match syntax. Forked from JSON grammer.
JSON_text
= ws value:value ws { return value; }
begin_array = ws "[" ws
begin_object = ws "{" ws
end_array = ws "]" ws
end_object = ws "}" ws
name_separator = ws ":" ws
value_separator = ws "," ws
ws "whitespace" = [ \t\n\r]*
identChar = [a-zA-Z_]
ident = value:identChar+ { return value.join('') }
identifier = name:ident { return { type: "identifier", name: name } }
// ----- 3. Values -----
value
= false
/ null
/ true
/ object
/ array
/ number
/ string
false = "false" { return false; }
null = "null" { return null; }
true = "true" { return true; }
// ----- 4. Objects -----
object
= begin_object
members:(
head:member
tail:(value_separator m:member { return m; })*
{
var entries = [];
[head].concat(tail).forEach(function(element) {
entries.push(element);
});
return { type: "object", entries: entries };
}
)?
end_object
{ return members !== null ? members: {}; }
name = string
/ id:identifier "?" {
id.optional = true;
return id;
}
/ identifier
/ "[" ws value:value ws "]" {return value}
member
= name:name name_separator alias:ident ws value:value {
console.log(name,alias,value)
return [ name, {type: "alias", name: alias, value: value } ]
}
/ name:name name_separator value:value {
return [name, value];
}
/ name:name { return name; }
/ "..." id:identifier {
id.spread = true;
return id;
}
// ----- 5. Arrays -----
array
= begin_array
values:(
head:value
tail:(value_separator v:value { return v; })*
{ return [head].concat(tail); }
)?
end_array
{ return values !== null ? values : []; }
// ----- 6. Numbers -----
number "number"
= minus? int frac? exp? { return parseFloat(text()); }
decimal_point
= "."
digit1_9
= [1-9]
e
= [eE]
exp
= e (minus / plus)? DIGIT+
frac
= decimal_point DIGIT+
int
= zero / (digit1_9 DIGIT*)
minus
= "-"
plus
= "+"
zero
= "0"
// ----- 7. Strings -----
string "string"
= quotation_mark chars:char* quotation_mark { return chars.join(""); }
char
= unescaped
/ escape
sequence:(
'"'
/ "\\"
/ "/"
/ "b" { return "\b"; }
/ "f" { return "\f"; }
/ "n" { return "\n"; }
/ "r" { return "\r"; }
/ "t" { return "\t"; }
/ "u" digits:$(HEXDIG HEXDIG HEXDIG HEXDIG) {
return String.fromCharCode(parseInt(digits, 16));
}
)
{ return sequence; }
escape
= "\\"
quotation_mark
= '"'
unescaped
= [^\0-\x1F\x22\x5C]
// ----- Core ABNF Rules -----
// See RFC 4234, Appendix B (http://tools.ietf.org/html/rfc4234).
DIGIT = [0-9]
HEXDIG = [0-9a-f]i
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment