Skip to content

Instantly share code, notes, and snippets.

@dmajda
Created February 27, 2012 19:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dmajda/1926638 to your computer and use it in GitHub Desktop.
Save dmajda/1926638 to your computer and use it in GitHub Desktop.
Semantic predicates and label visibility in PEG.js
/*
* Task: Parse even numbers in PEG.js (http://pegjs.majda.cz).
*
* Solution: Let's parse all numbers and reject odd ones using a semantic
* predicate -- an arbitrary piece of code that returns true (meaning "continue
* parsing") or false (meaning "halt parsing").
*
* This solution wouldn't work before commit a2af1fe612 because predicates
* didn't have access to labeled expressions in the grammar as variables
* (without ugly workarounds). But they have the access now and the solution
* works.
*/
// Whitespace-separated numbers
numbers = number (" \t\r\n"+ number)*
// One (even) number
number = digits:[0-9]+ &{ return parseInt(digits.join(""), 10) % 2 === 0; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment