• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1use strict;
2use warnings;
3
4use lib qw( t/lib );
5
6use Test::More;
7use ANTLR::Runtime::Test;
8
9plan tests => 1;
10
11# The SimpleCalc grammar from the five minutes tutorial.
12g_test_output_is({ grammar => <<'GRAMMAR', test_program => <<'CODE', expected => <<'OUTPUT' });
13grammar SimpleCalc;
14options { language = Perl5; }
15
16tokens {
17	PLUS 	= '+' ;
18	MINUS	= '-' ;
19	MULT	= '*' ;
20	DIV	= '/' ;
21}
22
23/*------------------------------------------------------------------
24 * PARSER RULES
25 *------------------------------------------------------------------*/
26
27expr	: term ( ( PLUS | MINUS )  term )* ;
28
29term	: factor ( ( MULT | DIV ) factor )* ;
30
31factor	: NUMBER ;
32
33/*------------------------------------------------------------------
34 * LEXER RULES
35 *------------------------------------------------------------------*/
36
37NUMBER	: (DIGIT)+ ;
38
39WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ 	{ $channel = HIDDEN; } ;
40
41fragment DIGIT	: '0'..'9' ;
42GRAMMAR
43use strict;
44use warnings;
45
46use ANTLR::Runtime::ANTLRStringStream;
47use ANTLR::Runtime::CommonTokenStream;
48use ANTLR::Runtime::RecognitionException;
49use SimpleCalcLexer;
50use SimpleCalcParser;
51
52my @examples = (
53    '1',
54    '1 + 1',
55    '1 +',
56    '1 * 2 + 3',
57);
58
59foreach my $example (@examples) {
60    my $input = ANTLR::Runtime::ANTLRStringStream->new({ input => $example });
61    my $lexer = SimpleCalcLexer->new({ input => $input });
62    my $tokens = ANTLR::Runtime::CommonTokenStream->new({ token_source => $lexer });
63    my $parser = SimpleCalcParser->new({ input => $tokens });
64    eval {
65        $parser->expr();
66        if ($parser->get_number_of_syntax_errors() == 0) {
67            print "$example: good\n";
68        }
69        else {
70            print "$example: bad\n";
71        }
72    };
73    if (my $ex = ANTLR::Runtime::RecognitionException->caught()) {
74        print "$example: error\n";
75    } elsif ($ex = Exception::Class->caught()) {
76        print "$example: error: $ex\n";
77        ref $ex ? $ex->rethrow() : die $ex;
78    }
79}
80CODE
811: good
821 + 1: good
831 +: bad
841 * 2 + 3: good
85OUTPUT
86
87__END__
88