简体   繁体   中英

ANTLR - Can I get parser context object to type definition?

I am writing a code generator using IDL grammar from antlers grammar repo .

I have the following case:

enum MyEnum
{
    One,
    Two,
    Three,
}

struct MyStruct
{
  //↓
    MyEnum myEnum;
}

When I get to the point where I want to generate a default constructor for MyStruct I want to explicit set "myEnum = MyEnum::One;" . I have a IdlParser.MemberContext object for MyEnum(marked with an arrow above). Is there a way to get a IdlParser.Enum_typeContext object from a IdlParser.MemberContext object so I can get all the enum literals?

I can of course start at the top of the AST and poke trough it again but is there a way to get context object to a type definition?

I am struggling with a good title. Please give feedback if you have a better one.

After you've parsed your input and have the ParseTree in hand, you'll need to traverse the tree using either a Listener or a Visitor (generally, Listeners are simpler, but Visitors give you a bit more flexibility (you have to handle navigating the tree yourself in visitors, so I only use them if a Listener won't work)).

One of the first questions is whether or not all of your symbols must be defined prior to their first use. This was common in older languages and grammars (made for faster parsing, but creates potential issue with the need for forward references or recursion.) Most, newer languages will allow you to refer to something you will define later. In that case, you'd create a Listener to build a symbol table for all of your definitions (taking scoping rules into account). Then a second Listener can be used to traverse the tree again, with the symbol table used to resolve references to items you've defined elsewhere.

(*** IF *** all referenced items must be defined before they're referenced, you CAN build the symbol table as you go and reference your symbol table as you encounter the identifiers. But it's still probably much cleaner to do it in two passes)

Your IdlParser.MemberContext will have nothing in it to point to your IdlParser.Enum_typeContext. it will just have an identifier that you can use to look it up in the symbol table you created in your first pass of the tree with a Listener to build the symbol table.

Take things one step at a time. Re-traversing the tree will almost assuredly not be a measurable performance impact, and it will keep your concerns well separated, and your logic easier to manage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM