Skip to content

Instantly share code, notes, and snippets.

@moritz
Created August 6, 2017 14:01
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 moritz/944e304f0d64e54b1a09e198e5b969a2 to your computer and use it in GitHub Desktop.
Save moritz/944e304f0d64e54b1a09e198e5b969a2 to your computer and use it in GitHub Desktop.
Dynamic hash variables in a grammar
my $valid = Q:to/EOF/;
a = 1
b = 2
{
c = a, 5, b
}
EOF
my $invalid = Q:to/EOF/;
a = 1
{
b = 2
}
c = a, 5, b
EOF
grammar VariableLists {
token TOP {
:my %*SYMBOLS;
<statement>*
}
token ws { <!ww> \h* }
token statement {
| <declaration>
| <block>
}
rule declaration {
<identifier>
{ %*SYMBOLS{ $<identifier> } := True }
'=' <termlist>
\n
}
rule block {
'{' \n*
:my %*SYMBOLS = CALLER::<%*SYMBOLS>;
<statement>*
'}' \n*
}
rule termlist { <term> * % ',' }
token term { <variable> | <number> }
token variable {
<identifier>
<?{ %*SYMBOLS{ $<identifier> } }>
}
token number { \d+ }
token identifier { <:alpha> \w* }
}
use Test;
ok VariableLists.parse($valid);
nok VariableLists.parse($invalid), 'Undeclared variables cause parse fail';;
done-testing;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment