Skip to content

Instantly share code, notes, and snippets.

@jakubkulhan
Created July 28, 2012 10:42
Show Gist options
  • Save jakubkulhan/3192844 to your computer and use it in GitHub Desktop.
Save jakubkulhan/3192844 to your computer and use it in GitHub Desktop.
Python style indentation parser in PEG.js
// do not use result cache, nor line and column tracking
{ var indentStack = [], indent = ""; }
start
= INDENT? lines:( blank / line )*
{ return lines; }
line
= SAMEDENT line:(!EOL c:. { return c; })+ EOL?
children:( b:blank* INDENT c:( blank / line )* DEDENT { return b.concat(c); })?
{ return [line.join(""), children === "" ? [] : children]; }
blank
= [ \t]* EOL
{ return undefined; }
EOL
= "\r\n" / "\n" / "\r"
SAMEDENT
= i:[ \t]* &{ return i.join("") === indent; }
INDENT
= i:[ \t]+ &{ return i.length > indent.length; }
{ indentStack.push(indent); indent = i.join(""); pos = offset; }
DEDENT
= { indent = indentStack.pop(); }
@kristianmandrup
Copy link

Tried it in PEG.j online:

Line 29, column 5: Expected "!", "$", "&", "(", ".", character class, comment, end of line, identifier, literal, or whitespace but "{" found.

Any idea what could be the problem and how to fix it? Thanx.

@nilslindemann
Copy link

nilslindemann commented Jun 17, 2019

I was also not able to get this running. This example works well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment