Skip to content

Instantly share code, notes, and snippets.

@Turbo87
Created January 31, 2017 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Turbo87/55dcb6c45efb6f5668644f41673cb459 to your computer and use it in GitHub Desktop.
Save Turbo87/55dcb6c45efb6f5668644f41673cb459 to your computer and use it in GitHub Desktop.
Handlebars grammar for nearley.js
@builtin "string.ne"
@builtin "whitespace.ne"
MustacheStatement -> OPEN _ _Path (__ _Param):* (__ Hash):? _ CLOSE {% (data, location) => ({
type: 'MustacheStatement',
path: data[2],
params: data[3].map(it => it[1]),
hash: data[4] && data[4][1],
range: { start: location, end: data[6].range.end },
}) %}
OPEN -> "{{"
CLOSE -> "}}" {% (data, location) => ({ range: { start: location, end: location + data[0].length } }) %}
OPEN_SEXPR -> "("
CLOSE_SEXPR -> ")"
SEP -> "."
EQUALS -> "="
ID -> [^\s!"#%-,\.\/;->@\[-\^`\{-~]:+ {% id %}
STRING -> dqstring {% id %} | sqstring {% id %}
NUMBER -> "-":? [0-9]:+ ("." [0-9]:+):? {% id %}
BOOLEAN -> "true" | "false" {% id %}
UNDEFINED -> "undefined" {% id %}
NULL -> "null" {% id %}
_Path -> PathExpression {% id %}
| StringLiteral {% id %}
| NumberLiteral {% id %}
| BooleanLiteral {% id %}
| UndefinedLiteral {% id %}
| NullLiteral {% id %}
PathExpression -> _PathSegments {% d => ({
type: 'PathExpression',
original: d[0].map(it => it.name).join('.'), parts: d[0]
}) %}
_PathSegments -> Identifier (SEP Identifier):* {% d => [d[0]].concat(d[1].map(it => it[1])) %}
_Param -> _Path {% id %}
| SubExpression {% id %}
SubExpression -> OPEN_SEXPR _ _Path (__ _Param):* (__ Hash):? _ CLOSE_SEXPR {% d => ({
type: 'SubExpression',
path: d[2],
params: d[3].map(it => it[1]),
hash: d[4] && d[4][1],
}) %}
Hash -> HashPair (_ HashPair):* {%d => ({
type: 'Hash',
pairs: [d[0]].concat(d[1].map(it => it[1])),
}) %}
Identifier -> ID {% (data, location, reject) => {
let name = data[0].join("");
if (['true', 'false', 'undefined', 'null'].indexOf(name) === -1) {
return { type: 'Identifier', name };
} else {
return reject;
}
} %}
HashPair -> Identifier EQUALS _Param {% d => ({ type: 'HashPair', key: d[0], value: d[2] }) %}
StringLiteral -> STRING {% d => ({ type: 'StringLiteral', original: d[0], value: d[0] }) %}
NumberLiteral -> NUMBER {% d => ({ type: 'StringLiteral', original: d[0], value: parseFloat(d[0]) }) %}
BooleanLiteral -> BOOLEAN {% d => ({ type: 'StringLiteral', original: d[0], value: d[0] === 'true' }) %}
UndefinedLiteral -> UNDEFINED {% d => ({ type: 'StringLiteral', original: d[0], value: undefined }) %}
NullLiteral -> NULL {% d => ({ type: 'StringLiteral', original: d[0], value: null }) %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment