rest25/library/parser.rst => rest262/library/parser.rst
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
n11-.. % Copyright 1995 Virginia Polytechnic Institute and State University
n11+.. Copyright 1995 Virginia Polytechnic Institute and State University and Fred
12-.. % and Fred L. Drake, Jr.  This copyright notice must be distributed on
12+   L. Drake, Jr.  This copyright notice must be distributed on all copies, but
13-.. % all copies, but this document otherwise may be distributed as part
13+   this document otherwise may be distributed as part of the Python
14-.. % of the Python distribution.  No fee may be charged for this document
14+   distribution.  No fee may be charged for this document in any representation,
15-.. % in any representation, either on paper or electronically.  This
15+   either on paper or electronically.  This restriction does not affect other
16-.. % restriction does not affect other elements in a distributed package
16+   elements in a distributed package in any way.
17-.. % in any way.
18
19.. index:: single: parsing; Python source code
20
21The :mod:`parser` module provides an interface to Python's internal parser and
22byte-code compiler.  The primary purpose for this interface is to allow Python
23code to edit the parse tree of a Python expression and create executable code
24from this.  This is better than trying to parse and modify an arbitrary Python
25code fragment as a string because parsing is performed in a manner identical to
26the code forming the application.  It is also faster.
27
n27+.. 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+ 
33+   The :mod:`parser` module exports the names documented here also with "st"
34+   replaced by "ast"; this is a legacy from the time when there was no other
35+   AST and has nothing to do with the AST found in Python 2.5.  This is also the
36+   reason for the functions' keyword arguments being called *ast*, not *st*.
37+   The "ast" functions will be removed in Python 3.0.
38+ 
28There are a few things to note about this module which are important to making
29use of the data structures created.  This is not a tutorial on editing the parse
30trees for Python code, but some examples of using the :mod:`parser` module are
31presented.
32
33Most importantly, a good understanding of the Python grammar processed by the
34internal parser is required.  For full information on the language syntax, refer
n35-to the Python Language Reference (XXX reference: ../ref/ref.html).  The parser
n46+to :ref:`reference-index`.  The parser
36itself is created from a grammar specification defined in the file
37:file:`Grammar/Grammar` in the standard Python distribution.  The parse trees
n38-stored in the AST objects created by this module are the actual output from the
n49+stored in the ST objects created by this module are the actual output from the
39internal parser when created by the :func:`expr` or :func:`suite` functions,
n40-described below.  The AST objects created by :func:`sequence2ast` faithfully
n51+described below.  The ST objects created by :func:`sequence2st` faithfully
41simulate those structures.  Be aware that the values of the sequences which are
42considered "correct" will vary from one version of Python to another as the
43formal grammar for the language is revised.  However, transporting code from one
44Python version to another as source text will always allow correct parse trees
45to be created in the target version, with the only restriction being that
46migrating to an older version of the interpreter will not support more recent
47language constructs.  The parse trees are not typically compatible from one
48version to another, whereas source code has always been forward-compatible.
49
n50-Each element of the sequences returned by :func:`ast2list` or :func:`ast2tuple`
n61+Each element of the sequences returned by :func:`st2list` or :func:`st2tuple`
51has a simple form.  Sequences representing non-terminal elements in the grammar
52always have a length greater than one.  The first element is an integer which
53identifies a production in the grammar.  These integers are given symbolic names
54in the C header file :file:`Include/graminit.h` and the Python module
55:mod:`symbol`.  Each additional element of the sequence represents a component
56of the production as recognized in the input string: these are always sequences
57which have the same form as the parent.  An important aspect of this structure
58which should be noted is that keywords used to identify the parent node type,
65the ``12`` represents the line number at which the terminal symbol was found.
66
67Terminal elements are represented in much the same way, but without any child
68elements and the addition of the source text which was identified.  The example
69of the :keyword:`if` keyword above is representative.  The various types of
70terminal symbols are defined in the C header file :file:`Include/token.h` and
71the Python module :mod:`token`.
72
n73-The AST objects are not required to support the functionality of this module,
n84+The ST objects are not required to support the functionality of this module,
74but are provided for three purposes: to allow an application to amortize the
75cost of processing complex parse trees, to provide a parse tree representation
76which conserves memory space when compared to the Python list or tuple
77representation, and to ease the creation of additional modules in C which
78manipulate parse trees.  A simple "wrapper" class may be created in Python to
n79-hide the use of AST objects.
n90+hide the use of ST objects.
80
81The :mod:`parser` module defines functions for a few distinct purposes.  The
n82-most important purposes are to create AST objects and to convert AST objects to
n93+most important purposes are to create ST objects and to convert ST objects to
83other representations such as parse trees and compiled code objects, but there
84are also functions which serve to query the type of parse tree represented by an
n85-AST object.
n96+ST object.
86
87
88.. seealso::
89
90   Module :mod:`symbol`
91      Useful constants representing internal nodes of the parse tree.
92
93   Module :mod:`token`
94      Useful constants representing leaf nodes of the parse tree and functions for
95      testing node values.
96
97
n98-.. _creating asts:
n109+.. _creating-sts:
99
n100-Creating AST Objects
n111+Creating ST Objects
101---------------------
112+-------------------
102
n103-AST objects may be created from source code or from a parse tree. When creating
n114+ST objects may be created from source code or from a parse tree. When creating
104-an AST object from source, different functions are used to create the ``'eval'``
115+an ST object from source, different functions are used to create the ``'eval'``
105and ``'exec'`` forms.
106
107
108.. function:: expr(source)
109
110   The :func:`expr` function parses the parameter *source* as if it were an input
n111-   to ``compile(source, 'file.py', 'eval')``.  If the parse succeeds, an AST object
n122+   to ``compile(source, 'file.py', 'eval')``.  If the parse succeeds, an ST object
112   is created to hold the internal parse tree representation, otherwise an
113   appropriate exception is thrown.
114
115
116.. function:: suite(source)
117
118   The :func:`suite` function parses the parameter *source* as if it were an input
n119-   to ``compile(source, 'file.py', 'exec')``.  If the parse succeeds, an AST object
n130+   to ``compile(source, 'file.py', 'exec')``.  If the parse succeeds, an ST object
120   is created to hold the internal parse tree representation, otherwise an
121   appropriate exception is thrown.
122
123
n124-.. function:: sequence2ast(sequence)
n135+.. function:: sequence2st(sequence)
125
126   This function accepts a parse tree represented as a sequence and builds an
127   internal representation if possible.  If it can validate that the tree conforms
128   to the Python grammar and all nodes are valid node types in the host version of
n129-   Python, an AST object is created from the internal representation and returned
n140+   Python, an ST object is created from the internal representation and returned
130   to the called.  If there is a problem creating the internal representation, or
131   if the tree cannot be validated, a :exc:`ParserError` exception is thrown.  An
n132-   AST object created this way should not be assumed to compile correctly; normal
n143+   ST object created this way should not be assumed to compile correctly; normal
133-   exceptions thrown by compilation may still be initiated when the AST object is
144+   exceptions thrown by compilation may still be initiated when the ST object is
134-   passed to :func:`compileast`.  This may indicate problems not related to syntax
145+   passed to :func:`compilest`.  This may indicate problems not related to syntax
135   (such as a :exc:`MemoryError` exception), but may also be due to constructs such
136   as the result of parsing ``del f(0)``, which escapes the Python parser but is
137   checked by the bytecode compiler.
138
139   Sequences representing terminal tokens may be represented as either two-element
140   lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1,
141   'name', 56)``.  If the third element is present, it is assumed to be a valid
142   line number.  The line number may be specified for any subset of the terminal
143   symbols in the input tree.
144
145
n146-.. function:: tuple2ast(sequence)
n157+.. function:: tuple2st(sequence)
147
n148-   This is the same function as :func:`sequence2ast`.  This entry point is
n159+   This is the same function as :func:`sequence2st`.  This entry point is
149   maintained for backward compatibility.
150
151
n152-.. _converting asts:
n163+.. _converting-sts:
153
n154-Converting AST Objects
n165+Converting ST Objects
155-----------------------
166+---------------------
156
n157-AST objects, regardless of the input used to create them, may be converted to
n168+ST objects, regardless of the input used to create them, may be converted to
158parse trees represented as list- or tuple- trees, or may be compiled into
159executable code objects.  Parse trees may be extracted with or without line
160numbering information.
161
162
n163-.. function:: ast2list(ast[, line_info])
n174+.. function:: st2list(ast[, line_info])
164
n165-   This function accepts an AST object from the caller in *ast* and returns a
n176+   This function accepts an ST object from the caller in *ast* and returns a
166   Python list representing the equivalent parse tree.  The resulting list
167   representation can be used for inspection or the creation of a new parse tree in
168   list form.  This function does not fail so long as memory is available to build
169   the list representation.  If the parse tree will only be used for inspection,
n170-   :func:`ast2tuple` should be used instead to reduce memory consumption and
n181+   :func:`st2tuple` should be used instead to reduce memory consumption and
171   fragmentation.  When the list representation is required, this function is
172   significantly faster than retrieving a tuple representation and converting that
173   to nested lists.
174
175   If *line_info* is true, line number information will be included for all
176   terminal tokens as a third element of the list representing the token.  Note
177   that the line number provided specifies the line on which the token *ends*.
178   This information is omitted if the flag is false or omitted.
179
180
n181-.. function:: ast2tuple(ast[, line_info])
n192+.. function:: st2tuple(ast[, line_info])
182
n183-   This function accepts an AST object from the caller in *ast* and returns a
n194+   This function accepts an ST object from the caller in *ast* and returns a
184   Python tuple representing the equivalent parse tree.  Other than returning a
n185-   tuple instead of a list, this function is identical to :func:`ast2list`.
n196+   tuple instead of a list, this function is identical to :func:`st2list`.
186
187   If *line_info* is true, line number information will be included for all
188   terminal tokens as a third element of the list representing the token.  This
189   information is omitted if the flag is false or omitted.
190
191
n192-.. function:: compileast(ast[, filename\ ``= '<ast>'``])
n203+.. function:: compilest(ast[, filename='<syntax-tree>'])
193
194   .. index:: builtin: eval
195
n196-   The Python byte compiler can be invoked on an AST object to produce code objects
n207+   The Python byte compiler can be invoked on an ST object to produce code objects
197   which can be used as part of an :keyword:`exec` statement or a call to the
198   built-in :func:`eval` function. This function provides the interface to the
199   compiler, passing the internal parse tree from *ast* to the parser, using the
200   source file name specified by the *filename* parameter. The default value
n201-   supplied for *filename* indicates that the source was an AST object.
n212+   supplied for *filename* indicates that the source was an ST object.
202
n203-   Compiling an AST object may result in exceptions related to compilation; an
n214+   Compiling an ST object may result in exceptions related to compilation; an
204   example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``:
205   this statement is considered legal within the formal grammar for Python but is
206   not a legal language construct.  The :exc:`SyntaxError` raised for this
207   condition is actually generated by the Python byte-compiler normally, which is
208   why it can be raised at this point by the :mod:`parser` module.  Most causes of
209   compilation failure can be diagnosed programmatically by inspection of the parse
210   tree.
211
212
n213-.. _querying asts:
n224+.. _querying-sts:
214
n215-Queries on AST Objects
n226+Queries on ST Objects
216-----------------------
227+---------------------
217
n218-Two functions are provided which allow an application to determine if an AST was
n229+Two functions are provided which allow an application to determine if an ST was
219created as an expression or a suite.  Neither of these functions can be used to
n220-determine if an AST was created from source code via :func:`expr` or
n231+determine if an ST was created from source code via :func:`expr` or
221-:func:`suite` or from a parse tree via :func:`sequence2ast`.
232+:func:`suite` or from a parse tree via :func:`sequence2st`.
222
223
224.. function:: isexpr(ast)
225
226   .. index:: builtin: compile
227
228   When *ast* represents an ``'eval'`` form, this function returns true, otherwise
229   it returns false.  This is useful, since code objects normally cannot be queried
230   for this information using existing built-in functions.  Note that the code
n231-   objects created by :func:`compileast` cannot be queried like this either, and
n242+   objects created by :func:`compilest` cannot be queried like this either, and
232   are identical to those created by the built-in :func:`compile` function.
233
234
235.. function:: issuite(ast)
236
n237-   This function mirrors :func:`isexpr` in that it reports whether an AST object
n248+   This function mirrors :func:`isexpr` in that it reports whether an ST object
238   represents an ``'exec'`` form, commonly known as a "suite."  It is not safe to
239   assume that this function is equivalent to ``not isexpr(ast)``, as additional
240   syntactic fragments may be supported in the future.
241
242
n243-.. _ast errors:
n254+.. _st-errors:
244
245Exceptions and Error Handling
246-----------------------------
247
248The parser module defines a single exception, but may also pass other built-in
249exceptions from other portions of the Python runtime environment.  See each
250function for information about the exceptions it can raise.
251
252
253.. exception:: ParserError
254
255   Exception raised when a failure occurs within the parser module.  This is
256   generally produced for validation failures rather than the built in
257   :exc:`SyntaxError` thrown during normal parsing. The exception argument is
258   either a string describing the reason of the failure or a tuple containing a
n259-   sequence causing the failure from a parse tree passed to :func:`sequence2ast`
n270+   sequence causing the failure from a parse tree passed to :func:`sequence2st`
260-   and an explanatory string.  Calls to :func:`sequence2ast` need to be able to
271+   and an explanatory string.  Calls to :func:`sequence2st` need to be able to
261   handle either type of exception, while calls to other functions in the module
262   will only need to be aware of the simple string values.
263
n264-Note that the functions :func:`compileast`, :func:`expr`, and :func:`suite` may
n275+Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may
265throw exceptions which are normally thrown by the parsing and compilation
266process.  These include the built in exceptions :exc:`MemoryError`,
267:exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`.  In these
268cases, these exceptions carry all the meaning normally associated with them.
269Refer to the descriptions of each function for detailed information.
270
271
n272-.. _ast objects:
n283+.. _st-objects:
273
n274-AST Objects
n285+ST Objects
275------------
286+----------
276
n277-Ordered and equality comparisons are supported between AST objects. Pickling of
n288+Ordered and equality comparisons are supported between ST objects. Pickling of
278-AST objects (using the :mod:`pickle` module) is also supported.
289+ST objects (using the :mod:`pickle` module) is also supported.
279
280
n281-.. data:: ASTType
n292+.. data:: STType
282
283   The type of the objects returned by :func:`expr`, :func:`suite` and
n284-   :func:`sequence2ast`.
n295+   :func:`sequence2st`.
285
n286-AST objects have the following methods:
n297+ST objects have the following methods:
287
288
n289-.. method:: AST.compile([filename])
n300+.. method:: ST.compile([filename])
290
n291-   Same as ``compileast(ast, filename)``.
n302+   Same as ``compilest(st, filename)``.
292
293
n294-.. method:: AST.isexpr()
n305+.. method:: ST.isexpr()
295
n296-   Same as ``isexpr(ast)``.
n307+   Same as ``isexpr(st)``.
297
298
n299-.. method:: AST.issuite()
n310+.. method:: ST.issuite()
300
n301-   Same as ``issuite(ast)``.
n312+   Same as ``issuite(st)``.
302
303
n304-.. method:: AST.tolist([line_info])
n315+.. method:: ST.tolist([line_info])
305
n306-   Same as ``ast2list(ast, line_info)``.
n317+   Same as ``st2list(st, line_info)``.
307
308
n309-.. method:: AST.totuple([line_info])
n320+.. method:: ST.totuple([line_info])
310
n311-   Same as ``ast2tuple(ast, line_info)``.
n322+   Same as ``st2tuple(st, line_info)``.
312
313
n314-.. _ast examples:
n325+.. _st-examples:
315
316Examples
317--------
318
319.. index:: builtin: compile
320
321The parser modules allows operations to be performed on the parse tree of Python
n322-source code before the bytecode is generated, and provides for inspection of the
n333+source code before the :term:`bytecode` is generated, and provides for inspection of the
323parse tree for information gathering purposes. Two examples are presented.  The
324simple example demonstrates emulation of the :func:`compile` built-in function
325and the complex example shows the use of a parse tree for information discovery.
326
327
328Emulation of :func:`compile`
329^^^^^^^^^^^^^^^^^^^^^^^^^^^^
330
334to the code ::
335
336   >>> code = compile('a + 5', 'file.py', 'eval')
337   >>> a = 5
338   >>> eval(code)
339   10
340
341The equivalent operation using the :mod:`parser` module is somewhat longer, and
n342-allows the intermediate internal parse tree to be retained as an AST object::
n353+allows the intermediate internal parse tree to be retained as an ST object::
343
344   >>> import parser
n345-   >>> ast = parser.expr('a + 5')
n356+   >>> st = parser.expr('a + 5')
346-   >>> code = ast.compile('file.py')
357+   >>> code = st.compile('file.py')
347   >>> a = 5
348   >>> eval(code)
349   10
350
n351-An application which needs both AST and code objects can package this code into
n362+An application which needs both ST and code objects can package this code into
352readily available functions::
353
354   import parser
355
356   def load_suite(source_string):
n357-       ast = parser.suite(source_string)
n368+       st = parser.suite(source_string)
358-       return ast, ast.compile()
369+       return st, st.compile()
359
360   def load_expression(source_string):
n361-       ast = parser.expr(source_string)
n372+       st = parser.expr(source_string)
362-       return ast, ast.compile()
373+       return st, st.compile()
363
364
365Information Discovery
366^^^^^^^^^^^^^^^^^^^^^
367
368.. index::
369   single: string; documentation
370   single: docstrings
408   """
409
410Using the interpreter to take a look at the parse tree, we find a bewildering
411mass of numbers and parentheses, with the documentation buried deep in nested
412tuples. ::
413
414   >>> import parser
415   >>> import pprint
n416-   >>> ast = parser.suite(open('docstring.py').read())
n427+   >>> st = parser.suite(open('docstring.py').read())
417-   >>> tup = ast.totuple()
428+   >>> tup = st.totuple()
418   >>> pprint.pprint(tup)
419   (257,
420    (264,
421     (265,
422      (266,
423       (267,
424        (307,
425         (287,
625"short form" or the "long form."  The short form is used when the code block is
626on the same line as the definition of the code block, as in ::
627
628   def square(x): "Square an argument."; return x ** 2
629
630while the long form uses an indented block and allows nested definitions::
631
632   def make_power(exp):
n633-       "Make a function that raises an argument to the exponent `exp'."
n644+       "Make a function that raises an argument to the exponent `exp`."
634       def raiser(x, y=exp):
635           return x ** y
636       return raiser
637
638When the short form is used, the code block may contain a docstring as the
639first, and possibly only, :const:`small_stmt` element.  The extraction of such a
640docstring is slightly different and requires only a portion of the complete
641pattern used in the more common case.  As implemented, the docstring will only
666file :file:`example.py`.) ::
667
668   def get_docs(fileName):
669       import os
670       import parser
671
672       source = open(fileName).read()
673       basename = os.path.basename(os.path.splitext(fileName)[0])
t674-       ast = parser.suite(source)
t685+       st = parser.suite(source)
675-       return ModuleInfo(ast.totuple(), basename)
686+       return ModuleInfo(st.totuple(), basename)
676
677This provides an easy-to-use interface to the documentation of a module.  If
678information is required which is not extracted by the code of this example, the
679code may be extended at clearly defined points to provide additional
680capabilities.
681
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op