|
| 1 | +% XXX Label can't be _ast? |
| 2 | +% XXX Where should this section/chapter go? |
| 3 | +\chapter{Abstract Syntax Trees\label{ast}} |
| 4 | + |
| 5 | +\sectionauthor{Martin v. L\"owis}{martin@v.loewis.de} |
| 6 | + |
| 7 | +The \code{_ast} module helps Python applications to process |
| 8 | +trees of the Python abstract syntax grammar. The Python compiler |
| 9 | +currently provides read-only access to such trees, meaning that |
| 10 | +applications can only create a tree for a given piece of Python |
| 11 | +source code; generating byte code from a (potentially modified) |
| 12 | +tree is not supported. The abstract syntax itself might change with |
| 13 | +each Python release; this module helps to find out programmatically |
| 14 | +what the current grammar looks like. |
| 15 | + |
| 16 | +An abstract syntax tree can be generated by passing \code{_ast.PyCF_ONLY_AST} |
| 17 | +as a flag to the \function{compile} builtin function. The result will be a tree |
| 18 | +of objects whose classes all inherit from \code{_ast.AST}. |
| 19 | + |
| 20 | +The actual classes are derived from the \code{Parser/Python.asdl} file, |
| 21 | +which is reproduced below. There is one class defined for each left-hand |
| 22 | +side symbol in the abstract grammar (for example, \code{_ast.stmt} or \code{_ast.expr}). |
| 23 | +In addition, there is one class defined for each constructor on the |
| 24 | +right-hand side; these classes inherit from the classes for the left-hand |
| 25 | +side trees. For example, \code{_ast.BinOp} inherits from \code{_ast.expr}. |
| 26 | +For production rules with alternatives (aka "sums"), the left-hand side |
| 27 | +class is abstract: only instances of specific constructor nodes are ever |
| 28 | +created. |
| 29 | + |
| 30 | +Each concrete class has an attribute \code{_fields} which gives the |
| 31 | +names of all child nodes. |
| 32 | + |
| 33 | +Each instance of a concrete class has one attribute for each child node, |
| 34 | +of the type as defined in the grammar. For example, \code{_ast.BinOp} |
| 35 | +instances have an attribute \code{left} of type \code{_ast.expr}. |
| 36 | + |
| 37 | +If these attributes are marked as optional in the grammar (using a |
| 38 | +question mark), the value might be \code{None}. If the attributes |
| 39 | +can have zero-or-more values (marked with an asterisk), the |
| 40 | +values are represented as Python lists. |
| 41 | + |
| 42 | +\subsection{Abstract Grammar} |
| 43 | + |
| 44 | +The abstract grammar is currently defined as follows: |
| 45 | + |
| 46 | +\verbatiminput{../../Parser/Python.asdl} |
0 commit comments