Skip to content

Instantly share code, notes, and snippets.

@moritz
Created August 19, 2017 16:14
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/9c8e1a5f48f3f61355dfd245a999a66c to your computer and use it in GitHub Desktop.
Save moritz/9c8e1a5f48f3f61355dfd245a999a66c to your computer and use it in GitHub Desktop.
High-water mark error reporting in Perl 6 grammar
grammar MathExpression {
method parse($target, |c) {
my $*HIGHWATER = 0;
my $*LASTRULE;
my $match = callsame;
self.error($target) unless $match;
return $match;
}
token TOP { <sum> }
rule sum { <multiplication>+ % '+' }
rule multiplication { <term>+ % '*' }
rule term { <number> | <parenthesized> }
rule parenthesized {
'(' <sum> ')'
}
token number { \d+ }
method ws() {
if self.pos > $*HIGHWATER {
$*HIGHWATER = self.pos;
$*LASTRULE = callframe(1).code.name;
}
callsame;
}
method error($target) {
my $parsed = $target.substr(0, $*HIGHWATER).trim-trailing;
my $line-no = $parsed.lines.elems;
my $msg = "Cannot parse mathematical expression";
$msg ~= "; error in rule $*LASTRULE" if $*LASTRULE;
die "$msg at line $line-no";
}
}
say MathExpression.parse("1 + ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment