1 /** Demonstrates how semantic predicates get hoisted out of the rule in 2 * which they are found and used in other decisions. This grammar illustrates 3 * how predicates can be used to distinguish between enum as a keyword and 4 * an ID *dynamically*. :) 5 6 * Run "java org.antlr.Tool -dfa t.g" to generate DOT (graphviz) files. See 7 * the T_dec-1.dot file to see the predicates in action. 8 */ 9 grammar T; 10 11 options { 12 language=ObjC; 13 } 14 15 @memVars { 16 /* With this true, enum is seen as a keyword. False, it's an identifier */ 17 BOOL enableEnum; 18 } 19 20 @init { 21 enableEnum = NO; 22 } 23 24 stat: identifier {NSLog(@"enum is an ID");} 25 | enumAsKeyword {NSLog(@"enum is a keyword");} 26 ; 27 28 identifier 29 : ID 30 | enumAsID 31 ; 32 33 enumAsKeyword : {enableEnum}? 'enum' ; 34 35 enumAsID : {!enableEnum}? 'enum' ; 36 37 ID : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')* 38 ; 39 40 INT : ('0'..'9')+ 41 ; 42 43 WS : ( ' ' 44 | '\t' 45 | '\r' 46 | '\n' 47 )+ 48 { $channel=99; } 49 ; 50