1 use strict; 2 use warnings; 3 4 use lib qw( t/lib ); 5 6 use Test::More; 7 use ANTLR::Runtime::Test; 8 9 plan tests => 1; 10 11 # The SimpleCalc grammar from the five minutes tutorial. 12 g_test_output_is({ grammar => <<'GRAMMAR', test_program => <<'CODE', expected => <<'OUTPUT' }); 13 grammar SimpleCalc; 14 options { language = Perl5; } 15 16 tokens { 17 PLUS = '+' ; 18 MINUS = '-' ; 19 MULT = '*' ; 20 DIV = '/' ; 21 } 22 23 /*------------------------------------------------------------------ 24 * PARSER RULES 25 *------------------------------------------------------------------*/ 26 27 expr : term ( ( PLUS | MINUS ) term )* ; 28 29 term : factor ( ( MULT | DIV ) factor )* ; 30 31 factor : NUMBER ; 32 33 /*------------------------------------------------------------------ 34 * LEXER RULES 35 *------------------------------------------------------------------*/ 36 37 NUMBER : (DIGIT)+ ; 38 39 WHITESPACE : ( '\t' | ' ' | '\r' | '\n'| '\u000C' )+ { $channel = HIDDEN; } ; 40 41 fragment DIGIT : '0'..'9' ; 42 GRAMMAR 43 use strict; 44 use warnings; 45 46 use ANTLR::Runtime::ANTLRStringStream; 47 use ANTLR::Runtime::CommonTokenStream; 48 use ANTLR::Runtime::RecognitionException; 49 use SimpleCalcLexer; 50 use SimpleCalcParser; 51 52 my @examples = ( 53 '1', 54 '1 + 1', 55 '1 +', 56 '1 * 2 + 3', 57 ); 58 59 foreach 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 } 80 CODE 81 1: good 82 1 + 1: good 83 1 +: bad 84 1 * 2 + 3: good 85 OUTPUT 86 87 __END__ 88