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