简体   繁体   中英

Given an ANTLR ParserRuleContext, how do I find the first parent of a given type?

I'm using ANTLR's XPath to get database views' table dependencies:

//create_view//from_clause//tableview_name

Now I need to get the view name that each table name belongs to. Eg, if there were a FirstParentOfType method, the code might look like this:

context.FirstParentOfType<Create_viewContext>().tableview_name().GetText();

But that method doesn't exist as far as I can tell. How is this done?

Pending a better way, here's an extension method that does it:

public static class RuleContextExtensions
{
    public static T FirstParentOfType<T>(this RuleContext context) where T : RuleContext => context as T ?? (context.Parent != null ? FirstParentOfType<T>(context.Parent) : null);
}

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