Created
November 27, 2015 15:00
-
-
Save dmajda/04002578dd41ae8190fc to your computer and use it in GitHub Desktop.
Simple intentation-based language PEG.js grammar
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
/* | |
* Simple Intentation-Based Language PEG.js Grammar | |
* ================================================ | |
* | |
* Describes a simple indentation-based language. A program in this language is | |
* a possibly empty list of the following statements: | |
* | |
* * S (simple) | |
* | |
* Consists of the letter "S". | |
* | |
* * I (indent) | |
* | |
* Consists of the letter "I", optionally followed by a newline and a list | |
* of statements indented by one indentation level (2 spaces) relative to | |
* the I statement itself. | |
* | |
* Statements are terminated by a newline or EOF. | |
* | |
* Example: | |
* | |
* I | |
* S | |
* I | |
* S | |
* S | |
* | |
* The grammar needs to be compiled without caching. | |
*/ | |
{ | |
var INDENT_STEP = 2; | |
var indentLevel = 0; | |
} | |
Start | |
= Statements | |
Statements | |
= Statement* | |
Statement | |
= Samedent statement:(S / I) { return statement; } | |
S | |
= "S" EOS { | |
return "S"; | |
} | |
I | |
= "I" EOL Indent statements:Statements Dedent { | |
return statements; | |
} | |
/ "I" EOS { | |
return []; | |
} | |
Samedent "correct indentation" | |
= spaces:" "* &{ return spaces.length === indentLevel * INDENT_STEP; } | |
Indent | |
= &{ indentLevel++; return true; } | |
Dedent | |
= &{ indentLevel--; return true; } | |
EOS | |
= EOL | |
/ EOF | |
EOL | |
= "\n" | |
EOF | |
= !. |
This really is beautiful. Been looking at this for years now and finally got it! Thank you!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Beautiful :) Would love to see some more advanced examples building on this foundation!!