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