在 Marpa 中处理错误有两种可能性。
“红宝石拖鞋”解析
Marpa 在扫描过程中维护了很多上下文。我们可以使用这个上下文,以便解析器需要一些令牌,并且我们可以决定是否要将它提供给 Marpa,即使它不在输入中。例如,考虑一种要求任何语句以分号结尾的编程语言。然后,我们可以使用 Ruby Slippers 技术在特定位置插入分号,例如在行尾或右大括号之前:
use strict;
use warnings;
use Marpa::R2;
use Data::Dump 'dd';
my $grammar = Marpa::R2::Scanless::G->new({
source => \q{
:discard ~ ws
Block ::= Statement+ action => ::array
Statement ::= StatementBody (STATEMENT_TERMINATOR) action => ::first
StatementBody ::= 'statement' action => ::first
| ('{') Block ('}') action => ::first
STATEMENT_TERMINATOR ~ ';'
event ruby_slippers = predicted STATEMENT_TERMINATOR
ws ~ [\s]+
},
});
my $recce = Marpa::R2::Scanless::R->new({ grammar => $grammar });
my $input = q(
statement;
{ statement }
statement
statement
);
for (
$recce->read(\$input);
$recce->pos < length $input;
$recce->resume
) {
ruby_slippers($recce, \$input);
}
ruby_slippers($recce, \$input);
dd $recce->value;
sub ruby_slippers {
my ($recce, $input) = @_;
my %possible_tokens_by_length;
my @expected = @{ $recce->terminals_expected };
for my $token (@expected) {
pos($$input) = $recce->pos;
if ($token eq 'STATEMENT_TERMINATOR') {
# fudge a terminator at the end of a line, or before a closing brace
if ($$input =~ /\G \s*? (?: $ | [}] )/smxgc) {
push @{ $possible_tokens_by_length{0} }, [STATEMENT_TERMINATOR => ';'];
}
}
}
my $max_length = 0;
for (keys %possible_tokens_by_length) {
$max_length = $_ if $_ > $max_length;
}
if (my $longest_tokens = $possible_tokens_by_length{$max_length}) {
for my $lexeme (@$longest_tokens) {
$recce->lexeme_alternative(@$lexeme);
}
$recce->lexeme_complete($recce->pos, $max_length);
return ruby_slippers($recce, $input);
}
}
在该ruby_slippers
函数中,您还可以计算您需要多久伪造一个令牌。如果该计数超过某个值,您可以通过抛出错误来放弃解析。
跳过输入
如果您的输入可能包含无法解析的垃圾,您可以尝试跳过如果没有找到词素的话。为此,该$recce->resume
方法采用可选的位置参数,正常解析将在其中恢复。
use strict;
use warnings;
use Marpa::R2;
use Data::Dump 'dd';
use Try::Tiny;
my $grammar = Marpa::R2::Scanless::G->new({
source => \q{
:discard ~ ws
Sentence ::= WORD+ action => ::array
WORD ~ 'foo':i | 'bar':i | 'baz':i | 'qux':i
ws ~ [\s]+
},
});
my $recce = Marpa::R2::Scanless::R->new({ grammar => $grammar });
my $input = '1) Foo bar: baz and qux, therefore qux (foo!) implies bar.';
try { $recce->read(\$input) };
while ($recce->pos < length $input) {
# ruby_slippers($recce, \$input);
try { $recce->resume } # restart at current position
catch { try { $recce->resume($recce->pos + 1) } }; # advance the position
# if both fail, we go into a new iteration of the loop.
}
dd $recce->value;
虽然可以使用匹配任何内容的词位来实现相同的效果:discard
,但是在我们的客户端代码中进行跳过允许我们在必须做太多的伪造时中止解析。