tags:

views:

223

answers:

1

I'm still on the learning path with ANTLR. I've built a grammar and for the most part it does what I expect, but I need it to be able to run silently (no output to stdout or stderr).

Grammar

grammar MyPredicate;

options 
{
    output=AST; 
} 

parse   :   expression EOF
    ;

expression 
    :   field WS? OPERATOR_BINARY WS? value
    ;

OPERATOR_BINARY
    :   '=' | '<' | '>' | '<=' | '>=' | '!=' | 'has'
    ;

value   :   VALUE_STRING
    |   VALUE_NUMERIC
    |   VALUE_BOOLEAN
    ;

VALUE_STRING
    :   '""'
    |   '"' (ESC_SEQ | ~('\\'|'"'))+ '"'
    ;

VALUE_NUMERIC
    :   ('0'..'9')+ ('.' ('0'..'9')+)?
    ;

VALUE_BOOLEAN 
    :   'true'
    |   'false'
    ;

field   :   FIELD_NAME
    ;

FIELD_NAME 
    :   ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*
    ;

ESC_SEQ
    :   '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
    ;

WS  :   (' ' | '\t' | '\r' | '\n') {skip();}
    ;

Java

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
    public static void main(String[] args) throws Exception {
        MyPredicateParser parser = new MyPredicateParser(new CommonTokenStream(new MyPredicateLexer(new ANTLRStringStream(args[0]))));
        MyPredicateParser.parse_return r = parser.parse();
        parser.parse();

        if ( r.tree!=null ) {
            System.out.println(((Tree)r.tree).toStringTree());
            ((CommonTree)r.tree).sanityCheckParentAndChildIndexes();
        }
    }
}

Input

a = 1

Output

line 0:-1 mismatched input '<EOF>' expecting FIELD_NAME
a = 1 null

I'm not sure why I get the EOF error. From what I understand my grammar is parsing correctly, and I get the error after the "parse" parser is evaluated, but that node is looking for the EOF. Using ANTLR 3.2

+4  A: 

The problem is that you're calling parse() twice in your Main class. Remove the line:

parser.parse();

leaving only:

MyPredicateParser.parse_return r = parser.parse();

in place.

Bart Kiers
Wow. Is there a way to remove a question on the basis that I was retarded?Thanks a million
Hounshell