java compiler/Compiler1.javajava compiler/Compiler1.java
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
publicclassTest1{
publicstaticvoid main(String[] args)throwsRecognitionException{
CharStream stream =
newANTLRStringStream("program XLSample1 =\r\n"+
"/*\r\n"+
" constant one : Integer := 1;\r\n"+
" constant two : Integer := 2 * 3;\r\n"+
" var x, y, z : Integer := 42;\r\n"+
"*/\r\n"+
"\r\n"+
" procedure foo() =\r\n"+
" var x : Integer := 2;\r\n"+
" begin\r\n"+
" end foo.\r\n"+
" procedure fee(y : Integer) =\r\n"+
" var x : Integer := 2;\r\n"+
" begin\r\n"+
" end fee.\r\n"+
" function fie(y : Integer) : Integer =\r\n"+
" var x : Integer := 2;\r\n"+
" begin\r\n"+
" return y;\r\n"+
" end fie.\r\n"+
"begin\r\n"+
"end XLSample1.");
SampleLexer lexer =newSampleLexer(stream);
TokenStream tokenStream =newCommonTokenStream(lexer);
SampleParser parser =newSampleParser(tokenStream);
parser.program();
System.out.println("ok");
}
}
java compiler/Compiler2.javajava compiler/Compiler2.java
import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.TokenStream;
publicclassTest2{
publicstaticvoid main(String[] args)throwsRecognitionException{
CharStream stream =
newANTLRStringStream("3 * (2 + 4) * 3");
Sample2Lexer lexer =newSample2Lexer(stream);
TokenStream tokenStream =newCommonTokenStream(lexer);
Sample2Parser parser =newSample2Parser(tokenStream);
int result = parser.evaluator();
System.out.println("ok - result is "+ result);
}
}
java compiler/src1.g4
grammar scr1;
options {
language = Java;
}
@header {
package a.b.c;
}
@lexer::header {
package a.b.c;
}
program
: 'program' IDENT '='
(constant | variable | function | procedure | typeDecl)*
'begin'
statement*
'end' IDENT '.'
;
constant
: 'constant' IDENT ':' type ':=' expression ';'
;
variable
: 'var' IDENT (',' IDENT)* ':' type (':=' expression)? ';'
;
type
: 'Integer'
| 'Boolean'
| 'String'
| 'Char'
| IDENT
| typeSpec
;
typeDecl
: 'type' IDENT '=' typeSpec ';'
;
typeSpec
: arrayType
| recordType
| enumType
;
arrayType
: 'array' '[' INTEGER '..' INTEGER ']' 'of' type
;
recordType
: 'record' field* 'end' 'record'
;
field
: IDENT ':' type ';'
;
enumType
: '<' IDENT (',' IDENT)* '>'
;
statement
: assignmentStatement
| ifStatement
| loopStatement
| whileStatement
| procedureCallStatement
;
procedureCallStatement
: IDENT '(' actualParameters? ')' ';'
;
actualParameters
: expression (',' expression)*
;
ifStatement
: 'if' expression 'then' statement+
('elsif' expression 'then' stateme ...