-
-
Save moritz/9c8e1a5f48f3f61355dfd245a999a66c to your computer and use it in GitHub Desktop.
High-water mark error reporting in Perl 6 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
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