Debian Codegraph @

t/sl_tut2.t

raw
1 #!/usr/bin/perl
2 # Copyright 2022 Jeffrey Kegler
3 # This file is part of Marpa::R2. Marpa::R2 is free software: you can
4 # redistribute it and/or modify it under the terms of the GNU Lesser
5 # General Public License as published by the Free Software Foundation,
6 # either version 3 of the License, or (at your option) any later version.
7 #
8 # Marpa::R2 is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 # Lesser General Public License for more details.
12 #
13 # You should have received a copy of the GNU Lesser
14 # General Public License along with Marpa::R2. If not, see
15 # http://www.gnu.org/licenses/.
16
17 # Tutorial 2 synopsis
18
19 use 5.010001;
20 use strict;
21 use warnings;
22
23 use Test::More tests => 1;
24
25 use lib 'inc';
26 use Marpa::R2::Test;
27
28 ## no critic (ErrorHandling::RequireCarping);
29
30 # Marpa::R2::Display
31 # name: Tutorial 2 synopsis
32
33 use Marpa::R2;
34
35 my $dsl = <<'END_OF_DSL';
36 :default ::= action => [name,values]
37 lexeme default = latm => 1
38
39 Calculator ::= Expression action => ::first
40
41 Factor ::= Number action => ::first
42 Term ::=
43 Term '*' Factor action => do_multiply
44 | Factor action => ::first
45 Expression ::=
46 Expression '+' Term action => do_add
47 | Term action => ::first
48 Number ~ digits
49 digits ~ [\d]+
50 :discard ~ whitespace
51 whitespace ~ [\s]+
52 END_OF_DSL
53
54 my $grammar = Marpa::R2::Scanless::G->new( { source => \$dsl } );
55 my $recce = Marpa::R2::Scanless::R->new(
56 { grammar => $grammar, semantics_package => 'My_Actions' } );
57 my $input = '42 * 1 + 7';
58 my $length_read = $recce->read( \$input );
59
60 die "Read ended after $length_read of ", length $input, " characters"
61 if $length_read != length $input;
62
63 if ( my $ambiguous_status = $recce->ambiguous() ) {
64 chomp $ambiguous_status;
65 die "Parse is ambiguous\n", $ambiguous_status;
66 }
67
68 my $value_ref = $recce->value;
69 my $value = ${$value_ref};
70
71 sub My_Actions::do_add {
72 my ( undef, $t1, undef, $t2 ) = @_;
73 return $t1 + $t2;
74 }
75
76 sub My_Actions::do_multiply {
77 my ( undef, $t1, undef, $t2 ) = @_;
78 return $t1 * $t2;
79 }
80
81 # Marpa::R2::Display::End
82
83 Test::More::is( $value, 49, 'Tutorial 2 synopsis value' );
84
85 1; # In case used as "do" file
86
87 # Local Variables:
88 # mode: cperl
89 # cperl-indent-level: 4
90 # fill-column: 100
91 # End:
92 # vim: expandtab shiftwidth=4: