[antlr-interest] how to get the value of an identifier
John B. Brodie
jbb at acm.org
Tue Sep 29 08:51:09 PDT 2009
Greetings!
On Tue, 2009-09-29 at 16:54 +0200, Thierry USO wrote:
> A complete example which shows my problem.
>
....remainder snipped....
Your grammar does not handle New-Line characters ('\n' and possibly
'\r'). You should have received many "no viable alternative at ..."
error messages....
As others have stated you should:
1) make LETTER and DIGIT fragement rules.
2) make ConstDef be a parser rule
3) when you do 2) you should add a WHITESPACE lexer rule, perhaps
putting the WHITESPACE (including new-lines) on the HIDDEN channel (e.g.
{ $channel = HIDDEN; } )
attached is a complete example with the above suggestions applied. Oh by
the way.... in my example I construct an AST during the parse and then
print the AST at the end; rather than doing the System.out stuff during
the parse....
Hope this helps...
-jbb
-------------- next part --------------
grammar ADL; // Rally Application Development Language
options {
output = AST;
ASTLabelType = CommonTree;
}
@members {
private static final String [] x = new String[]{
"\nCONST str1 = \"ok\" ;\n str2=\"ko\";\n str3 = \"end\";"
};
public static void main(String [] args) {
for( int i = 0; i < x.length; ++i ) {
try {
System.out.println("about to parse:`"+x[i]+"`");
ADLLexer lexer = new ADLLexer(new ANTLRStringStream(x[i]));
CommonTokenStream tokens = new CommonTokenStream(lexer);
ADLParser parser = new ADLParser(tokens);
ADLParser.start_return p_result = parser.start();
CommonTree ast = p_result.tree;
if( ast == null ) {
System.out.println("resultant tree: is NULL");
} else {
System.out.println("resultant tree: " + ast.toStringTree());
}
System.out.println();
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
start : constant_definition EOF!;
constant_definition : constDef ;
constDef : CONST ( Identifier EQUAL CharString SEMICOLON )+ ;
CharString : '"' (LETTER)+ '"' ;
CONST : 'CONST' ;
fragment LETTER : ('a'..'z'|'A'..'Z') ;
fragment DIGIT : ('0'..'9') ;
SEMICOLON : ';' ;
EQUAL : '=' ;
Identifier : LETTER (LETTER|'_'|DIGIT)+ ;
WHITESPACE : (' '|'\t')+ { $channel = HIDDEN; } ;
NEWLINE : ('\r'|'\n')+ { $channel = HIDDEN; } ;
More information about the antlr-interest
mailing list