blob: 50b94c175060eb2386923d602d1dc4ecf5b01c00 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`parser` --- Access Python parse trees
3===========================================
4
5.. module:: parser
6 :synopsis: Access parse trees for Python source code.
7.. moduleauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
9
10
Christian Heimes5b5e81c2007-12-31 16:14:33 +000011.. Copyright 1995 Virginia Polytechnic Institute and State University and Fred
12 L. Drake, Jr. This copyright notice must be distributed on all copies, but
13 this document otherwise may be distributed as part of the Python
14 distribution. No fee may be charged for this document in any representation,
15 either on paper or electronically. This restriction does not affect other
16 elements in a distributed package in any way.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18.. index:: single: parsing; Python source code
19
20The :mod:`parser` module provides an interface to Python's internal parser and
21byte-code compiler. The primary purpose for this interface is to allow Python
22code to edit the parse tree of a Python expression and create executable code
23from this. This is better than trying to parse and modify an arbitrary Python
24code fragment as a string because parsing is performed in a manner identical to
25the code forming the application. It is also faster.
26
Georg Brandl0c77a822008-06-10 16:37:50 +000027.. note::
28
29 From Python 2.5 onward, it's much more convenient to cut in at the Abstract
30 Syntax Tree (AST) generation and compilation stage, using the :mod:`ast`
31 module.
32
Georg Brandl116aa622007-08-15 14:28:22 +000033There are a few things to note about this module which are important to making
34use of the data structures created. This is not a tutorial on editing the parse
35trees for Python code, but some examples of using the :mod:`parser` module are
36presented.
37
38Most importantly, a good understanding of the Python grammar processed by the
39internal parser is required. For full information on the language syntax, refer
40to :ref:`reference-index`. The parser
41itself is created from a grammar specification defined in the file
42:file:`Grammar/Grammar` in the standard Python distribution. The parse trees
Georg Brandl0c77a822008-06-10 16:37:50 +000043stored in the ST objects created by this module are the actual output from the
Georg Brandl116aa622007-08-15 14:28:22 +000044internal parser when created by the :func:`expr` or :func:`suite` functions,
Georg Brandl0c77a822008-06-10 16:37:50 +000045described below. The ST objects created by :func:`sequence2st` faithfully
Georg Brandl116aa622007-08-15 14:28:22 +000046simulate those structures. Be aware that the values of the sequences which are
47considered "correct" will vary from one version of Python to another as the
48formal grammar for the language is revised. However, transporting code from one
49Python version to another as source text will always allow correct parse trees
50to be created in the target version, with the only restriction being that
51migrating to an older version of the interpreter will not support more recent
52language constructs. The parse trees are not typically compatible from one
53version to another, whereas source code has always been forward-compatible.
54
Georg Brandl0c77a822008-06-10 16:37:50 +000055Each element of the sequences returned by :func:`st2list` or :func:`st2tuple`
Georg Brandl116aa622007-08-15 14:28:22 +000056has a simple form. Sequences representing non-terminal elements in the grammar
57always have a length greater than one. The first element is an integer which
58identifies a production in the grammar. These integers are given symbolic names
59in the C header file :file:`Include/graminit.h` and the Python module
60:mod:`symbol`. Each additional element of the sequence represents a component
61of the production as recognized in the input string: these are always sequences
62which have the same form as the parent. An important aspect of this structure
63which should be noted is that keywords used to identify the parent node type,
64such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the
65node tree without any special treatment. For example, the :keyword:`if` keyword
66is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value
67associated with all :const:`NAME` tokens, including variable and function names
68defined by the user. In an alternate form returned when line number information
69is requested, the same token might be represented as ``(1, 'if', 12)``, where
70the ``12`` represents the line number at which the terminal symbol was found.
71
72Terminal elements are represented in much the same way, but without any child
73elements and the addition of the source text which was identified. The example
74of the :keyword:`if` keyword above is representative. The various types of
75terminal symbols are defined in the C header file :file:`Include/token.h` and
76the Python module :mod:`token`.
77
Georg Brandl0c77a822008-06-10 16:37:50 +000078The ST objects are not required to support the functionality of this module,
Georg Brandl116aa622007-08-15 14:28:22 +000079but are provided for three purposes: to allow an application to amortize the
80cost of processing complex parse trees, to provide a parse tree representation
81which conserves memory space when compared to the Python list or tuple
82representation, and to ease the creation of additional modules in C which
83manipulate parse trees. A simple "wrapper" class may be created in Python to
Georg Brandl0c77a822008-06-10 16:37:50 +000084hide the use of ST objects.
Georg Brandl116aa622007-08-15 14:28:22 +000085
86The :mod:`parser` module defines functions for a few distinct purposes. The
Georg Brandl0c77a822008-06-10 16:37:50 +000087most important purposes are to create ST objects and to convert ST objects to
Georg Brandl116aa622007-08-15 14:28:22 +000088other representations such as parse trees and compiled code objects, but there
89are also functions which serve to query the type of parse tree represented by an
Georg Brandl0c77a822008-06-10 16:37:50 +000090ST object.
Georg Brandl116aa622007-08-15 14:28:22 +000091
92
93.. seealso::
94
95 Module :mod:`symbol`
96 Useful constants representing internal nodes of the parse tree.
97
98 Module :mod:`token`
99 Useful constants representing leaf nodes of the parse tree and functions for
100 testing node values.
101
102
Georg Brandl0c77a822008-06-10 16:37:50 +0000103.. _creating-sts:
Georg Brandl116aa622007-08-15 14:28:22 +0000104
Georg Brandl0c77a822008-06-10 16:37:50 +0000105Creating ST Objects
106-------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000107
Georg Brandl0c77a822008-06-10 16:37:50 +0000108ST objects may be created from source code or from a parse tree. When creating
109an ST object from source, different functions are used to create the ``'eval'``
Georg Brandl116aa622007-08-15 14:28:22 +0000110and ``'exec'`` forms.
111
112
113.. function:: expr(source)
114
115 The :func:`expr` function parses the parameter *source* as if it were an input
Georg Brandl0c77a822008-06-10 16:37:50 +0000116 to ``compile(source, 'file.py', 'eval')``. If the parse succeeds, an ST object
Georg Brandl116aa622007-08-15 14:28:22 +0000117 is created to hold the internal parse tree representation, otherwise an
Georg Brandl13f959b2010-10-06 08:35:38 +0000118 appropriate exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000119
120
121.. function:: suite(source)
122
123 The :func:`suite` function parses the parameter *source* as if it were an input
Georg Brandl0c77a822008-06-10 16:37:50 +0000124 to ``compile(source, 'file.py', 'exec')``. If the parse succeeds, an ST object
Georg Brandl116aa622007-08-15 14:28:22 +0000125 is created to hold the internal parse tree representation, otherwise an
Georg Brandl13f959b2010-10-06 08:35:38 +0000126 appropriate exception is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000127
128
Georg Brandl0c77a822008-06-10 16:37:50 +0000129.. function:: sequence2st(sequence)
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131 This function accepts a parse tree represented as a sequence and builds an
132 internal representation if possible. If it can validate that the tree conforms
133 to the Python grammar and all nodes are valid node types in the host version of
Georg Brandl0c77a822008-06-10 16:37:50 +0000134 Python, an ST object is created from the internal representation and returned
Georg Brandl116aa622007-08-15 14:28:22 +0000135 to the called. If there is a problem creating the internal representation, or
Georg Brandl13f959b2010-10-06 08:35:38 +0000136 if the tree cannot be validated, a :exc:`ParserError` exception is raised. An
Georg Brandl0c77a822008-06-10 16:37:50 +0000137 ST object created this way should not be assumed to compile correctly; normal
Georg Brandl13f959b2010-10-06 08:35:38 +0000138 exceptions raised by compilation may still be initiated when the ST object is
Georg Brandl0c77a822008-06-10 16:37:50 +0000139 passed to :func:`compilest`. This may indicate problems not related to syntax
Georg Brandl116aa622007-08-15 14:28:22 +0000140 (such as a :exc:`MemoryError` exception), but may also be due to constructs such
141 as the result of parsing ``del f(0)``, which escapes the Python parser but is
142 checked by the bytecode compiler.
143
144 Sequences representing terminal tokens may be represented as either two-element
145 lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1,
146 'name', 56)``. If the third element is present, it is assumed to be a valid
147 line number. The line number may be specified for any subset of the terminal
148 symbols in the input tree.
149
150
Georg Brandl0c77a822008-06-10 16:37:50 +0000151.. function:: tuple2st(sequence)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
Georg Brandl0c77a822008-06-10 16:37:50 +0000153 This is the same function as :func:`sequence2st`. This entry point is
Georg Brandl116aa622007-08-15 14:28:22 +0000154 maintained for backward compatibility.
155
156
Georg Brandl0c77a822008-06-10 16:37:50 +0000157.. _converting-sts:
Georg Brandl116aa622007-08-15 14:28:22 +0000158
Georg Brandl0c77a822008-06-10 16:37:50 +0000159Converting ST Objects
160---------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Georg Brandl0c77a822008-06-10 16:37:50 +0000162ST objects, regardless of the input used to create them, may be converted to
Georg Brandl116aa622007-08-15 14:28:22 +0000163parse trees represented as list- or tuple- trees, or may be compiled into
164executable code objects. Parse trees may be extracted with or without line
165numbering information.
166
167
Georg Brandl30704ea2008-07-23 15:07:12 +0000168.. function:: st2list(st[, line_info])
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Georg Brandl30704ea2008-07-23 15:07:12 +0000170 This function accepts an ST object from the caller in *st* and returns a
Georg Brandl116aa622007-08-15 14:28:22 +0000171 Python list representing the equivalent parse tree. The resulting list
172 representation can be used for inspection or the creation of a new parse tree in
173 list form. This function does not fail so long as memory is available to build
174 the list representation. If the parse tree will only be used for inspection,
Georg Brandl0c77a822008-06-10 16:37:50 +0000175 :func:`st2tuple` should be used instead to reduce memory consumption and
Georg Brandl116aa622007-08-15 14:28:22 +0000176 fragmentation. When the list representation is required, this function is
177 significantly faster than retrieving a tuple representation and converting that
178 to nested lists.
179
180 If *line_info* is true, line number information will be included for all
181 terminal tokens as a third element of the list representing the token. Note
182 that the line number provided specifies the line on which the token *ends*.
183 This information is omitted if the flag is false or omitted.
184
185
Georg Brandl30704ea2008-07-23 15:07:12 +0000186.. function:: st2tuple(st[, line_info])
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl30704ea2008-07-23 15:07:12 +0000188 This function accepts an ST object from the caller in *st* and returns a
Georg Brandl116aa622007-08-15 14:28:22 +0000189 Python tuple representing the equivalent parse tree. Other than returning a
Georg Brandl0c77a822008-06-10 16:37:50 +0000190 tuple instead of a list, this function is identical to :func:`st2list`.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 If *line_info* is true, line number information will be included for all
193 terminal tokens as a third element of the list representing the token. This
194 information is omitted if the flag is false or omitted.
195
196
Georg Brandl30704ea2008-07-23 15:07:12 +0000197.. function:: compilest(st[, filename='<syntax-tree>'])
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199 .. index::
200 builtin: exec
201 builtin: eval
202
Georg Brandl0c77a822008-06-10 16:37:50 +0000203 The Python byte compiler can be invoked on an ST object to produce code objects
Georg Brandl116aa622007-08-15 14:28:22 +0000204 which can be used as part of a call to the built-in :func:`exec` or :func:`eval`
205 functions. This function provides the interface to the compiler, passing the
Georg Brandl30704ea2008-07-23 15:07:12 +0000206 internal parse tree from *st* to the parser, using the source file name
Georg Brandl116aa622007-08-15 14:28:22 +0000207 specified by the *filename* parameter. The default value supplied for *filename*
Georg Brandl0c77a822008-06-10 16:37:50 +0000208 indicates that the source was an ST object.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
Georg Brandl0c77a822008-06-10 16:37:50 +0000210 Compiling an ST object may result in exceptions related to compilation; an
Georg Brandl116aa622007-08-15 14:28:22 +0000211 example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``:
212 this statement is considered legal within the formal grammar for Python but is
213 not a legal language construct. The :exc:`SyntaxError` raised for this
214 condition is actually generated by the Python byte-compiler normally, which is
215 why it can be raised at this point by the :mod:`parser` module. Most causes of
216 compilation failure can be diagnosed programmatically by inspection of the parse
217 tree.
218
219
Georg Brandl0c77a822008-06-10 16:37:50 +0000220.. _querying-sts:
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl0c77a822008-06-10 16:37:50 +0000222Queries on ST Objects
223---------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000224
Georg Brandl0c77a822008-06-10 16:37:50 +0000225Two functions are provided which allow an application to determine if an ST was
Georg Brandl116aa622007-08-15 14:28:22 +0000226created as an expression or a suite. Neither of these functions can be used to
Georg Brandl0c77a822008-06-10 16:37:50 +0000227determine if an ST was created from source code via :func:`expr` or
228:func:`suite` or from a parse tree via :func:`sequence2st`.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230
Georg Brandl30704ea2008-07-23 15:07:12 +0000231.. function:: isexpr(st)
Georg Brandl116aa622007-08-15 14:28:22 +0000232
233 .. index:: builtin: compile
234
Georg Brandl30704ea2008-07-23 15:07:12 +0000235 When *st* represents an ``'eval'`` form, this function returns true, otherwise
Georg Brandl116aa622007-08-15 14:28:22 +0000236 it returns false. This is useful, since code objects normally cannot be queried
237 for this information using existing built-in functions. Note that the code
Georg Brandl0c77a822008-06-10 16:37:50 +0000238 objects created by :func:`compilest` cannot be queried like this either, and
Georg Brandl116aa622007-08-15 14:28:22 +0000239 are identical to those created by the built-in :func:`compile` function.
240
241
Georg Brandl30704ea2008-07-23 15:07:12 +0000242.. function:: issuite(st)
Georg Brandl116aa622007-08-15 14:28:22 +0000243
Georg Brandl0c77a822008-06-10 16:37:50 +0000244 This function mirrors :func:`isexpr` in that it reports whether an ST object
Georg Brandl116aa622007-08-15 14:28:22 +0000245 represents an ``'exec'`` form, commonly known as a "suite." It is not safe to
Georg Brandl30704ea2008-07-23 15:07:12 +0000246 assume that this function is equivalent to ``not isexpr(st)``, as additional
Georg Brandl116aa622007-08-15 14:28:22 +0000247 syntactic fragments may be supported in the future.
248
249
Georg Brandl0c77a822008-06-10 16:37:50 +0000250.. _st-errors:
Georg Brandl116aa622007-08-15 14:28:22 +0000251
252Exceptions and Error Handling
253-----------------------------
254
255The parser module defines a single exception, but may also pass other built-in
256exceptions from other portions of the Python runtime environment. See each
257function for information about the exceptions it can raise.
258
259
260.. exception:: ParserError
261
262 Exception raised when a failure occurs within the parser module. This is
Georg Brandl13f959b2010-10-06 08:35:38 +0000263 generally produced for validation failures rather than the built-in
264 :exc:`SyntaxError` raised during normal parsing. The exception argument is
Georg Brandl116aa622007-08-15 14:28:22 +0000265 either a string describing the reason of the failure or a tuple containing a
Georg Brandl0c77a822008-06-10 16:37:50 +0000266 sequence causing the failure from a parse tree passed to :func:`sequence2st`
267 and an explanatory string. Calls to :func:`sequence2st` need to be able to
Georg Brandl116aa622007-08-15 14:28:22 +0000268 handle either type of exception, while calls to other functions in the module
269 will only need to be aware of the simple string values.
270
Georg Brandl0c77a822008-06-10 16:37:50 +0000271Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may
Éric Araujod82a47c2010-11-30 17:38:32 +0000272raise exceptions which are normally raised by the parsing and compilation
Georg Brandl116aa622007-08-15 14:28:22 +0000273process. These include the built in exceptions :exc:`MemoryError`,
274:exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`. In these
275cases, these exceptions carry all the meaning normally associated with them.
276Refer to the descriptions of each function for detailed information.
277
278
Georg Brandl0c77a822008-06-10 16:37:50 +0000279.. _st-objects:
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl0c77a822008-06-10 16:37:50 +0000281ST Objects
282----------
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl0c77a822008-06-10 16:37:50 +0000284Ordered and equality comparisons are supported between ST objects. Pickling of
285ST objects (using the :mod:`pickle` module) is also supported.
Georg Brandl116aa622007-08-15 14:28:22 +0000286
287
Georg Brandl0c77a822008-06-10 16:37:50 +0000288.. data:: STType
Georg Brandl116aa622007-08-15 14:28:22 +0000289
290 The type of the objects returned by :func:`expr`, :func:`suite` and
Georg Brandl0c77a822008-06-10 16:37:50 +0000291 :func:`sequence2st`.
Georg Brandl116aa622007-08-15 14:28:22 +0000292
Georg Brandl0c77a822008-06-10 16:37:50 +0000293ST objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295
Georg Brandl0c77a822008-06-10 16:37:50 +0000296.. method:: ST.compile([filename])
Georg Brandl116aa622007-08-15 14:28:22 +0000297
Georg Brandl0c77a822008-06-10 16:37:50 +0000298 Same as ``compilest(st, filename)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000299
300
Georg Brandl0c77a822008-06-10 16:37:50 +0000301.. method:: ST.isexpr()
Georg Brandl116aa622007-08-15 14:28:22 +0000302
Georg Brandl0c77a822008-06-10 16:37:50 +0000303 Same as ``isexpr(st)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000304
305
Georg Brandl0c77a822008-06-10 16:37:50 +0000306.. method:: ST.issuite()
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Georg Brandl0c77a822008-06-10 16:37:50 +0000308 Same as ``issuite(st)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000309
310
Georg Brandl0c77a822008-06-10 16:37:50 +0000311.. method:: ST.tolist([line_info])
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl0c77a822008-06-10 16:37:50 +0000313 Same as ``st2list(st, line_info)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315
Georg Brandl0c77a822008-06-10 16:37:50 +0000316.. method:: ST.totuple([line_info])
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Georg Brandl0c77a822008-06-10 16:37:50 +0000318 Same as ``st2tuple(st, line_info)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000319
320
Georg Brandlab32fec2010-11-26 08:49:15 +0000321Example: Emulation of :func:`compile`
322-------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000323
324While many useful operations may take place between parsing and bytecode
325generation, the simplest operation is to do nothing. For this purpose, using
326the :mod:`parser` module to produce an intermediate data structure is equivalent
327to the code ::
328
329 >>> code = compile('a + 5', 'file.py', 'eval')
330 >>> a = 5
331 >>> eval(code)
332 10
333
334The equivalent operation using the :mod:`parser` module is somewhat longer, and
Georg Brandl0c77a822008-06-10 16:37:50 +0000335allows the intermediate internal parse tree to be retained as an ST object::
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337 >>> import parser
Georg Brandl0c77a822008-06-10 16:37:50 +0000338 >>> st = parser.expr('a + 5')
339 >>> code = st.compile('file.py')
Georg Brandl116aa622007-08-15 14:28:22 +0000340 >>> a = 5
341 >>> eval(code)
342 10
343
Georg Brandl0c77a822008-06-10 16:37:50 +0000344An application which needs both ST and code objects can package this code into
Georg Brandl116aa622007-08-15 14:28:22 +0000345readily available functions::
346
347 import parser
348
349 def load_suite(source_string):
Georg Brandl0c77a822008-06-10 16:37:50 +0000350 st = parser.suite(source_string)
351 return st, st.compile()
Georg Brandl116aa622007-08-15 14:28:22 +0000352
353 def load_expression(source_string):
Georg Brandl0c77a822008-06-10 16:37:50 +0000354 st = parser.expr(source_string)
355 return st, st.compile()