blob: 130ae951930f903c3c4a6a64e7f97a47d22d086c [file] [log] [blame]
Guido van Rossum4b73a061995-10-11 17:30:04 +00001% libparser.tex
2%
3% Introductory documentation for the new parser built-in module.
4%
5% Copyright 1995 Virginia Polytechnic Institute and State University
6% and Fred L. Drake, Jr. This copyright notice must be distributed on
7% all copies, but this document otherwise may be distributed as part
8% of the Python distribution. No fee may be charged for this document
9% in any representation, either on paper or electronically. This
10% restriction does not affect other elements in a distributed package
11% in any way.
12%
13
14\section{Built-in Module \sectcode{parser}}
15\bimodindex{parser}
16
17
18% ==== 2. ====
19% Give a short overview of what the module does.
20% If it is platform specific, mention this.
21% Mention other important restrictions or general operating principles.
22
23The \code{parser} module provides an interface to Python's internal
24parser and byte-code compiler. The primary purpose for this interface
25is to allow Python code to edit the parse tree of a Python expression
26and create executable code from this. This can be better than trying
27to parse and modify an arbitrary Python code fragment as a string, and
28ensures that parsing is performed in a manner identical to the code
29forming the application. It's also faster.
30
31There are a few things to note about this module which are important
32to making use of the data structures created. This is not a tutorial
33on editing the parse trees for Python code.
34
35Most importantly, a good understanding of the Python grammar processed
36by the internal parser is required. For full information on the
37language syntax, refer to the Language Reference. The parser itself
38is created from a grammar specification defined in the file
39\code{Grammar/Grammar} in the standard Python distribution. The parse
40trees stored in the ``AST objects'' created by this module are the
41actual output from the internal parser when created by the
42\code{expr()} or \code{suite()} functions, described below. The AST
43objects created by \code{tuple2ast()} faithfully simulate those
44structures.
45
46Each element of the tuples returned by \code{ast2tuple()} has a simple
47form. Tuples representing non-terminal elements in the grammar always
48have a length greater than one. The first element is an integer which
49identifies a production in the grammar. These integers are given
50symbolic names in the C header file \code{Include/graminit.h} and the
51Python module \code{Lib/symbol.py}. Each additional element of the
52tuple represents a component of the production as recognized in the
53input string: these are always tuples which have the same form as the
54parent. An important aspect of this structure which should be noted
55is that keywords used to identify the parent node type, such as the
56keyword \code{if} in an \emph{if\_stmt}, are included in the node tree
57without any special treatment. For example, the \code{if} keyword is
58represented by the tuple \code{(1, 'if')}, where \code{1} is the
59numeric value associated with all \code{NAME} elements, including
60variable and function names defined by the user.
61
62Terminal elements are represented in much the same way, but without
63any child elements and the addition of the source text which was
64identified. The example of the \code{if} keyword above is
65representative. The various types of terminal symbols are defined in
66the C header file \code{Include/token.h} and the Python module
67\code{Lib/token.py}.
68
69The AST objects are not actually required to support the functionality
70of this module, but are provided for three purposes: to allow an
71application to amortize the cost of processing complex parse trees, to
72provide a parse tree representation which conserves memory space when
73compared to the Python tuple representation, and to ease the creation
74of additional modules in C which manipulate parse trees. A simple
Guido van Rossumed430731996-07-21 02:21:31 +000075``wrapper'' module may be created in Python to hide the use of AST
76objects.
Guido van Rossum4b73a061995-10-11 17:30:04 +000077
78
Guido van Rossum4b73a061995-10-11 17:30:04 +000079The \code{parser} module defines the following functions:
80
Guido van Rossum4b73a061995-10-11 17:30:04 +000081\renewcommand{\indexsubitem}{(in module parser)}
82
Guido van Rossum4b73a061995-10-11 17:30:04 +000083\begin{funcdesc}{ast2tuple}{ast}
84This function accepts an AST object from the caller in
85\code{\var{ast}} and returns a Python tuple representing the
86equivelent parse tree. The resulting tuple representation can be used
87for inspection or the creation of a new parse tree in tuple form.
88This function does not fail so long as memory is available to build
89the tuple representation.
90\end{funcdesc}
91
92
93\begin{funcdesc}{compileast}{ast\optional{\, filename \code{= '<ast>'}}}
94The Python byte compiler can be invoked on an AST object to produce
95code objects which can be used as part of an \code{exec} statement or
96a call to the built-in \code{eval()} function. This function provides
97the interface to the compiler, passing the internal parse tree from
98\code{\var{ast}} to the parser, using the source file name specified
99by the \code{\var{filename}} parameter. The default value supplied
100for \code{\var{filename}} indicates that the source was an AST object.
101\end{funcdesc}
102
103
104\begin{funcdesc}{expr}{string}
105The \code{expr()} function parses the parameter \code{\var{string}}
106as if it were an input to \code{compile(\var{string}, 'eval')}. If
107the parse succeeds, an AST object is created to hold the internal
108parse tree representation, otherwise an appropriate exception is
109thrown.
110\end{funcdesc}
111
112
113\begin{funcdesc}{isexpr}{ast}
114When \code{\var{ast}} represents an \code{'eval'} form, this function
115returns a true value (\code{1}), otherwise it returns false
116(\code{0}). This is useful, since code objects normally cannot be
117queried for this information using existing built-in functions. Note
118that the code objects created by \code{compileast()} cannot be queried
119like this either, and are identical to those created by the built-in
120\code{compile()} function.
121\end{funcdesc}
122
123
124\begin{funcdesc}{issuite}{ast}
125This function mirrors \code{isexpr()} in that it reports whether an
126AST object represents a suite of statements. It is not safe to assume
127that this function is equivelent to \code{not isexpr(\var{ast})}, as
128additional syntactic fragments may be supported in the future.
129\end{funcdesc}
130
131
132\begin{funcdesc}{suite}{string}
133The \code{suite()} function parses the parameter \code{\var{string}}
134as if it were an input to \code{compile(\var{string}, 'exec')}. If
135the parse succeeds, an AST object is created to hold the internal
136parse tree representation, otherwise an appropriate exception is
137thrown.
138\end{funcdesc}
139
140
141\begin{funcdesc}{tuple2ast}{tuple}
142This function accepts a parse tree represented as a tuple and builds
143an internal representation if possible. If it can validate that the
144tree conforms to the Python syntax and all nodes are valid node types
145in the host version of Python, an AST object is created from the
146internal representation and returned to the called. If there is a
147problem creating the internal representation, or if the tree cannot be
148validated, a \code{ParserError} exception is thrown. An AST object
149created this way should not be assumed to compile correctly; normal
150exceptions thrown by compilation may still be initiated when the AST
151object is passed to \code{compileast()}. This will normally indicate
152problems not related to syntax (such as a \code{MemoryError}
153exception).
154\end{funcdesc}
155
156
Guido van Rossum4b73a061995-10-11 17:30:04 +0000157\subsection{Exceptions and Error Handling}
158
159The parser module defines a single exception, but may also pass other
160built-in exceptions from other portions of the Python runtime
161environment. See each function for information about the exceptions
162it can raise.
163
164\begin{excdesc}{ParserError}
165Exception raised when a failure occurs within the parser module. This
166is generally produced for validation failures rather than the built in
167\code{SyntaxError} thrown during normal parsing.
168The exception argument is either a string describing the reason of the
169failure or a tuple containing a tuple causing the failure from a parse
170tree passed to \code{tuple2ast()} and an explanatory string. Calls to
171\code{tuple2ast()} need to be able to handle either type of exception,
172while calls to other functions in the module will only need to be
173aware of the simple string values.
174\end{excdesc}
175
176Note that the functions \code{compileast()}, \code{expr()}, and
177\code{suite()} may throw exceptions which are normally thrown by the
178parsing and compilation process. These include the built in
179exceptions \code{MemoryError}, \code{OverflowError},
180\code{SyntaxError}, and \code{SystemError}. In these cases, these
181exceptions carry all the meaning normally associated with them. Refer
182to the descriptions of each function for detailed information.
183
Guido van Rossum4b73a061995-10-11 17:30:04 +0000184
185\subsection{Example}
186
187A simple example:
188
189\begin{verbatim}
190>>> import parser
191>>> ast = parser.expr('a + 5')
192>>> code = parser.compileast(ast)
193>>> a = 5
194>>> eval(code)
19510
196\end{verbatim}
197
198
199\subsection{AST Objects}
200
201AST objects (returned by \code{expr()}, \code{suite()}, and
202\code{tuple2ast()}, described above) have no methods of their own.
203Some of the functions defined which accept an AST object as their
204first argument may change to object methods in the future.
205
206Ordered and equality comparisons are supported between AST objects.
207
208\renewcommand{\indexsubitem}{(ast method)}
209
210%\begin{funcdesc}{empty}{}
211%Empty the can into the trash.
212%\end{funcdesc}