简体   繁体   中英

ANTLR4: How to parse non-root node?

Given a grammar

script: statement*;
statement: do | check;
do: 'do';
check: 'check';

How can I parse a non-root node? In other words,

ScriptParser sp = new ScriptParser();
StatementContext sc = sp.parse<StatementContext>("do");

I simplified above example.

A solution is to make all nodes root nodes like

rootNode: script | statement | do | check;

but I don't want that as it pollutes my grammar and is a maintenance nightmare (whenever the grammar adds/removes a node, the rootnode must be updated, which is error-prone). Another solution is to write another derived grammar with the rootnode specification. This would not pollute the main grammar, but still has the maintenance issue.

Is there a better way to do this? I'd like to use many of my nodes (***Context classes) and pass them into constructors of my domain model classes.

Thanks @Jiri Tousek! The answer is indeed

ScriptParser sp = new ScriptParser();
StatementContext sc = sp.statement();

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