1

I'm very new to ANTLR and I am currently using the ANTLRWorks 2 plugin for Netbeans IDE 7.3 to visualize my grammar files for ANTLR 4.1.

What I am trying to do is parse a text file with line separated dollar values and return them all in a one-dimensional array of doubles "double[]."

For example say I have a file values.txt which contains:...

12.40
16.91
18.00
17.97
12.85

...I want to use the ANTLR generated **Parser.parseMethod(tokens)* to return an array. So the return value would be {12.4,16.91,18.00,17.85,12.85}

I attempted to adapt this method I found by a similar question answered here - Antlr Array Help -, and settle on working with a list, resulting in the following code:

grammar Values;

parse returns [List<Double> numbers]
@init {
  $numbers = new ArrayList<Double>();
}
  :  (line {$numbers.add($line.row);})* EOF
  ;

line returns [Double row]
@init {
  $row = new Double(0.0);
}
  :  (Number {$row = Double.parseDouble($Number.text);})+ (LineBreak | EOF)
  ;

fragment Digit : ('0'..'9')+ ;
Number : Digit '.' Digit ;
Space
  :  (' ' | '\t') -> channel(HIDDEN)
  ;

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

But once this grammar file is generated the parse() method returns a "ParseContext" object...

public final ParseContext parse() throws RecognitionException {...}

...which I do not know how to use. And I do not know why ParseContext is created.

1 Answer 1

1

ANTLR 4 generates a context class for every rule which is used to represent invocations of that rule in the final parse tree. The name is derived from the rule name, so rule parse is represented by ParseContext and rule foo is represented by FooContext. The ParseContext class produced by your grammar will provide you with access to several things, including the following items specific to your grammar.

  • The numbers return value will be stored in the generated field ParseContext.numbers.
  • The generated line() method will return a List<LineContext> containing the parse tree node for each invocation of the line rule from parse.
  • The class will also contain supporting methods required for the ANTLR 4 listener and visitor functionality to work.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.