Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | |
| 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 Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 11 | .. 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | |
| 18 | .. index:: single: parsing; Python source code |
| 19 | |
| 20 | The :mod:`parser` module provides an interface to Python's internal parser and |
| 21 | byte-code compiler. The primary purpose for this interface is to allow Python |
| 22 | code to edit the parse tree of a Python expression and create executable code |
| 23 | from this. This is better than trying to parse and modify an arbitrary Python |
| 24 | code fragment as a string because parsing is performed in a manner identical to |
| 25 | the code forming the application. It is also faster. |
| 26 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 27 | .. 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 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 38 | There are a few things to note about this module which are important to making |
| 39 | use of the data structures created. This is not a tutorial on editing the parse |
| 40 | trees for Python code, but some examples of using the :mod:`parser` module are |
| 41 | presented. |
| 42 | |
| 43 | Most importantly, a good understanding of the Python grammar processed by the |
| 44 | internal parser is required. For full information on the language syntax, refer |
| 45 | to :ref:`reference-index`. The parser |
| 46 | itself is created from a grammar specification defined in the file |
| 47 | :file:`Grammar/Grammar` in the standard Python distribution. The parse trees |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 48 | stored in the ST objects created by this module are the actual output from the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 49 | internal parser when created by the :func:`expr` or :func:`suite` functions, |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 50 | described below. The ST objects created by :func:`sequence2st` faithfully |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 51 | simulate those structures. Be aware that the values of the sequences which are |
| 52 | considered "correct" will vary from one version of Python to another as the |
| 53 | formal grammar for the language is revised. However, transporting code from one |
| 54 | Python version to another as source text will always allow correct parse trees |
| 55 | to be created in the target version, with the only restriction being that |
| 56 | migrating to an older version of the interpreter will not support more recent |
| 57 | language constructs. The parse trees are not typically compatible from one |
| 58 | version to another, whereas source code has always been forward-compatible. |
| 59 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 60 | Each element of the sequences returned by :func:`st2list` or :func:`st2tuple` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 61 | has a simple form. Sequences representing non-terminal elements in the grammar |
| 62 | always have a length greater than one. The first element is an integer which |
| 63 | identifies a production in the grammar. These integers are given symbolic names |
| 64 | in the C header file :file:`Include/graminit.h` and the Python module |
| 65 | :mod:`symbol`. Each additional element of the sequence represents a component |
| 66 | of the production as recognized in the input string: these are always sequences |
| 67 | which have the same form as the parent. An important aspect of this structure |
| 68 | which should be noted is that keywords used to identify the parent node type, |
| 69 | such as the keyword :keyword:`if` in an :const:`if_stmt`, are included in the |
| 70 | node tree without any special treatment. For example, the :keyword:`if` keyword |
| 71 | is represented by the tuple ``(1, 'if')``, where ``1`` is the numeric value |
| 72 | associated with all :const:`NAME` tokens, including variable and function names |
| 73 | defined by the user. In an alternate form returned when line number information |
| 74 | is requested, the same token might be represented as ``(1, 'if', 12)``, where |
| 75 | the ``12`` represents the line number at which the terminal symbol was found. |
| 76 | |
| 77 | Terminal elements are represented in much the same way, but without any child |
| 78 | elements and the addition of the source text which was identified. The example |
| 79 | of the :keyword:`if` keyword above is representative. The various types of |
| 80 | terminal symbols are defined in the C header file :file:`Include/token.h` and |
| 81 | the Python module :mod:`token`. |
| 82 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 83 | The ST objects are not required to support the functionality of this module, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 84 | but are provided for three purposes: to allow an application to amortize the |
| 85 | cost of processing complex parse trees, to provide a parse tree representation |
| 86 | which conserves memory space when compared to the Python list or tuple |
| 87 | representation, and to ease the creation of additional modules in C which |
| 88 | manipulate parse trees. A simple "wrapper" class may be created in Python to |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 89 | hide the use of ST objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 90 | |
| 91 | The :mod:`parser` module defines functions for a few distinct purposes. The |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 92 | most important purposes are to create ST objects and to convert ST objects to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 93 | other representations such as parse trees and compiled code objects, but there |
| 94 | are also functions which serve to query the type of parse tree represented by an |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 95 | ST object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 96 | |
| 97 | |
| 98 | .. seealso:: |
| 99 | |
| 100 | Module :mod:`symbol` |
| 101 | Useful constants representing internal nodes of the parse tree. |
| 102 | |
| 103 | Module :mod:`token` |
| 104 | Useful constants representing leaf nodes of the parse tree and functions for |
| 105 | testing node values. |
| 106 | |
| 107 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 108 | .. _creating-sts: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 109 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 110 | Creating ST Objects |
| 111 | ------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 112 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 113 | ST objects may be created from source code or from a parse tree. When creating |
| 114 | an ST object from source, different functions are used to create the ``'eval'`` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 115 | and ``'exec'`` forms. |
| 116 | |
| 117 | |
| 118 | .. function:: expr(source) |
| 119 | |
| 120 | The :func:`expr` function parses the parameter *source* as if it were an input |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 121 | to ``compile(source, 'file.py', 'eval')``. If the parse succeeds, an ST object |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 122 | is created to hold the internal parse tree representation, otherwise an |
| 123 | appropriate exception is thrown. |
| 124 | |
| 125 | |
| 126 | .. function:: suite(source) |
| 127 | |
| 128 | The :func:`suite` function parses the parameter *source* as if it were an input |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 129 | to ``compile(source, 'file.py', 'exec')``. If the parse succeeds, an ST object |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 130 | is created to hold the internal parse tree representation, otherwise an |
| 131 | appropriate exception is thrown. |
| 132 | |
| 133 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 134 | .. function:: sequence2st(sequence) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 135 | |
| 136 | This function accepts a parse tree represented as a sequence and builds an |
| 137 | internal representation if possible. If it can validate that the tree conforms |
| 138 | to the Python grammar and all nodes are valid node types in the host version of |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 139 | Python, an ST object is created from the internal representation and returned |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 140 | to the called. If there is a problem creating the internal representation, or |
| 141 | if the tree cannot be validated, a :exc:`ParserError` exception is thrown. An |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 142 | ST object created this way should not be assumed to compile correctly; normal |
| 143 | exceptions thrown by compilation may still be initiated when the ST object is |
| 144 | passed to :func:`compilest`. This may indicate problems not related to syntax |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 145 | (such as a :exc:`MemoryError` exception), but may also be due to constructs such |
| 146 | as the result of parsing ``del f(0)``, which escapes the Python parser but is |
| 147 | checked by the bytecode compiler. |
| 148 | |
| 149 | Sequences representing terminal tokens may be represented as either two-element |
| 150 | lists of the form ``(1, 'name')`` or as three-element lists of the form ``(1, |
| 151 | 'name', 56)``. If the third element is present, it is assumed to be a valid |
| 152 | line number. The line number may be specified for any subset of the terminal |
| 153 | symbols in the input tree. |
| 154 | |
| 155 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 156 | .. function:: tuple2st(sequence) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 158 | This is the same function as :func:`sequence2st`. This entry point is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 159 | maintained for backward compatibility. |
| 160 | |
| 161 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 162 | .. _converting-sts: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 163 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 164 | Converting ST Objects |
| 165 | --------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 166 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 167 | ST objects, regardless of the input used to create them, may be converted to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 168 | parse trees represented as list- or tuple- trees, or may be compiled into |
| 169 | executable code objects. Parse trees may be extracted with or without line |
| 170 | numbering information. |
| 171 | |
| 172 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 173 | .. function:: st2list(ast[, line_info]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 175 | This function accepts an ST object from the caller in *ast* and returns a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 176 | Python list representing the equivalent parse tree. The resulting list |
| 177 | representation can be used for inspection or the creation of a new parse tree in |
| 178 | list form. This function does not fail so long as memory is available to build |
| 179 | the list representation. If the parse tree will only be used for inspection, |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 180 | :func:`st2tuple` should be used instead to reduce memory consumption and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | fragmentation. When the list representation is required, this function is |
| 182 | significantly faster than retrieving a tuple representation and converting that |
| 183 | to nested lists. |
| 184 | |
| 185 | If *line_info* is true, line number information will be included for all |
| 186 | terminal tokens as a third element of the list representing the token. Note |
| 187 | that the line number provided specifies the line on which the token *ends*. |
| 188 | This information is omitted if the flag is false or omitted. |
| 189 | |
| 190 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 191 | .. function:: st2tuple(ast[, line_info]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 192 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 193 | This function accepts an ST object from the caller in *ast* and returns a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | Python tuple representing the equivalent parse tree. Other than returning a |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 195 | tuple instead of a list, this function is identical to :func:`st2list`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 196 | |
| 197 | If *line_info* is true, line number information will be included for all |
| 198 | terminal tokens as a third element of the list representing the token. This |
| 199 | information is omitted if the flag is false or omitted. |
| 200 | |
| 201 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 202 | .. function:: compilest(ast[, filename='<syntax-tree>']) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 203 | |
| 204 | .. index:: |
| 205 | builtin: exec |
| 206 | builtin: eval |
| 207 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 208 | The Python byte compiler can be invoked on an ST object to produce code objects |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 209 | which can be used as part of a call to the built-in :func:`exec` or :func:`eval` |
| 210 | functions. This function provides the interface to the compiler, passing the |
| 211 | internal parse tree from *ast* to the parser, using the source file name |
| 212 | specified by the *filename* parameter. The default value supplied for *filename* |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 213 | indicates that the source was an ST object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 214 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 215 | Compiling an ST object may result in exceptions related to compilation; an |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 | example would be a :exc:`SyntaxError` caused by the parse tree for ``del f(0)``: |
| 217 | this statement is considered legal within the formal grammar for Python but is |
| 218 | not a legal language construct. The :exc:`SyntaxError` raised for this |
| 219 | condition is actually generated by the Python byte-compiler normally, which is |
| 220 | why it can be raised at this point by the :mod:`parser` module. Most causes of |
| 221 | compilation failure can be diagnosed programmatically by inspection of the parse |
| 222 | tree. |
| 223 | |
| 224 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 225 | .. _querying-sts: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 226 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 227 | Queries on ST Objects |
| 228 | --------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 230 | Two functions are provided which allow an application to determine if an ST was |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 231 | created as an expression or a suite. Neither of these functions can be used to |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 232 | determine if an ST was created from source code via :func:`expr` or |
| 233 | :func:`suite` or from a parse tree via :func:`sequence2st`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | |
| 235 | |
| 236 | .. function:: isexpr(ast) |
| 237 | |
| 238 | .. index:: builtin: compile |
| 239 | |
| 240 | When *ast* represents an ``'eval'`` form, this function returns true, otherwise |
| 241 | it returns false. This is useful, since code objects normally cannot be queried |
| 242 | for this information using existing built-in functions. Note that the code |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 243 | objects created by :func:`compilest` cannot be queried like this either, and |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 244 | are identical to those created by the built-in :func:`compile` function. |
| 245 | |
| 246 | |
| 247 | .. function:: issuite(ast) |
| 248 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 249 | This function mirrors :func:`isexpr` in that it reports whether an ST object |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 250 | represents an ``'exec'`` form, commonly known as a "suite." It is not safe to |
| 251 | assume that this function is equivalent to ``not isexpr(ast)``, as additional |
| 252 | syntactic fragments may be supported in the future. |
| 253 | |
| 254 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 255 | .. _st-errors: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 256 | |
| 257 | Exceptions and Error Handling |
| 258 | ----------------------------- |
| 259 | |
| 260 | The parser module defines a single exception, but may also pass other built-in |
| 261 | exceptions from other portions of the Python runtime environment. See each |
| 262 | function for information about the exceptions it can raise. |
| 263 | |
| 264 | |
| 265 | .. exception:: ParserError |
| 266 | |
| 267 | Exception raised when a failure occurs within the parser module. This is |
| 268 | generally produced for validation failures rather than the built in |
| 269 | :exc:`SyntaxError` thrown during normal parsing. The exception argument is |
| 270 | either a string describing the reason of the failure or a tuple containing a |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 271 | sequence causing the failure from a parse tree passed to :func:`sequence2st` |
| 272 | and an explanatory string. Calls to :func:`sequence2st` need to be able to |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 273 | handle either type of exception, while calls to other functions in the module |
| 274 | will only need to be aware of the simple string values. |
| 275 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 276 | Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 277 | throw exceptions which are normally thrown by the parsing and compilation |
| 278 | process. These include the built in exceptions :exc:`MemoryError`, |
| 279 | :exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`. In these |
| 280 | cases, these exceptions carry all the meaning normally associated with them. |
| 281 | Refer to the descriptions of each function for detailed information. |
| 282 | |
| 283 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 284 | .. _st-objects: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 285 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 286 | ST Objects |
| 287 | ---------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 288 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 289 | Ordered and equality comparisons are supported between ST objects. Pickling of |
| 290 | ST objects (using the :mod:`pickle` module) is also supported. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 291 | |
| 292 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 293 | .. data:: STType |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 294 | |
| 295 | The type of the objects returned by :func:`expr`, :func:`suite` and |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 296 | :func:`sequence2st`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 297 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 298 | ST objects have the following methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 299 | |
| 300 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 301 | .. method:: ST.compile([filename]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 303 | Same as ``compilest(st, filename)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 304 | |
| 305 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 306 | .. method:: ST.isexpr() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 307 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 308 | Same as ``isexpr(st)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 309 | |
| 310 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 311 | .. method:: ST.issuite() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 312 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 313 | Same as ``issuite(st)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 314 | |
| 315 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 316 | .. method:: ST.tolist([line_info]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 317 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 318 | Same as ``st2list(st, line_info)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 319 | |
| 320 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 321 | .. method:: ST.totuple([line_info]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 322 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 323 | Same as ``st2tuple(st, line_info)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 324 | |
| 325 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 326 | .. _st-examples: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 327 | |
| 328 | Examples |
| 329 | -------- |
| 330 | |
| 331 | .. index:: builtin: compile |
| 332 | |
| 333 | The parser modules allows operations to be performed on the parse tree of Python |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 334 | source code before the :term:`bytecode` is generated, and provides for inspection of the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 335 | parse tree for information gathering purposes. Two examples are presented. The |
| 336 | simple example demonstrates emulation of the :func:`compile` built-in function |
| 337 | and the complex example shows the use of a parse tree for information discovery. |
| 338 | |
| 339 | |
| 340 | Emulation of :func:`compile` |
| 341 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 342 | |
| 343 | While many useful operations may take place between parsing and bytecode |
| 344 | generation, the simplest operation is to do nothing. For this purpose, using |
| 345 | the :mod:`parser` module to produce an intermediate data structure is equivalent |
| 346 | to the code :: |
| 347 | |
| 348 | >>> code = compile('a + 5', 'file.py', 'eval') |
| 349 | >>> a = 5 |
| 350 | >>> eval(code) |
| 351 | 10 |
| 352 | |
| 353 | The equivalent operation using the :mod:`parser` module is somewhat longer, and |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 354 | allows the intermediate internal parse tree to be retained as an ST object:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 355 | |
| 356 | >>> import parser |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 357 | >>> st = parser.expr('a + 5') |
| 358 | >>> code = st.compile('file.py') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 359 | >>> a = 5 |
| 360 | >>> eval(code) |
| 361 | 10 |
| 362 | |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 363 | An application which needs both ST and code objects can package this code into |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 364 | readily available functions:: |
| 365 | |
| 366 | import parser |
| 367 | |
| 368 | def load_suite(source_string): |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 369 | st = parser.suite(source_string) |
| 370 | return st, st.compile() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 371 | |
| 372 | def load_expression(source_string): |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 373 | st = parser.expr(source_string) |
| 374 | return st, st.compile() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | |
| 376 | |
| 377 | Information Discovery |
| 378 | ^^^^^^^^^^^^^^^^^^^^^ |
| 379 | |
| 380 | .. index:: |
| 381 | single: string; documentation |
| 382 | single: docstrings |
| 383 | |
| 384 | Some applications benefit from direct access to the parse tree. The remainder |
| 385 | of this section demonstrates how the parse tree provides access to module |
| 386 | documentation defined in docstrings without requiring that the code being |
| 387 | examined be loaded into a running interpreter via :keyword:`import`. This can |
| 388 | be very useful for performing analyses of untrusted code. |
| 389 | |
| 390 | Generally, the example will demonstrate how the parse tree may be traversed to |
| 391 | distill interesting information. Two functions and a set of classes are |
| 392 | developed which provide programmatic access to high level function and class |
| 393 | definitions provided by a module. The classes extract information from the |
| 394 | parse tree and provide access to the information at a useful semantic level, one |
| 395 | function provides a simple low-level pattern matching capability, and the other |
| 396 | function defines a high-level interface to the classes by handling file |
| 397 | operations on behalf of the caller. All source files mentioned here which are |
| 398 | not part of the Python installation are located in the :file:`Demo/parser/` |
| 399 | directory of the distribution. |
| 400 | |
| 401 | The dynamic nature of Python allows the programmer a great deal of flexibility, |
| 402 | but most modules need only a limited measure of this when defining classes, |
| 403 | functions, and methods. In this example, the only definitions that will be |
| 404 | considered are those which are defined in the top level of their context, e.g., |
| 405 | a function defined by a :keyword:`def` statement at column zero of a module, but |
| 406 | not a function defined within a branch of an :keyword:`if` ... :keyword:`else` |
| 407 | construct, though there are some good reasons for doing so in some situations. |
| 408 | Nesting of definitions will be handled by the code developed in the example. |
| 409 | |
| 410 | To construct the upper-level extraction methods, we need to know what the parse |
| 411 | tree structure looks like and how much of it we actually need to be concerned |
| 412 | about. Python uses a moderately deep parse tree so there are a large number of |
| 413 | intermediate nodes. It is important to read and understand the formal grammar |
| 414 | used by Python. This is specified in the file :file:`Grammar/Grammar` in the |
| 415 | distribution. Consider the simplest case of interest when searching for |
| 416 | docstrings: a module consisting of a docstring and nothing else. (See file |
| 417 | :file:`docstring.py`.) :: |
| 418 | |
| 419 | """Some documentation. |
| 420 | """ |
| 421 | |
| 422 | Using the interpreter to take a look at the parse tree, we find a bewildering |
| 423 | mass of numbers and parentheses, with the documentation buried deep in nested |
| 424 | tuples. :: |
| 425 | |
| 426 | >>> import parser |
| 427 | >>> import pprint |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 428 | >>> st = parser.suite(open('docstring.py').read()) |
| 429 | >>> tup = st.totuple() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 430 | >>> pprint.pprint(tup) |
| 431 | (257, |
| 432 | (264, |
| 433 | (265, |
| 434 | (266, |
| 435 | (267, |
| 436 | (307, |
| 437 | (287, |
| 438 | (288, |
| 439 | (289, |
| 440 | (290, |
| 441 | (292, |
| 442 | (293, |
| 443 | (294, |
| 444 | (295, |
| 445 | (296, |
| 446 | (297, |
| 447 | (298, |
| 448 | (299, |
| 449 | (300, (3, '"""Some documentation.\n"""'))))))))))))))))), |
| 450 | (4, ''))), |
| 451 | (4, ''), |
| 452 | (0, '')) |
| 453 | |
| 454 | The numbers at the first element of each node in the tree are the node types; |
| 455 | they map directly to terminal and non-terminal symbols in the grammar. |
| 456 | Unfortunately, they are represented as integers in the internal representation, |
| 457 | and the Python structures generated do not change that. However, the |
| 458 | :mod:`symbol` and :mod:`token` modules provide symbolic names for the node types |
| 459 | and dictionaries which map from the integers to the symbolic names for the node |
| 460 | types. |
| 461 | |
| 462 | In the output presented above, the outermost tuple contains four elements: the |
| 463 | integer ``257`` and three additional tuples. Node type ``257`` has the symbolic |
| 464 | name :const:`file_input`. Each of these inner tuples contains an integer as the |
| 465 | first element; these integers, ``264``, ``4``, and ``0``, represent the node |
| 466 | types :const:`stmt`, :const:`NEWLINE`, and :const:`ENDMARKER`, respectively. |
| 467 | Note that these values may change depending on the version of Python you are |
| 468 | using; consult :file:`symbol.py` and :file:`token.py` for details of the |
| 469 | mapping. It should be fairly clear that the outermost node is related primarily |
| 470 | to the input source rather than the contents of the file, and may be disregarded |
| 471 | for the moment. The :const:`stmt` node is much more interesting. In |
| 472 | particular, all docstrings are found in subtrees which are formed exactly as |
| 473 | this node is formed, with the only difference being the string itself. The |
| 474 | association between the docstring in a similar tree and the defined entity |
| 475 | (class, function, or module) which it describes is given by the position of the |
| 476 | docstring subtree within the tree defining the described structure. |
| 477 | |
| 478 | By replacing the actual docstring with something to signify a variable component |
| 479 | of the tree, we allow a simple pattern matching approach to check any given |
| 480 | subtree for equivalence to the general pattern for docstrings. Since the |
| 481 | example demonstrates information extraction, we can safely require that the tree |
| 482 | be in tuple form rather than list form, allowing a simple variable |
| 483 | representation to be ``['variable_name']``. A simple recursive function can |
| 484 | implement the pattern matching, returning a Boolean and a dictionary of variable |
| 485 | name to value mappings. (See file :file:`example.py`.) :: |
| 486 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 487 | def match(pattern, data, vars=None): |
| 488 | if vars is None: |
| 489 | vars = {} |
Collin Winter | 1b1498b | 2007-08-28 06:10:19 +0000 | [diff] [blame] | 490 | if isinstance(pattern, list): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 491 | vars[pattern[0]] = data |
Collin Winter | 1b1498b | 2007-08-28 06:10:19 +0000 | [diff] [blame] | 492 | return True, vars |
| 493 | if not instance(pattern, tuple): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 494 | return (pattern == data), vars |
| 495 | if len(data) != len(pattern): |
Collin Winter | 1b1498b | 2007-08-28 06:10:19 +0000 | [diff] [blame] | 496 | return False, vars |
| 497 | for pattern, data in zip(pattern, data): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 498 | same, vars = match(pattern, data, vars) |
| 499 | if not same: |
| 500 | break |
| 501 | return same, vars |
| 502 | |
| 503 | Using this simple representation for syntactic variables and the symbolic node |
| 504 | types, the pattern for the candidate docstring subtrees becomes fairly readable. |
| 505 | (See file :file:`example.py`.) :: |
| 506 | |
| 507 | import symbol |
| 508 | import token |
| 509 | |
| 510 | DOCSTRING_STMT_PATTERN = ( |
| 511 | symbol.stmt, |
| 512 | (symbol.simple_stmt, |
| 513 | (symbol.small_stmt, |
| 514 | (symbol.expr_stmt, |
| 515 | (symbol.testlist, |
| 516 | (symbol.test, |
| 517 | (symbol.and_test, |
| 518 | (symbol.not_test, |
| 519 | (symbol.comparison, |
| 520 | (symbol.expr, |
| 521 | (symbol.xor_expr, |
| 522 | (symbol.and_expr, |
| 523 | (symbol.shift_expr, |
| 524 | (symbol.arith_expr, |
| 525 | (symbol.term, |
| 526 | (symbol.factor, |
| 527 | (symbol.power, |
| 528 | (symbol.atom, |
| 529 | (token.STRING, ['docstring']) |
| 530 | )))))))))))))))), |
| 531 | (token.NEWLINE, '') |
| 532 | )) |
| 533 | |
| 534 | Using the :func:`match` function with this pattern, extracting the module |
| 535 | docstring from the parse tree created previously is easy:: |
| 536 | |
| 537 | >>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1]) |
| 538 | >>> found |
Collin Winter | 1b1498b | 2007-08-28 06:10:19 +0000 | [diff] [blame] | 539 | True |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 540 | >>> vars |
| 541 | {'docstring': '"""Some documentation.\n"""'} |
| 542 | |
| 543 | Once specific data can be extracted from a location where it is expected, the |
| 544 | question of where information can be expected needs to be answered. When |
| 545 | dealing with docstrings, the answer is fairly simple: the docstring is the first |
| 546 | :const:`stmt` node in a code block (:const:`file_input` or :const:`suite` node |
| 547 | types). A module consists of a single :const:`file_input` node, and class and |
| 548 | function definitions each contain exactly one :const:`suite` node. Classes and |
| 549 | functions are readily identified as subtrees of code block nodes which start |
| 550 | with ``(stmt, (compound_stmt, (classdef, ...`` or ``(stmt, (compound_stmt, |
| 551 | (funcdef, ...``. Note that these subtrees cannot be matched by :func:`match` |
| 552 | since it does not support multiple sibling nodes to match without regard to |
| 553 | number. A more elaborate matching function could be used to overcome this |
| 554 | limitation, but this is sufficient for the example. |
| 555 | |
| 556 | Given the ability to determine whether a statement might be a docstring and |
| 557 | extract the actual string from the statement, some work needs to be performed to |
| 558 | walk the parse tree for an entire module and extract information about the names |
| 559 | defined in each context of the module and associate any docstrings with the |
| 560 | names. The code to perform this work is not complicated, but bears some |
| 561 | explanation. |
| 562 | |
| 563 | The public interface to the classes is straightforward and should probably be |
| 564 | somewhat more flexible. Each "major" block of the module is described by an |
| 565 | object providing several methods for inquiry and a constructor which accepts at |
| 566 | least the subtree of the complete parse tree which it represents. The |
| 567 | :class:`ModuleInfo` constructor accepts an optional *name* parameter since it |
| 568 | cannot otherwise determine the name of the module. |
| 569 | |
| 570 | The public classes include :class:`ClassInfo`, :class:`FunctionInfo`, and |
| 571 | :class:`ModuleInfo`. All objects provide the methods :meth:`get_name`, |
| 572 | :meth:`get_docstring`, :meth:`get_class_names`, and :meth:`get_class_info`. The |
| 573 | :class:`ClassInfo` objects support :meth:`get_method_names` and |
| 574 | :meth:`get_method_info` while the other classes provide |
| 575 | :meth:`get_function_names` and :meth:`get_function_info`. |
| 576 | |
| 577 | Within each of the forms of code block that the public classes represent, most |
| 578 | of the required information is in the same form and is accessed in the same way, |
| 579 | with classes having the distinction that functions defined at the top level are |
| 580 | referred to as "methods." Since the difference in nomenclature reflects a real |
| 581 | semantic distinction from functions defined outside of a class, the |
| 582 | implementation needs to maintain the distinction. Hence, most of the |
| 583 | functionality of the public classes can be implemented in a common base class, |
| 584 | :class:`SuiteInfoBase`, with the accessors for function and method information |
| 585 | provided elsewhere. Note that there is only one class which represents function |
| 586 | and method information; this parallels the use of the :keyword:`def` statement |
| 587 | to define both types of elements. |
| 588 | |
| 589 | Most of the accessor functions are declared in :class:`SuiteInfoBase` and do not |
| 590 | need to be overridden by subclasses. More importantly, the extraction of most |
| 591 | information from a parse tree is handled through a method called by the |
| 592 | :class:`SuiteInfoBase` constructor. The example code for most of the classes is |
| 593 | clear when read alongside the formal grammar, but the method which recursively |
| 594 | creates new information objects requires further examination. Here is the |
| 595 | relevant part of the :class:`SuiteInfoBase` definition from :file:`example.py`:: |
| 596 | |
| 597 | class SuiteInfoBase: |
| 598 | _docstring = '' |
| 599 | _name = '' |
| 600 | |
| 601 | def __init__(self, tree = None): |
| 602 | self._class_info = {} |
| 603 | self._function_info = {} |
| 604 | if tree: |
| 605 | self._extract_info(tree) |
| 606 | |
| 607 | def _extract_info(self, tree): |
| 608 | # extract docstring |
| 609 | if len(tree) == 2: |
| 610 | found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1]) |
| 611 | else: |
| 612 | found, vars = match(DOCSTRING_STMT_PATTERN, tree[3]) |
| 613 | if found: |
| 614 | self._docstring = eval(vars['docstring']) |
| 615 | # discover inner definitions |
| 616 | for node in tree[1:]: |
| 617 | found, vars = match(COMPOUND_STMT_PATTERN, node) |
| 618 | if found: |
| 619 | cstmt = vars['compound'] |
| 620 | if cstmt[0] == symbol.funcdef: |
| 621 | name = cstmt[2][1] |
| 622 | self._function_info[name] = FunctionInfo(cstmt) |
| 623 | elif cstmt[0] == symbol.classdef: |
| 624 | name = cstmt[2][1] |
| 625 | self._class_info[name] = ClassInfo(cstmt) |
| 626 | |
| 627 | After initializing some internal state, the constructor calls the |
| 628 | :meth:`_extract_info` method. This method performs the bulk of the information |
| 629 | extraction which takes place in the entire example. The extraction has two |
| 630 | distinct phases: the location of the docstring for the parse tree passed in, and |
| 631 | the discovery of additional definitions within the code block represented by the |
| 632 | parse tree. |
| 633 | |
| 634 | The initial :keyword:`if` test determines whether the nested suite is of the |
| 635 | "short form" or the "long form." The short form is used when the code block is |
| 636 | on the same line as the definition of the code block, as in :: |
| 637 | |
| 638 | def square(x): "Square an argument."; return x ** 2 |
| 639 | |
| 640 | while the long form uses an indented block and allows nested definitions:: |
| 641 | |
| 642 | def make_power(exp): |
| 643 | "Make a function that raises an argument to the exponent `exp'." |
| 644 | def raiser(x, y=exp): |
| 645 | return x ** y |
| 646 | return raiser |
| 647 | |
| 648 | When the short form is used, the code block may contain a docstring as the |
| 649 | first, and possibly only, :const:`small_stmt` element. The extraction of such a |
| 650 | docstring is slightly different and requires only a portion of the complete |
| 651 | pattern used in the more common case. As implemented, the docstring will only |
| 652 | be found if there is only one :const:`small_stmt` node in the |
| 653 | :const:`simple_stmt` node. Since most functions and methods which use the short |
| 654 | form do not provide a docstring, this may be considered sufficient. The |
| 655 | extraction of the docstring proceeds using the :func:`match` function as |
| 656 | described above, and the value of the docstring is stored as an attribute of the |
| 657 | :class:`SuiteInfoBase` object. |
| 658 | |
| 659 | After docstring extraction, a simple definition discovery algorithm operates on |
| 660 | the :const:`stmt` nodes of the :const:`suite` node. The special case of the |
| 661 | short form is not tested; since there are no :const:`stmt` nodes in the short |
| 662 | form, the algorithm will silently skip the single :const:`simple_stmt` node and |
| 663 | correctly not discover any nested definitions. |
| 664 | |
| 665 | Each statement in the code block is categorized as a class definition, function |
| 666 | or method definition, or something else. For the definition statements, the |
| 667 | name of the element defined is extracted and a representation object appropriate |
| 668 | to the definition is created with the defining subtree passed as an argument to |
| 669 | the constructor. The representation objects are stored in instance variables |
| 670 | and may be retrieved by name using the appropriate accessor methods. |
| 671 | |
| 672 | The public classes provide any accessors required which are more specific than |
| 673 | those provided by the :class:`SuiteInfoBase` class, but the real extraction |
| 674 | algorithm remains common to all forms of code blocks. A high-level function can |
| 675 | be used to extract the complete set of information from a source file. (See |
| 676 | file :file:`example.py`.) :: |
| 677 | |
| 678 | def get_docs(fileName): |
| 679 | import os |
| 680 | import parser |
| 681 | |
| 682 | source = open(fileName).read() |
| 683 | basename = os.path.basename(os.path.splitext(fileName)[0]) |
Georg Brandl | 0c77a82 | 2008-06-10 16:37:50 +0000 | [diff] [blame^] | 684 | st = parser.suite(source) |
| 685 | return ModuleInfo(st.totuple(), basename) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 686 | |
| 687 | This provides an easy-to-use interface to the documentation of a module. If |
| 688 | information is required which is not extracted by the code of this example, the |
| 689 | code may be extended at clearly defined points to provide additional |
| 690 | capabilities. |
| 691 | |