A1
, (). , backtrack=true , , . backtrack=true, backtracking , , , . , , backtrack=true , , , , . , .
, , . -, . :
foo : bar baz ;
bar : 'bar' ;
baz : 'baz' | /* epsilon */ ;
foo : bar baz? ;
bar : 'bar' ;
baz : 'baz' ;
.
, , true, false .., : lexer. Lexer , ( ) , ID, . .
A2
, , () .
:
grammar test;
options {
output=AST;
}
tokens {
ARRAY_EXPR;
}
start : expression;
expression : andExp;
andExp : cmpExp (And^ cmpExp)*;
cmpExp : sumExp (LessThan^ sumExp)*;
sumExp : prodExp ((Plus | Minus)^ prodExp)*;
prodExp : unaryExp (Times^ unaryExp)*;
unaryExp : '-' primaryExp
| '!' primaryExp
| primaryExp
;
primaryExp : INT primaryPrime[null]?
| 'true' primaryPrime[null]?
| 'false' primaryPrime[null]?
| 'this' primaryPrime[null]?
| (ID -> ID) (primaryPrime[new CommonTree($ID)] -> primaryPrime)?
| '('! expression ')'! primaryPrime[null]?
;
primaryPrime [CommonTree parent]
: '[' expression ']' primaryPrime[null]? -> ^(ARRAY_EXPR {parent} expression primaryPrime?)
| '.' ID '(' exprList? ')' primaryPrime[null]?
| '.length' primaryPrime[null]?
| 'new' 'int' '[' expression ']' primaryPrime[null]?
| 'new' ID '(' ')' primaryPrime[null]?
;
exprList : expression (',' expression)*;
True : 'true';
False : 'false';
This : 'this';
LessThan : '<';
Plus : '+';
Minus : '-';
Times : '*';
And : '&&';
Not : '!';
INT : '0' | ('1'..'9')('0'..'9')*;
ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*;
WS : ('\t' | ' ' | '\r' | '\n'| '\u000C') { $channel=HIDDEN; } ;
"array[2*3]" AST:

, :
import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;
public class Main {
public static void main(String[] args) throws Exception {
String source = "array[2*3]";
testLexer lexer = new testLexer(new ANTLRStringStream(source));
CommonTokenStream tokens = new CommonTokenStream(lexer);
testParser parser = new testParser(tokens);
testParser.start_return returnValue = parser.start();
CommonTree tree = (CommonTree)returnValue.getTree();
DOTTreeGenerator gen = new DOTTreeGenerator();
StringTemplate st = gen.toDOT(tree);
System.out.println(st);
}
}