Your test input contains two instances of content that will match the decFunc
rule. The generated parse-tree shows exactly that: two sub-trees, each having a deFunc
as the root.
Antlr v4 will not produce a true AST where f
and sum
are the roots of separate sub-trees.
Is there any thing can I do with the grammar to make both f
and sum
roots – Jonny Magnam
Not directly in an Antlr v4 grammar. You could:
- switch to Antlr v3, or another parser tool, and define the generated AST as you wish.
- walk the Antlr v4 parse-tree and create a separate AST of your desired form.
- just use the parse-tree directly with the realization that it is informationally equivalent to a classically defined AST and the implementation provides a number practical benefits.
Specifically, the standard academic AST is mutable, meaning that every (or all but the first) visitor is custom, not generated, and that any change in the underlying grammar or an interim structure of the AST will require reconsideration and likely changes to every subsequent visitor and their implemented logic.
The Antlr v4 parse-tree is essentially immutable, allowing decorations to be accumulated against tree nodes without loss of relational integrity. Visitors all use a common base structure, greatly reducing brittleness due to grammar changes and effects of prior executed visitors. As a practical matter, tree-walks are easily constructed, fast, and mutually independent except where expressly desired. They can achieve a greater separation of concerns in design and easier code maintenance in practice.
Choose the right tool for the whole job, in whatever way you define it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…