Package: antlr-ast
antlr-astThis package allows you to use ANTLR grammars and use the parser output to generate an abstract syntax tree (AST).Installpipinstallantlr-astNote:this package is not python2 compatible.Running Tests# may need:# pip install pytestpy.testUsageUsingantlr-astinvolves four steps:Using ANTLR to define a grammar and to generate the necessary Python files to parse this grammarUsingparseto get the ANTLR runtime output based on the generated grammar filesUsingprocess_treeon the output of the previous stepABaseAstVisitor(customisable by providing a subclass) transforms the ANTLR output to a serializable tree ofBaseNodes,
dynamically created based on the rules in the ANTLR grammarABaseNodeTransformersubclass can be used to transform each kind of nodeThe simplify option can be used to shorten paths in the tree by skipping nodes that only have a single descendantUsing the resulting treeThe next sections go into more detail about these steps.To visualize the process of creating and transforrming these parse trees, you can usethis ast-viewer.Using ANTLRNote: For this part of this tutorial you need to know how to parse codeSee the ANTLRgetting started guideif you have never installed ANTLR.TheANTLR Mega Tutorialhas useful Python examples.This page explains how to write ANTLR parser rules.The rule definition below is an example with descriptive names for important ANTLR parser grammar elements:rule_name: rule_element? rule_element_label='literal'    #RuleAlternativeLabel
         | TOKEN+                                        #RuleAlternativeLabel
         ;Rule element and alternative labels are optional.+,*,?,|and()have the same meaning as in RegEx.Below, we'll use a simple grammar to explain howantlr-astworks.
This grammar can be found in/tests/Expr.g4.grammar Expr;

// parser

expr:   left=expr op=('+'|'-') right=expr       #BinaryExpr
    |   NOT expr                                #NotExpr
    |   INT                                     #Integer
    |   '(' expr ')'                            #SubExpr
    ;

// lexer

INT :   [0-9]+ ;         // match integers
NOT :   'not' ;

WS  :   [ \t]+ -> skip ; // toss out whitespaceANTLR can use the grammar above to generate a parser in a number of languages.
To generate a Python parser, you can use the following command.antlr4-Dlanguage=Python3-visitor/tests/Expr.g4This will generate a number of files in the/tests/directory, including a Lexer (ExprLexer.py),
a parser (ExprParser.py), and a visitor (ExprVisitor.py).You can use and import these directly in Python. For example, from the root of this repo:fromtestsimportExprVisitorTo easily use the generated files, they are put in theantlr_pypackage.
The__init__.pyfile exports the generated files under an alias that doesn't include the name of the grammar.Base nodesABaseNodesubclass has fields for all rule elements and labels for all rule element labels in its corresponding grammar rule.
Both fields and labels are available as properties onBaseNodeinstances.
Labels take precedence over fields if the names would collide.The name of aBaseNodeis the name of the corresponding ANTLR grammar rule, but starting with an uppercase character.
If rule alternative labels are specified for an ANTLR rule, these are used instead of the rule name.Transforming nodesTypically, there is no 1-to-1 mapping between ANTLR rules and the concepts of a language: the rule hierarchy is more nested.
Transformations can be used to make the initial tree of BaseNodes based on ANTLR rules more similar to an AST.TransformerTheBaseNodeTransformerwill walk over the tree from the root node to the leaf nodes.
When visiting a node, it is possible to transform it.
The tree is updated with transformed node before continuing the walk over the tree.To define a node transform, add a static method to theBaseNodeTransformersubclass passed toprocess_tree.The name of the method you should define follows this pattern:visit_<BaseNode>,
where<BaseNode>should be replaced by the name of theBaseNodesubclass to transform.The method should return the transformed node.This is a simple example:classTransformer(BaseNodeTransformer):@staticmethoddefvisit_My_antlr_rule(node):returnnode.name_of_partCustom nodesA custom node can represent a part of the parsed language, a type of node present in an AST.To make it easy to return a custom node, you can defineAliasNodesubclasses.
Normally, fields ofAliasNodes are like symlinks to navigate the tree ofBaseNodes.Instances of custom nodes are created from aBaseNode.
Fields and labels of the sourceBaseNodeare also available on theAliasNode.
If anAliasNodefield name collides with these, it takes precedence when accessing that property.This is what a custom node looks like:classNotExpr(AliasNode):_fields_spec=["expr","op=NOT"]This code defines a custom node,NotExprwith anexprand anopfield.Field specsThe_fields_specclass property is a list that defines the fields the custom node should have.This is how a field spec in this list is used when creating an custom node from aBaseNode(the source node):If a field spec does not exist on the source node, it is set toNoneIf multiple field specs define the same field, the first one that isn'tNoneis usedIf a field spec is just a name, it is copied from the source nodeIf a field spec is an assignment, the left side is the name of the field on theAliasNodeand the right side is the path that should be taken starting in the source node to get the node
that should be the value for the field on the custom node.
Parts of this path are separated using.Connecting to the transformerTo use this custom node, add a method to the transformer:classTransformer(BaseNodeTransformer):# ...# here the BaseNode name is the same as the custom node name# but that isn't required@staticmethoddefvisit_NotExpr(node):returnNotExpr.from_spec(node)Instead of defining methods on the transformer class to use custom nodes, it's possible to do this automatically:Transformer.bind_alias_nodes(alias_nodes)To make this work, theAliasNodeclasses in the list should have a_rulesclass property
with a list of theBaseNodenames it should transform.This is the result:classNotExpr(AliasNode):_fields_spec=["expr","op=NOT"]_rules=["NotExpr"]classTransformer(BaseNodeTransformer):passalias_nodes=[NotExpr]Transformer.bind_alias_nodes(alias_nodes)An item in_rulescan also be a tuple.
In that case, the first item in the tuple is aBaseNodename
and the second item is the name of a class method of the custom node.It's not useful in the example above, but it is equivalent to this:classNotExpr(AliasNode):_fields_spec=["expr","op=NOT"]_rules=[("NotExpr","from_not")]@classmethoddeffrom_not(cls,node):returncls.from_spec(node)classTransformer(BaseNodeTransformer):passalias_nodes=[NotExpr]Transformer.bind_alias_nodes(alias_nodes)Using the final treeIt's easy to use a tree that has a mix ofAliasNodes and dynamicBaseNodes:
the whole tree is just a nested Python object.When searching nodes in a tree, the priority of nodes can be taken into account.
By default,BaseNodes have priority 3 andAliasNodes have priority 2.When writing code to work with trees, it can be affected by changes in the grammar, the transforms and the custom nodes.
The grammar is the most likely to change.To make grammar updates have no impact on your code, don't rely onBaseNodes.
You can still check whether theAliasNodeparent node of aBaseNodehas the correct fields set
and search for nestedAliasNodes in a subtree.If you do rely onBaseNodes, code could break by the addition ofAliasNodes that replace some of these
if a field name collides with a field name on a usedBaseNode.