How to get error messages in antlr analysis?

I wrote a grammar with antlr 4.4 as follows:

grammar CSV;

file
  :  row+ EOF
  ;

row
  :  value (Comma value)* (LineBreak | EOF)
  ;

value
  :  SimpleValueA
  |  QuotedValue
  ;

Comma
  :  ','
  ;

LineBreak
  :  '\r'? '\n'
  |  '\r'
  ;

SimpleValue
  :  ~(',' | '\r' | '\n' | '"')+
  ;

QuotedValue
  :  '"' ('""' | ~'"')* '"'
  ;

then I use antlr 4.4 to generate parser and lexer, this process is successful

after generating the classes, I wrote java code to use grammar

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;

public class Main {

    public static void main(String[] args)
    {
        String source =  "\"a\",\"b\",\"c";
        CSVLexer lex = new CSVLexer(new ANTLRInputStream(source));
        CommonTokenStream tokens = new CommonTokenStream(lex);
        tokens.fill();
        CSVParser parser = new CSVParser(tokens);
        CSVParser.FileContext file = parser.file();
    }
}

all of the above code is a parser for CSV strings for example: "a", "b", c "

Window output:

line 1:8 token recognition error at: '"c'
line 1:10 missing {SimpleValue, QuotedValue} at '<EOF>'

I want to know How can I get these errors from a method (getErrors () or ...) in encoding not as a result of an output window

Can anybody help me?

+4
source share
1 answer

ANTLR CSV IMHO, ...

  • ANTLRErrorListener. BaseErrorListener . .
  • parser.removeErrorListeners()
  • parser.addErrorListener(yourListenerInstance), .

, lexer, removeErrorListeners/addErrorListener, :

UNKNOWN_CHAR : . ;

( UNKNOWN_CHAR, ), ( , UNKNOWN_CHAR ). .

+3

All Articles