Need a tip for the ANTLR4 tree

Many years have passed since my (one) compiler course so forgave me if this question is not correct. I am also new to ANTLR and C, not Java encoder. What I would like to do is describe my problem and then ask for advice on the best technique to use.

I am trying to translate ASN.1 production to ML. For instance,

Foo ::= ENUMERATED {
  bar  (0),    -- some comment 0
  baz  (1)     -- some comment 1
}

at

<Enumerated name="Foo">
  <NamedValues>
    <Unsigned name="bar" value="0" comment="some comment 0"/>
    <Unsigned name="baz" value="1" comment="some comment 1"/>
  </NamedValues>
</Enumerated>

My (simplified) ASN1 grammar:

assignment : IDENTIFIER typeAssignment ;
typeAssignment : '::=' type ;
type : builtinType ;
builtinType : enumeratedType ;
enumeratedType : 'ENUMERATED' '{' enumerations '}' ;
...

A few examples from the "ANTLR4 Final Description" demonstrate by overriding some enterNode or exitNode method in BaseListener and everything you need in a Node context. My problem is that I would like to override enterTypeAssignmentand exitTypeAssignment, but some of the info I need is in the nodes above (for example, assignment) or lower (for example, enumeration) in the parse tree.

, , ? , .

:

import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.misc.Interval;

public class MylListener extends ASN1BaseListener {
  ASN1Parser parser;
  String id = "";
  String assignedType =  "";

  public MyListener(ASN1Parser parser) {this.parser = parser;}

  @Override
  public void enterAssignment(ASN1Parser.AssignmentContext ctx) {
    id = ctx.IDENTIFIER().getText();
  }

  /** Listen to matches of typeAssignment **/
  @Override
  public void enterTypeAssignment(ASN1Parser.TypeAssignmentContext ctx) {
    if ( ctx.type() != null ) {
      if ( ctx.type().builtinType() != null ) {
        if ( ctx.type().builtinType().enumeratedType() != null ) {
          assignedType =  "Enumerated";
          System.out.println("");
          System.out.println("<Enumerated name=\""+id+"\">");
          ...
        }
      }
    }
  }

  @Override
  public void exitTypeAssignment(ASN1Parser.TypeAssignmentContext ctx) {
    if (assignedType.length() > 0) {
      System.out.println("</"+assignedType+">");
      assignedType =  "";
    }
  }
}

, , ...


UPDATE: , , TerminalNodes vars Listener . node?

+5
1

, . Listener , .

#, C.

+1
source

All Articles