Created
February 27, 2012 19:58
-
-
Save dmajda/1926638 to your computer and use it in GitHub Desktop.
Semantic predicates and label visibility in 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
/* | |
* 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