/Doc/library/compiler.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 644 lines · 534 code · 110 blank · 0 comment · 0 complexity · 9faa21e5e8e8032ff91bdf0c51c8f4f0 MD5 · raw file

  1. .. _compiler:
  2. ***********************
  3. Python compiler package
  4. ***********************
  5. .. deprecated:: 2.6
  6. The :mod:`compiler` package has been removed in Python 3.0.
  7. .. sectionauthor:: Jeremy Hylton <jeremy@zope.com>
  8. The Python compiler package is a tool for analyzing Python source code and
  9. generating Python bytecode. The compiler contains libraries to generate an
  10. abstract syntax tree from Python source code and to generate Python
  11. :term:`bytecode` from the tree.
  12. The :mod:`compiler` package is a Python source to bytecode translator written in
  13. Python. It uses the built-in parser and standard :mod:`parser` module to
  14. generated a concrete syntax tree. This tree is used to generate an abstract
  15. syntax tree (AST) and then Python bytecode.
  16. The full functionality of the package duplicates the builtin compiler provided
  17. with the Python interpreter. It is intended to match its behavior almost
  18. exactly. Why implement another compiler that does the same thing? The package
  19. is useful for a variety of purposes. It can be modified more easily than the
  20. builtin compiler. The AST it generates is useful for analyzing Python source
  21. code.
  22. This chapter explains how the various components of the :mod:`compiler` package
  23. work. It blends reference material with a tutorial.
  24. The basic interface
  25. ===================
  26. .. module:: compiler
  27. :synopsis: Python code compiler written in Python.
  28. :deprecated:
  29. The top-level of the package defines four functions. If you import
  30. :mod:`compiler`, you will get these functions and a collection of modules
  31. contained in the package.
  32. .. function:: parse(buf)
  33. Returns an abstract syntax tree for the Python source code in *buf*. The
  34. function raises :exc:`SyntaxError` if there is an error in the source code. The
  35. return value is a :class:`compiler.ast.Module` instance that contains the tree.
  36. .. function:: parseFile(path)
  37. Return an abstract syntax tree for the Python source code in the file specified
  38. by *path*. It is equivalent to ``parse(open(path).read())``.
  39. .. function:: walk(ast, visitor[, verbose])
  40. Do a pre-order walk over the abstract syntax tree *ast*. Call the appropriate
  41. method on the *visitor* instance for each node encountered.
  42. .. function:: compile(source, filename, mode, flags=None, dont_inherit=None)
  43. Compile the string *source*, a Python module, statement or expression, into a
  44. code object that can be executed by the exec statement or :func:`eval`. This
  45. function is a replacement for the built-in :func:`compile` function.
  46. The *filename* will be used for run-time error messages.
  47. The *mode* must be 'exec' to compile a module, 'single' to compile a single
  48. (interactive) statement, or 'eval' to compile an expression.
  49. The *flags* and *dont_inherit* arguments affect future-related statements, but
  50. are not supported yet.
  51. .. function:: compileFile(source)
  52. Compiles the file *source* and generates a .pyc file.
  53. The :mod:`compiler` package contains the following modules: :mod:`ast`,
  54. :mod:`consts`, :mod:`future`, :mod:`misc`, :mod:`pyassem`, :mod:`pycodegen`,
  55. :mod:`symbols`, :mod:`transformer`, and :mod:`visitor`.
  56. Limitations
  57. ===========
  58. There are some problems with the error checking of the compiler package. The
  59. interpreter detects syntax errors in two distinct phases. One set of errors is
  60. detected by the interpreter's parser, the other set by the compiler. The
  61. compiler package relies on the interpreter's parser, so it get the first phases
  62. of error checking for free. It implements the second phase itself, and that
  63. implementation is incomplete. For example, the compiler package does not raise
  64. an error if a name appears more than once in an argument list: ``def f(x, x):
  65. ...``
  66. A future version of the compiler should fix these problems.
  67. Python Abstract Syntax
  68. ======================
  69. The :mod:`compiler.ast` module defines an abstract syntax for Python. In the
  70. abstract syntax tree, each node represents a syntactic construct. The root of
  71. the tree is :class:`Module` object.
  72. The abstract syntax offers a higher level interface to parsed Python source
  73. code. The :mod:`parser` module and the compiler written in C for the Python
  74. interpreter use a concrete syntax tree. The concrete syntax is tied closely to
  75. the grammar description used for the Python parser. Instead of a single node
  76. for a construct, there are often several levels of nested nodes that are
  77. introduced by Python's precedence rules.
  78. The abstract syntax tree is created by the :mod:`compiler.transformer` module.
  79. The transformer relies on the builtin Python parser to generate a concrete
  80. syntax tree. It generates an abstract syntax tree from the concrete tree.
  81. .. index::
  82. single: Stein, Greg
  83. single: Tutt, Bill
  84. The :mod:`transformer` module was created by Greg Stein and Bill Tutt for an
  85. experimental Python-to-C compiler. The current version contains a number of
  86. modifications and improvements, but the basic form of the abstract syntax and of
  87. the transformer are due to Stein and Tutt.
  88. AST Nodes
  89. ---------
  90. .. module:: compiler.ast
  91. The :mod:`compiler.ast` module is generated from a text file that describes each
  92. node type and its elements. Each node type is represented as a class that
  93. inherits from the abstract base class :class:`compiler.ast.Node` and defines a
  94. set of named attributes for child nodes.
  95. .. class:: Node()
  96. The :class:`Node` instances are created automatically by the parser generator.
  97. The recommended interface for specific :class:`Node` instances is to use the
  98. public attributes to access child nodes. A public attribute may be bound to a
  99. single node or to a sequence of nodes, depending on the :class:`Node` type. For
  100. example, the :attr:`bases` attribute of the :class:`Class` node, is bound to a
  101. list of base class nodes, and the :attr:`doc` attribute is bound to a single
  102. node.
  103. Each :class:`Node` instance has a :attr:`lineno` attribute which may be
  104. ``None``. XXX Not sure what the rules are for which nodes will have a useful
  105. lineno.
  106. All :class:`Node` objects offer the following methods:
  107. .. method:: getChildren()
  108. Returns a flattened list of the child nodes and objects in the order they
  109. occur. Specifically, the order of the nodes is the order in which they
  110. appear in the Python grammar. Not all of the children are :class:`Node`
  111. instances. The names of functions and classes, for example, are plain
  112. strings.
  113. .. method:: getChildNodes()
  114. Returns a flattened list of the child nodes in the order they occur. This
  115. method is like :meth:`getChildren`, except that it only returns those
  116. children that are :class:`Node` instances.
  117. Two examples illustrate the general structure of :class:`Node` classes. The
  118. :keyword:`while` statement is defined by the following grammar production::
  119. while_stmt: "while" expression ":" suite
  120. ["else" ":" suite]
  121. The :class:`While` node has three attributes: :attr:`test`, :attr:`body`, and
  122. :attr:`else_`. (If the natural name for an attribute is also a Python reserved
  123. word, it can't be used as an attribute name. An underscore is appended to the
  124. word to make it a legal identifier, hence :attr:`else_` instead of
  125. :keyword:`else`.)
  126. The :keyword:`if` statement is more complicated because it can include several
  127. tests. ::
  128. if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  129. The :class:`If` node only defines two attributes: :attr:`tests` and
  130. :attr:`else_`. The :attr:`tests` attribute is a sequence of test expression,
  131. consequent body pairs. There is one pair for each :keyword:`if`/:keyword:`elif`
  132. clause. The first element of the pair is the test expression. The second
  133. elements is a :class:`Stmt` node that contains the code to execute if the test
  134. is true.
  135. The :meth:`getChildren` method of :class:`If` returns a flat list of child
  136. nodes. If there are three :keyword:`if`/:keyword:`elif` clauses and no
  137. :keyword:`else` clause, then :meth:`getChildren` will return a list of six
  138. elements: the first test expression, the first :class:`Stmt`, the second text
  139. expression, etc.
  140. The following table lists each of the :class:`Node` subclasses defined in
  141. :mod:`compiler.ast` and each of the public attributes available on their
  142. instances. The values of most of the attributes are themselves :class:`Node`
  143. instances or sequences of instances. When the value is something other than an
  144. instance, the type is noted in the comment. The attributes are listed in the
  145. order in which they are returned by :meth:`getChildren` and
  146. :meth:`getChildNodes`.
  147. +-----------------------+--------------------+---------------------------------+
  148. | Node type | Attribute | Value |
  149. +=======================+====================+=================================+
  150. | :class:`Add` | :attr:`left` | left operand |
  151. +-----------------------+--------------------+---------------------------------+
  152. | | :attr:`right` | right operand |
  153. +-----------------------+--------------------+---------------------------------+
  154. | :class:`And` | :attr:`nodes` | list of operands |
  155. +-----------------------+--------------------+---------------------------------+
  156. | :class:`AssAttr` | | *attribute as target of |
  157. | | | assignment* |
  158. +-----------------------+--------------------+---------------------------------+
  159. | | :attr:`expr` | expression on the left-hand |
  160. | | | side of the dot |
  161. +-----------------------+--------------------+---------------------------------+
  162. | | :attr:`attrname` | the attribute name, a string |
  163. +-----------------------+--------------------+---------------------------------+
  164. | | :attr:`flags` | XXX |
  165. +-----------------------+--------------------+---------------------------------+
  166. | :class:`AssList` | :attr:`nodes` | list of list elements being |
  167. | | | assigned to |
  168. +-----------------------+--------------------+---------------------------------+
  169. | :class:`AssName` | :attr:`name` | name being assigned to |
  170. +-----------------------+--------------------+---------------------------------+
  171. | | :attr:`flags` | XXX |
  172. +-----------------------+--------------------+---------------------------------+
  173. | :class:`AssTuple` | :attr:`nodes` | list of tuple elements being |
  174. | | | assigned to |
  175. +-----------------------+--------------------+---------------------------------+
  176. | :class:`Assert` | :attr:`test` | the expression to be tested |
  177. +-----------------------+--------------------+---------------------------------+
  178. | | :attr:`fail` | the value of the |
  179. | | | :exc:`AssertionError` |
  180. +-----------------------+--------------------+---------------------------------+
  181. | :class:`Assign` | :attr:`nodes` | a list of assignment targets, |
  182. | | | one per equal sign |
  183. +-----------------------+--------------------+---------------------------------+
  184. | | :attr:`expr` | the value being assigned |
  185. +-----------------------+--------------------+---------------------------------+
  186. | :class:`AugAssign` | :attr:`node` | |
  187. +-----------------------+--------------------+---------------------------------+
  188. | | :attr:`op` | |
  189. +-----------------------+--------------------+---------------------------------+
  190. | | :attr:`expr` | |
  191. +-----------------------+--------------------+---------------------------------+
  192. | :class:`Backquote` | :attr:`expr` | |
  193. +-----------------------+--------------------+---------------------------------+
  194. | :class:`Bitand` | :attr:`nodes` | |
  195. +-----------------------+--------------------+---------------------------------+
  196. | :class:`Bitor` | :attr:`nodes` | |
  197. +-----------------------+--------------------+---------------------------------+
  198. | :class:`Bitxor` | :attr:`nodes` | |
  199. +-----------------------+--------------------+---------------------------------+
  200. | :class:`Break` | | |
  201. +-----------------------+--------------------+---------------------------------+
  202. | :class:`CallFunc` | :attr:`node` | expression for the callee |
  203. +-----------------------+--------------------+---------------------------------+
  204. | | :attr:`args` | a list of arguments |
  205. +-----------------------+--------------------+---------------------------------+
  206. | | :attr:`star_args` | the extended \*-arg value |
  207. +-----------------------+--------------------+---------------------------------+
  208. | | :attr:`dstar_args` | the extended \*\*-arg value |
  209. +-----------------------+--------------------+---------------------------------+
  210. | :class:`Class` | :attr:`name` | the name of the class, a string |
  211. +-----------------------+--------------------+---------------------------------+
  212. | | :attr:`bases` | a list of base classes |
  213. +-----------------------+--------------------+---------------------------------+
  214. | | :attr:`doc` | doc string, a string or |
  215. | | | ``None`` |
  216. +-----------------------+--------------------+---------------------------------+
  217. | | :attr:`code` | the body of the class statement |
  218. +-----------------------+--------------------+---------------------------------+
  219. | :class:`Compare` | :attr:`expr` | |
  220. +-----------------------+--------------------+---------------------------------+
  221. | | :attr:`ops` | |
  222. +-----------------------+--------------------+---------------------------------+
  223. | :class:`Const` | :attr:`value` | |
  224. +-----------------------+--------------------+---------------------------------+
  225. | :class:`Continue` | | |
  226. +-----------------------+--------------------+---------------------------------+
  227. | :class:`Decorators` | :attr:`nodes` | List of function decorator |
  228. | | | expressions |
  229. +-----------------------+--------------------+---------------------------------+
  230. | :class:`Dict` | :attr:`items` | |
  231. +-----------------------+--------------------+---------------------------------+
  232. | :class:`Discard` | :attr:`expr` | |
  233. +-----------------------+--------------------+---------------------------------+
  234. | :class:`Div` | :attr:`left` | |
  235. +-----------------------+--------------------+---------------------------------+
  236. | | :attr:`right` | |
  237. +-----------------------+--------------------+---------------------------------+
  238. | :class:`Ellipsis` | | |
  239. +-----------------------+--------------------+---------------------------------+
  240. | :class:`Expression` | :attr:`node` | |
  241. +-----------------------+--------------------+---------------------------------+
  242. | :class:`Exec` | :attr:`expr` | |
  243. +-----------------------+--------------------+---------------------------------+
  244. | | :attr:`locals` | |
  245. +-----------------------+--------------------+---------------------------------+
  246. | | :attr:`globals` | |
  247. +-----------------------+--------------------+---------------------------------+
  248. | :class:`FloorDiv` | :attr:`left` | |
  249. +-----------------------+--------------------+---------------------------------+
  250. | | :attr:`right` | |
  251. +-----------------------+--------------------+---------------------------------+
  252. | :class:`For` | :attr:`assign` | |
  253. +-----------------------+--------------------+---------------------------------+
  254. | | :attr:`list` | |
  255. +-----------------------+--------------------+---------------------------------+
  256. | | :attr:`body` | |
  257. +-----------------------+--------------------+---------------------------------+
  258. | | :attr:`else_` | |
  259. +-----------------------+--------------------+---------------------------------+
  260. | :class:`From` | :attr:`modname` | |
  261. +-----------------------+--------------------+---------------------------------+
  262. | | :attr:`names` | |
  263. +-----------------------+--------------------+---------------------------------+
  264. | :class:`Function` | :attr:`decorators` | :class:`Decorators` or ``None`` |
  265. +-----------------------+--------------------+---------------------------------+
  266. | | :attr:`name` | name used in def, a string |
  267. +-----------------------+--------------------+---------------------------------+
  268. | | :attr:`argnames` | list of argument names, as |
  269. | | | strings |
  270. +-----------------------+--------------------+---------------------------------+
  271. | | :attr:`defaults` | list of default values |
  272. +-----------------------+--------------------+---------------------------------+
  273. | | :attr:`flags` | xxx |
  274. +-----------------------+--------------------+---------------------------------+
  275. | | :attr:`doc` | doc string, a string or |
  276. | | | ``None`` |
  277. +-----------------------+--------------------+---------------------------------+
  278. | | :attr:`code` | the body of the function |
  279. +-----------------------+--------------------+---------------------------------+
  280. | :class:`GenExpr` | :attr:`code` | |
  281. +-----------------------+--------------------+---------------------------------+
  282. | :class:`GenExprFor` | :attr:`assign` | |
  283. +-----------------------+--------------------+---------------------------------+
  284. | | :attr:`iter` | |
  285. +-----------------------+--------------------+---------------------------------+
  286. | | :attr:`ifs` | |
  287. +-----------------------+--------------------+---------------------------------+
  288. | :class:`GenExprIf` | :attr:`test` | |
  289. +-----------------------+--------------------+---------------------------------+
  290. | :class:`GenExprInner` | :attr:`expr` | |
  291. +-----------------------+--------------------+---------------------------------+
  292. | | :attr:`quals` | |
  293. +-----------------------+--------------------+---------------------------------+
  294. | :class:`Getattr` | :attr:`expr` | |
  295. +-----------------------+--------------------+---------------------------------+
  296. | | :attr:`attrname` | |
  297. +-----------------------+--------------------+---------------------------------+
  298. | :class:`Global` | :attr:`names` | |
  299. +-----------------------+--------------------+---------------------------------+
  300. | :class:`If` | :attr:`tests` | |
  301. +-----------------------+--------------------+---------------------------------+
  302. | | :attr:`else_` | |
  303. +-----------------------+--------------------+---------------------------------+
  304. | :class:`Import` | :attr:`names` | |
  305. +-----------------------+--------------------+---------------------------------+
  306. | :class:`Invert` | :attr:`expr` | |
  307. +-----------------------+--------------------+---------------------------------+
  308. | :class:`Keyword` | :attr:`name` | |
  309. +-----------------------+--------------------+---------------------------------+
  310. | | :attr:`expr` | |
  311. +-----------------------+--------------------+---------------------------------+
  312. | :class:`Lambda` | :attr:`argnames` | |
  313. +-----------------------+--------------------+---------------------------------+
  314. | | :attr:`defaults` | |
  315. +-----------------------+--------------------+---------------------------------+
  316. | | :attr:`flags` | |
  317. +-----------------------+--------------------+---------------------------------+
  318. | | :attr:`code` | |
  319. +-----------------------+--------------------+---------------------------------+
  320. | :class:`LeftShift` | :attr:`left` | |
  321. +-----------------------+--------------------+---------------------------------+
  322. | | :attr:`right` | |
  323. +-----------------------+--------------------+---------------------------------+
  324. | :class:`List` | :attr:`nodes` | |
  325. +-----------------------+--------------------+---------------------------------+
  326. | :class:`ListComp` | :attr:`expr` | |
  327. +-----------------------+--------------------+---------------------------------+
  328. | | :attr:`quals` | |
  329. +-----------------------+--------------------+---------------------------------+
  330. | :class:`ListCompFor` | :attr:`assign` | |
  331. +-----------------------+--------------------+---------------------------------+
  332. | | :attr:`list` | |
  333. +-----------------------+--------------------+---------------------------------+
  334. | | :attr:`ifs` | |
  335. +-----------------------+--------------------+---------------------------------+
  336. | :class:`ListCompIf` | :attr:`test` | |
  337. +-----------------------+--------------------+---------------------------------+
  338. | :class:`Mod` | :attr:`left` | |
  339. +-----------------------+--------------------+---------------------------------+
  340. | | :attr:`right` | |
  341. +-----------------------+--------------------+---------------------------------+
  342. | :class:`Module` | :attr:`doc` | doc string, a string or |
  343. | | | ``None`` |
  344. +-----------------------+--------------------+---------------------------------+
  345. | | :attr:`node` | body of the module, a |
  346. | | | :class:`Stmt` |
  347. +-----------------------+--------------------+---------------------------------+
  348. | :class:`Mul` | :attr:`left` | |
  349. +-----------------------+--------------------+---------------------------------+
  350. | | :attr:`right` | |
  351. +-----------------------+--------------------+---------------------------------+
  352. | :class:`Name` | :attr:`name` | |
  353. +-----------------------+--------------------+---------------------------------+
  354. | :class:`Not` | :attr:`expr` | |
  355. +-----------------------+--------------------+---------------------------------+
  356. | :class:`Or` | :attr:`nodes` | |
  357. +-----------------------+--------------------+---------------------------------+
  358. | :class:`Pass` | | |
  359. +-----------------------+--------------------+---------------------------------+
  360. | :class:`Power` | :attr:`left` | |
  361. +-----------------------+--------------------+---------------------------------+
  362. | | :attr:`right` | |
  363. +-----------------------+--------------------+---------------------------------+
  364. | :class:`Print` | :attr:`nodes` | |
  365. +-----------------------+--------------------+---------------------------------+
  366. | | :attr:`dest` | |
  367. +-----------------------+--------------------+---------------------------------+
  368. | :class:`Printnl` | :attr:`nodes` | |
  369. +-----------------------+--------------------+---------------------------------+
  370. | | :attr:`dest` | |
  371. +-----------------------+--------------------+---------------------------------+
  372. | :class:`Raise` | :attr:`expr1` | |
  373. +-----------------------+--------------------+---------------------------------+
  374. | | :attr:`expr2` | |
  375. +-----------------------+--------------------+---------------------------------+
  376. | | :attr:`expr3` | |
  377. +-----------------------+--------------------+---------------------------------+
  378. | :class:`Return` | :attr:`value` | |
  379. +-----------------------+--------------------+---------------------------------+
  380. | :class:`RightShift` | :attr:`left` | |
  381. +-----------------------+--------------------+---------------------------------+
  382. | | :attr:`right` | |
  383. +-----------------------+--------------------+---------------------------------+
  384. | :class:`Slice` | :attr:`expr` | |
  385. +-----------------------+--------------------+---------------------------------+
  386. | | :attr:`flags` | |
  387. +-----------------------+--------------------+---------------------------------+
  388. | | :attr:`lower` | |
  389. +-----------------------+--------------------+---------------------------------+
  390. | | :attr:`upper` | |
  391. +-----------------------+--------------------+---------------------------------+
  392. | :class:`Sliceobj` | :attr:`nodes` | list of statements |
  393. +-----------------------+--------------------+---------------------------------+
  394. | :class:`Stmt` | :attr:`nodes` | |
  395. +-----------------------+--------------------+---------------------------------+
  396. | :class:`Sub` | :attr:`left` | |
  397. +-----------------------+--------------------+---------------------------------+
  398. | | :attr:`right` | |
  399. +-----------------------+--------------------+---------------------------------+
  400. | :class:`Subscript` | :attr:`expr` | |
  401. +-----------------------+--------------------+---------------------------------+
  402. | | :attr:`flags` | |
  403. +-----------------------+--------------------+---------------------------------+
  404. | | :attr:`subs` | |
  405. +-----------------------+--------------------+---------------------------------+
  406. | :class:`TryExcept` | :attr:`body` | |
  407. +-----------------------+--------------------+---------------------------------+
  408. | | :attr:`handlers` | |
  409. +-----------------------+--------------------+---------------------------------+
  410. | | :attr:`else_` | |
  411. +-----------------------+--------------------+---------------------------------+
  412. | :class:`TryFinally` | :attr:`body` | |
  413. +-----------------------+--------------------+---------------------------------+
  414. | | :attr:`final` | |
  415. +-----------------------+--------------------+---------------------------------+
  416. | :class:`Tuple` | :attr:`nodes` | |
  417. +-----------------------+--------------------+---------------------------------+
  418. | :class:`UnaryAdd` | :attr:`expr` | |
  419. +-----------------------+--------------------+---------------------------------+
  420. | :class:`UnarySub` | :attr:`expr` | |
  421. +-----------------------+--------------------+---------------------------------+
  422. | :class:`While` | :attr:`test` | |
  423. +-----------------------+--------------------+---------------------------------+
  424. | | :attr:`body` | |
  425. +-----------------------+--------------------+---------------------------------+
  426. | | :attr:`else_` | |
  427. +-----------------------+--------------------+---------------------------------+
  428. | :class:`With` | :attr:`expr` | |
  429. +-----------------------+--------------------+---------------------------------+
  430. | | :attr:`vars` | |
  431. +-----------------------+--------------------+---------------------------------+
  432. | | :attr:`body` | |
  433. +-----------------------+--------------------+---------------------------------+
  434. | :class:`Yield` | :attr:`value` | |
  435. +-----------------------+--------------------+---------------------------------+
  436. Assignment nodes
  437. ----------------
  438. There is a collection of nodes used to represent assignments. Each assignment
  439. statement in the source code becomes a single :class:`Assign` node in the AST.
  440. The :attr:`nodes` attribute is a list that contains a node for each assignment
  441. target. This is necessary because assignment can be chained, e.g. ``a = b =
  442. 2``. Each :class:`Node` in the list will be one of the following classes:
  443. :class:`AssAttr`, :class:`AssList`, :class:`AssName`, or :class:`AssTuple`.
  444. Each target assignment node will describe the kind of object being assigned to:
  445. :class:`AssName` for a simple name, e.g. ``a = 1``. :class:`AssAttr` for an
  446. attribute assigned, e.g. ``a.x = 1``. :class:`AssList` and :class:`AssTuple` for
  447. list and tuple expansion respectively, e.g. ``a, b, c = a_tuple``.
  448. The target assignment nodes also have a :attr:`flags` attribute that indicates
  449. whether the node is being used for assignment or in a delete statement. The
  450. :class:`AssName` is also used to represent a delete statement, e.g. :class:`del
  451. x`.
  452. When an expression contains several attribute references, an assignment or
  453. delete statement will contain only one :class:`AssAttr` node -- for the final
  454. attribute reference. The other attribute references will be represented as
  455. :class:`Getattr` nodes in the :attr:`expr` attribute of the :class:`AssAttr`
  456. instance.
  457. Examples
  458. --------
  459. This section shows several simple examples of ASTs for Python source code. The
  460. examples demonstrate how to use the :func:`parse` function, what the repr of an
  461. AST looks like, and how to access attributes of an AST node.
  462. The first module defines a single function. Assume it is stored in
  463. :file:`/tmp/doublelib.py`. ::
  464. """This is an example module.
  465. This is the docstring.
  466. """
  467. def double(x):
  468. "Return twice the argument"
  469. return x * 2
  470. In the interactive interpreter session below, I have reformatted the long AST
  471. reprs for readability. The AST reprs use unqualified class names. If you want
  472. to create an instance from a repr, you must import the class names from the
  473. :mod:`compiler.ast` module. ::
  474. >>> import compiler
  475. >>> mod = compiler.parseFile("/tmp/doublelib.py")
  476. >>> mod
  477. Module('This is an example module.\n\nThis is the docstring.\n',
  478. Stmt([Function(None, 'double', ['x'], [], 0,
  479. 'Return twice the argument',
  480. Stmt([Return(Mul((Name('x'), Const(2))))]))]))
  481. >>> from compiler.ast import *
  482. >>> Module('This is an example module.\n\nThis is the docstring.\n',
  483. ... Stmt([Function(None, 'double', ['x'], [], 0,
  484. ... 'Return twice the argument',
  485. ... Stmt([Return(Mul((Name('x'), Const(2))))]))]))
  486. Module('This is an example module.\n\nThis is the docstring.\n',
  487. Stmt([Function(None, 'double', ['x'], [], 0,
  488. 'Return twice the argument',
  489. Stmt([Return(Mul((Name('x'), Const(2))))]))]))
  490. >>> mod.doc
  491. 'This is an example module.\n\nThis is the docstring.\n'
  492. >>> for node in mod.node.nodes:
  493. ... print node
  494. ...
  495. Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
  496. Stmt([Return(Mul((Name('x'), Const(2))))]))
  497. >>> func = mod.node.nodes[0]
  498. >>> func.code
  499. Stmt([Return(Mul((Name('x'), Const(2))))])
  500. Using Visitors to Walk ASTs
  501. ===========================
  502. .. module:: compiler.visitor
  503. The visitor pattern is ... The :mod:`compiler` package uses a variant on the
  504. visitor pattern that takes advantage of Python's introspection features to
  505. eliminate the need for much of the visitor's infrastructure.
  506. The classes being visited do not need to be programmed to accept visitors. The
  507. visitor need only define visit methods for classes it is specifically interested
  508. in; a default visit method can handle the rest.
  509. XXX The magic :meth:`visit` method for visitors.
  510. .. function:: walk(tree, visitor[, verbose])
  511. .. class:: ASTVisitor()
  512. The :class:`ASTVisitor` is responsible for walking over the tree in the correct
  513. order. A walk begins with a call to :meth:`preorder`. For each node, it checks
  514. the *visitor* argument to :meth:`preorder` for a method named 'visitNodeType,'
  515. where NodeType is the name of the node's class, e.g. for a :class:`While` node a
  516. :meth:`visitWhile` would be called. If the method exists, it is called with the
  517. node as its first argument.
  518. The visitor method for a particular node type can control how child nodes are
  519. visited during the walk. The :class:`ASTVisitor` modifies the visitor argument
  520. by adding a visit method to the visitor; this method can be used to visit a
  521. particular child node. If no visitor is found for a particular node type, the
  522. :meth:`default` method is called.
  523. :class:`ASTVisitor` objects have the following methods:
  524. XXX describe extra arguments
  525. .. method:: default(node[, ...])
  526. .. method:: dispatch(node[, ...])
  527. .. method:: preorder(tree, visitor)
  528. Bytecode Generation
  529. ===================
  530. The code generator is a visitor that emits bytecodes. Each visit method can
  531. call the :meth:`emit` method to emit a new bytecode. The basic code generator
  532. is specialized for modules, classes, and functions. An assembler converts that
  533. emitted instructions to the low-level bytecode format. It handles things like
  534. generation of constant lists of code objects and calculation of jump offsets.