[antlr-interest] inline template output

Michael West quagly at me.com
Sat Oct 23 07:56:16 PDT 2010


I am not getting any output when using inline template.   I have a trivial grammar that just has assignments and add integers with template output.  I want to output "assignment here" for each assignment and "print here" for each print statement.  Since the code is so small I put everything inline here:

input is:
---------------------------------
X = 1;
print (X);

grammer is:
---------------------------------
grammar First;
options { output=template; }
// START rules  
// statements can cross lines
prog: (stat ';') + ;

// a statment is either an addition expression or an assignment
stat: ID '=' expr  -> template() "assignment here"
    | PRINT '('  expr ')' -> template() "print here"
    ;

// an expression is 2 or more IDs or INTs added together
expr: atom ( '+' atom )*
    ;

// we can only add ints and ids 
atom: INT
    | ID
    ;

// END rules  


// START:tokens
PRINT : 'print';

SL_COMMENT : '//' .* '\n' {skip();} ;

ML_COMMENT
    :   '/*' (options {greedy=false;} : .)* '*/' {skip();} ;

/** Match identifiers that must start with '_' or a letter.  The first 
 * characters are followed by zero or more letters, digits, or '_'
 */
ID  :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0..9')* ;
INT :   '0'..'9'+ ;
WS  :   (' '|'\t'|'\n'|'\r')+ {skip();} ;

// END:tokens

java test code is:
---------------------------------

import org.antlr.runtime.*;
import java.io.FileReader;

public class Test {
    public static void main(String[] args) throws Exception {
        CharStream input = null;
        // Pick an input stream (filename from commandline or stdin)
        if ( args.length>0 ) input = new ANTLRFileStream(args[0]);
        else input = new ANTLRInputStream(System.in);
        // Create the lexer
        FirstLexer lex = new FirstLexer(input);
        // Create a stream of tokens between lexer and parser
        CommonTokenStream tokens = new CommonTokenStream(lex);
        // Create the parser, attaching it to the token stream
        FirstParser p = new FirstParser(tokens);
        p.prog();   // launch parser at rule prog
    }
}






More information about the antlr-interest mailing list