blob: fd5fd6c34eebff9fb83a040347f3c7fd921f8cd9 [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
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000156 All :class:`Node` objects offer the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000157
158
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000159 .. method:: getChildren()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000160
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000161 Returns a flattened list of the child nodes and objects in the order they
162 occur. Specifically, the order of the nodes is the order in which they
163 appear in the Python grammar. Not all of the children are :class:`Node`
164 instances. The names of functions and classes, for example, are plain
165 strings.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000166
167
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000168 .. method:: getChildNodes()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000169
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000170 Returns a flattened list of the child nodes in the order they occur. This
171 method is like :meth:`getChildren`, except that it only returns those
172 children that are :class:`Node` instances.
173
Georg Brandl8ec7f652007-08-15 14:28:01 +0000174
175Two examples illustrate the general structure of :class:`Node` classes. The
176:keyword:`while` statement is defined by the following grammar production::
177
178 while_stmt: "while" expression ":" suite
179 ["else" ":" suite]
180
181The :class:`While` node has three attributes: :attr:`test`, :attr:`body`, and
182:attr:`else_`. (If the natural name for an attribute is also a Python reserved
183word, it can't be used as an attribute name. An underscore is appended to the
184word to make it a legal identifier, hence :attr:`else_` instead of
185:keyword:`else`.)
186
187The :keyword:`if` statement is more complicated because it can include several
188tests. ::
189
190 if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
191
192The :class:`If` node only defines two attributes: :attr:`tests` and
193:attr:`else_`. The :attr:`tests` attribute is a sequence of test expression,
194consequent body pairs. There is one pair for each :keyword:`if`/:keyword:`elif`
195clause. The first element of the pair is the test expression. The second
196elements is a :class:`Stmt` node that contains the code to execute if the test
197is true.
198
199The :meth:`getChildren` method of :class:`If` returns a flat list of child
200nodes. If there are three :keyword:`if`/:keyword:`elif` clauses and no
201:keyword:`else` clause, then :meth:`getChildren` will return a list of six
202elements: the first test expression, the first :class:`Stmt`, the second text
203expression, etc.
204
205The following table lists each of the :class:`Node` subclasses defined in
206:mod:`compiler.ast` and each of the public attributes available on their
207instances. The values of most of the attributes are themselves :class:`Node`
208instances or sequences of instances. When the value is something other than an
209instance, the type is noted in the comment. The attributes are listed in the
210order in which they are returned by :meth:`getChildren` and
211:meth:`getChildNodes`.
212
213+-----------------------+--------------------+---------------------------------+
214| Node type | Attribute | Value |
215+=======================+====================+=================================+
216| :class:`Add` | :attr:`left` | left operand |
217+-----------------------+--------------------+---------------------------------+
218| | :attr:`right` | right operand |
219+-----------------------+--------------------+---------------------------------+
220| :class:`And` | :attr:`nodes` | list of operands |
221+-----------------------+--------------------+---------------------------------+
222| :class:`AssAttr` | | *attribute as target of |
223| | | assignment* |
224+-----------------------+--------------------+---------------------------------+
225| | :attr:`expr` | expression on the left-hand |
226| | | side of the dot |
227+-----------------------+--------------------+---------------------------------+
228| | :attr:`attrname` | the attribute name, a string |
229+-----------------------+--------------------+---------------------------------+
230| | :attr:`flags` | XXX |
231+-----------------------+--------------------+---------------------------------+
232| :class:`AssList` | :attr:`nodes` | list of list elements being |
233| | | assigned to |
234+-----------------------+--------------------+---------------------------------+
235| :class:`AssName` | :attr:`name` | name being assigned to |
236+-----------------------+--------------------+---------------------------------+
237| | :attr:`flags` | XXX |
238+-----------------------+--------------------+---------------------------------+
239| :class:`AssTuple` | :attr:`nodes` | list of tuple elements being |
240| | | assigned to |
241+-----------------------+--------------------+---------------------------------+
242| :class:`Assert` | :attr:`test` | the expression to be tested |
243+-----------------------+--------------------+---------------------------------+
244| | :attr:`fail` | the value of the |
245| | | :exc:`AssertionError` |
246+-----------------------+--------------------+---------------------------------+
247| :class:`Assign` | :attr:`nodes` | a list of assignment targets, |
248| | | one per equal sign |
249+-----------------------+--------------------+---------------------------------+
250| | :attr:`expr` | the value being assigned |
251+-----------------------+--------------------+---------------------------------+
252| :class:`AugAssign` | :attr:`node` | |
253+-----------------------+--------------------+---------------------------------+
254| | :attr:`op` | |
255+-----------------------+--------------------+---------------------------------+
256| | :attr:`expr` | |
257+-----------------------+--------------------+---------------------------------+
258| :class:`Backquote` | :attr:`expr` | |
259+-----------------------+--------------------+---------------------------------+
260| :class:`Bitand` | :attr:`nodes` | |
261+-----------------------+--------------------+---------------------------------+
262| :class:`Bitor` | :attr:`nodes` | |
263+-----------------------+--------------------+---------------------------------+
264| :class:`Bitxor` | :attr:`nodes` | |
265+-----------------------+--------------------+---------------------------------+
266| :class:`Break` | | |
267+-----------------------+--------------------+---------------------------------+
268| :class:`CallFunc` | :attr:`node` | expression for the callee |
269+-----------------------+--------------------+---------------------------------+
270| | :attr:`args` | a list of arguments |
271+-----------------------+--------------------+---------------------------------+
272| | :attr:`star_args` | the extended \*-arg value |
273+-----------------------+--------------------+---------------------------------+
274| | :attr:`dstar_args` | the extended \*\*-arg value |
275+-----------------------+--------------------+---------------------------------+
276| :class:`Class` | :attr:`name` | the name of the class, a string |
277+-----------------------+--------------------+---------------------------------+
278| | :attr:`bases` | a list of base classes |
279+-----------------------+--------------------+---------------------------------+
280| | :attr:`doc` | doc string, a string or |
281| | | ``None`` |
282+-----------------------+--------------------+---------------------------------+
283| | :attr:`code` | the body of the class statement |
284+-----------------------+--------------------+---------------------------------+
285| :class:`Compare` | :attr:`expr` | |
286+-----------------------+--------------------+---------------------------------+
287| | :attr:`ops` | |
288+-----------------------+--------------------+---------------------------------+
289| :class:`Const` | :attr:`value` | |
290+-----------------------+--------------------+---------------------------------+
291| :class:`Continue` | | |
292+-----------------------+--------------------+---------------------------------+
293| :class:`Decorators` | :attr:`nodes` | List of function decorator |
294| | | expressions |
295+-----------------------+--------------------+---------------------------------+
296| :class:`Dict` | :attr:`items` | |
297+-----------------------+--------------------+---------------------------------+
298| :class:`Discard` | :attr:`expr` | |
299+-----------------------+--------------------+---------------------------------+
300| :class:`Div` | :attr:`left` | |
301+-----------------------+--------------------+---------------------------------+
302| | :attr:`right` | |
303+-----------------------+--------------------+---------------------------------+
304| :class:`Ellipsis` | | |
305+-----------------------+--------------------+---------------------------------+
306| :class:`Expression` | :attr:`node` | |
307+-----------------------+--------------------+---------------------------------+
308| :class:`Exec` | :attr:`expr` | |
309+-----------------------+--------------------+---------------------------------+
310| | :attr:`locals` | |
311+-----------------------+--------------------+---------------------------------+
312| | :attr:`globals` | |
313+-----------------------+--------------------+---------------------------------+
314| :class:`FloorDiv` | :attr:`left` | |
315+-----------------------+--------------------+---------------------------------+
316| | :attr:`right` | |
317+-----------------------+--------------------+---------------------------------+
318| :class:`For` | :attr:`assign` | |
319+-----------------------+--------------------+---------------------------------+
320| | :attr:`list` | |
321+-----------------------+--------------------+---------------------------------+
322| | :attr:`body` | |
323+-----------------------+--------------------+---------------------------------+
324| | :attr:`else_` | |
325+-----------------------+--------------------+---------------------------------+
326| :class:`From` | :attr:`modname` | |
327+-----------------------+--------------------+---------------------------------+
328| | :attr:`names` | |
329+-----------------------+--------------------+---------------------------------+
330| :class:`Function` | :attr:`decorators` | :class:`Decorators` or ``None`` |
331+-----------------------+--------------------+---------------------------------+
332| | :attr:`name` | name used in def, a string |
333+-----------------------+--------------------+---------------------------------+
334| | :attr:`argnames` | list of argument names, as |
335| | | strings |
336+-----------------------+--------------------+---------------------------------+
337| | :attr:`defaults` | list of default values |
338+-----------------------+--------------------+---------------------------------+
339| | :attr:`flags` | xxx |
340+-----------------------+--------------------+---------------------------------+
341| | :attr:`doc` | doc string, a string or |
342| | | ``None`` |
343+-----------------------+--------------------+---------------------------------+
344| | :attr:`code` | the body of the function |
345+-----------------------+--------------------+---------------------------------+
346| :class:`GenExpr` | :attr:`code` | |
347+-----------------------+--------------------+---------------------------------+
348| :class:`GenExprFor` | :attr:`assign` | |
349+-----------------------+--------------------+---------------------------------+
350| | :attr:`iter` | |
351+-----------------------+--------------------+---------------------------------+
352| | :attr:`ifs` | |
353+-----------------------+--------------------+---------------------------------+
354| :class:`GenExprIf` | :attr:`test` | |
355+-----------------------+--------------------+---------------------------------+
356| :class:`GenExprInner` | :attr:`expr` | |
357+-----------------------+--------------------+---------------------------------+
358| | :attr:`quals` | |
359+-----------------------+--------------------+---------------------------------+
360| :class:`Getattr` | :attr:`expr` | |
361+-----------------------+--------------------+---------------------------------+
362| | :attr:`attrname` | |
363+-----------------------+--------------------+---------------------------------+
364| :class:`Global` | :attr:`names` | |
365+-----------------------+--------------------+---------------------------------+
366| :class:`If` | :attr:`tests` | |
367+-----------------------+--------------------+---------------------------------+
368| | :attr:`else_` | |
369+-----------------------+--------------------+---------------------------------+
370| :class:`Import` | :attr:`names` | |
371+-----------------------+--------------------+---------------------------------+
372| :class:`Invert` | :attr:`expr` | |
373+-----------------------+--------------------+---------------------------------+
374| :class:`Keyword` | :attr:`name` | |
375+-----------------------+--------------------+---------------------------------+
376| | :attr:`expr` | |
377+-----------------------+--------------------+---------------------------------+
378| :class:`Lambda` | :attr:`argnames` | |
379+-----------------------+--------------------+---------------------------------+
380| | :attr:`defaults` | |
381+-----------------------+--------------------+---------------------------------+
382| | :attr:`flags` | |
383+-----------------------+--------------------+---------------------------------+
384| | :attr:`code` | |
385+-----------------------+--------------------+---------------------------------+
386| :class:`LeftShift` | :attr:`left` | |
387+-----------------------+--------------------+---------------------------------+
388| | :attr:`right` | |
389+-----------------------+--------------------+---------------------------------+
390| :class:`List` | :attr:`nodes` | |
391+-----------------------+--------------------+---------------------------------+
392| :class:`ListComp` | :attr:`expr` | |
393+-----------------------+--------------------+---------------------------------+
394| | :attr:`quals` | |
395+-----------------------+--------------------+---------------------------------+
396| :class:`ListCompFor` | :attr:`assign` | |
397+-----------------------+--------------------+---------------------------------+
398| | :attr:`list` | |
399+-----------------------+--------------------+---------------------------------+
400| | :attr:`ifs` | |
401+-----------------------+--------------------+---------------------------------+
402| :class:`ListCompIf` | :attr:`test` | |
403+-----------------------+--------------------+---------------------------------+
404| :class:`Mod` | :attr:`left` | |
405+-----------------------+--------------------+---------------------------------+
406| | :attr:`right` | |
407+-----------------------+--------------------+---------------------------------+
408| :class:`Module` | :attr:`doc` | doc string, a string or |
409| | | ``None`` |
410+-----------------------+--------------------+---------------------------------+
411| | :attr:`node` | body of the module, a |
412| | | :class:`Stmt` |
413+-----------------------+--------------------+---------------------------------+
414| :class:`Mul` | :attr:`left` | |
415+-----------------------+--------------------+---------------------------------+
416| | :attr:`right` | |
417+-----------------------+--------------------+---------------------------------+
418| :class:`Name` | :attr:`name` | |
419+-----------------------+--------------------+---------------------------------+
420| :class:`Not` | :attr:`expr` | |
421+-----------------------+--------------------+---------------------------------+
422| :class:`Or` | :attr:`nodes` | |
423+-----------------------+--------------------+---------------------------------+
424| :class:`Pass` | | |
425+-----------------------+--------------------+---------------------------------+
426| :class:`Power` | :attr:`left` | |
427+-----------------------+--------------------+---------------------------------+
428| | :attr:`right` | |
429+-----------------------+--------------------+---------------------------------+
430| :class:`Print` | :attr:`nodes` | |
431+-----------------------+--------------------+---------------------------------+
432| | :attr:`dest` | |
433+-----------------------+--------------------+---------------------------------+
434| :class:`Printnl` | :attr:`nodes` | |
435+-----------------------+--------------------+---------------------------------+
436| | :attr:`dest` | |
437+-----------------------+--------------------+---------------------------------+
438| :class:`Raise` | :attr:`expr1` | |
439+-----------------------+--------------------+---------------------------------+
440| | :attr:`expr2` | |
441+-----------------------+--------------------+---------------------------------+
442| | :attr:`expr3` | |
443+-----------------------+--------------------+---------------------------------+
444| :class:`Return` | :attr:`value` | |
445+-----------------------+--------------------+---------------------------------+
446| :class:`RightShift` | :attr:`left` | |
447+-----------------------+--------------------+---------------------------------+
448| | :attr:`right` | |
449+-----------------------+--------------------+---------------------------------+
450| :class:`Slice` | :attr:`expr` | |
451+-----------------------+--------------------+---------------------------------+
452| | :attr:`flags` | |
453+-----------------------+--------------------+---------------------------------+
454| | :attr:`lower` | |
455+-----------------------+--------------------+---------------------------------+
456| | :attr:`upper` | |
457+-----------------------+--------------------+---------------------------------+
458| :class:`Sliceobj` | :attr:`nodes` | list of statements |
459+-----------------------+--------------------+---------------------------------+
460| :class:`Stmt` | :attr:`nodes` | |
461+-----------------------+--------------------+---------------------------------+
462| :class:`Sub` | :attr:`left` | |
463+-----------------------+--------------------+---------------------------------+
464| | :attr:`right` | |
465+-----------------------+--------------------+---------------------------------+
466| :class:`Subscript` | :attr:`expr` | |
467+-----------------------+--------------------+---------------------------------+
468| | :attr:`flags` | |
469+-----------------------+--------------------+---------------------------------+
470| | :attr:`subs` | |
471+-----------------------+--------------------+---------------------------------+
472| :class:`TryExcept` | :attr:`body` | |
473+-----------------------+--------------------+---------------------------------+
474| | :attr:`handlers` | |
475+-----------------------+--------------------+---------------------------------+
476| | :attr:`else_` | |
477+-----------------------+--------------------+---------------------------------+
478| :class:`TryFinally` | :attr:`body` | |
479+-----------------------+--------------------+---------------------------------+
480| | :attr:`final` | |
481+-----------------------+--------------------+---------------------------------+
482| :class:`Tuple` | :attr:`nodes` | |
483+-----------------------+--------------------+---------------------------------+
484| :class:`UnaryAdd` | :attr:`expr` | |
485+-----------------------+--------------------+---------------------------------+
486| :class:`UnarySub` | :attr:`expr` | |
487+-----------------------+--------------------+---------------------------------+
488| :class:`While` | :attr:`test` | |
489+-----------------------+--------------------+---------------------------------+
490| | :attr:`body` | |
491+-----------------------+--------------------+---------------------------------+
492| | :attr:`else_` | |
493+-----------------------+--------------------+---------------------------------+
494| :class:`With` | :attr:`expr` | |
495+-----------------------+--------------------+---------------------------------+
496| | :attr:`vars` | |
497+-----------------------+--------------------+---------------------------------+
498| | :attr:`body` | |
499+-----------------------+--------------------+---------------------------------+
500| :class:`Yield` | :attr:`value` | |
501+-----------------------+--------------------+---------------------------------+
502
503
504Assignment nodes
505----------------
506
507There is a collection of nodes used to represent assignments. Each assignment
508statement in the source code becomes a single :class:`Assign` node in the AST.
509The :attr:`nodes` attribute is a list that contains a node for each assignment
510target. This is necessary because assignment can be chained, e.g. ``a = b =
5112``. Each :class:`Node` in the list will be one of the following classes:
512:class:`AssAttr`, :class:`AssList`, :class:`AssName`, or :class:`AssTuple`.
513
514Each target assignment node will describe the kind of object being assigned to:
515:class:`AssName` for a simple name, e.g. ``a = 1``. :class:`AssAttr` for an
516attribute assigned, e.g. ``a.x = 1``. :class:`AssList` and :class:`AssTuple` for
517list and tuple expansion respectively, e.g. ``a, b, c = a_tuple``.
518
519The target assignment nodes also have a :attr:`flags` attribute that indicates
520whether the node is being used for assignment or in a delete statement. The
521:class:`AssName` is also used to represent a delete statement, e.g. :class:`del
522x`.
523
524When an expression contains several attribute references, an assignment or
525delete statement will contain only one :class:`AssAttr` node -- for the final
526attribute reference. The other attribute references will be represented as
527:class:`Getattr` nodes in the :attr:`expr` attribute of the :class:`AssAttr`
528instance.
529
530
531Examples
532--------
533
534This section shows several simple examples of ASTs for Python source code. The
535examples demonstrate how to use the :func:`parse` function, what the repr of an
536AST looks like, and how to access attributes of an AST node.
537
538The first module defines a single function. Assume it is stored in
539:file:`/tmp/doublelib.py`. ::
540
541 """This is an example module.
542
543 This is the docstring.
544 """
545
546 def double(x):
547 "Return twice the argument"
548 return x * 2
549
550In the interactive interpreter session below, I have reformatted the long AST
551reprs for readability. The AST reprs use unqualified class names. If you want
552to create an instance from a repr, you must import the class names from the
553:mod:`compiler.ast` module. ::
554
555 >>> import compiler
556 >>> mod = compiler.parseFile("/tmp/doublelib.py")
557 >>> mod
558 Module('This is an example module.\n\nThis is the docstring.\n',
559 Stmt([Function(None, 'double', ['x'], [], 0,
560 'Return twice the argument',
561 Stmt([Return(Mul((Name('x'), Const(2))))]))]))
562 >>> from compiler.ast import *
563 >>> Module('This is an example module.\n\nThis is the docstring.\n',
564 ... Stmt([Function(None, 'double', ['x'], [], 0,
565 ... 'Return twice the argument',
566 ... Stmt([Return(Mul((Name('x'), Const(2))))]))]))
567 Module('This is an example module.\n\nThis is the docstring.\n',
568 Stmt([Function(None, 'double', ['x'], [], 0,
569 'Return twice the argument',
570 Stmt([Return(Mul((Name('x'), Const(2))))]))]))
571 >>> mod.doc
572 'This is an example module.\n\nThis is the docstring.\n'
573 >>> for node in mod.node.nodes:
574 ... print node
575 ...
576 Function(None, 'double', ['x'], [], 0, 'Return twice the argument',
577 Stmt([Return(Mul((Name('x'), Const(2))))]))
578 >>> func = mod.node.nodes[0]
579 >>> func.code
580 Stmt([Return(Mul((Name('x'), Const(2))))])
581
582
583Using Visitors to Walk ASTs
584===========================
585
586.. module:: compiler.visitor
587
588
589The visitor pattern is ... The :mod:`compiler` package uses a variant on the
590visitor pattern that takes advantage of Python's introspection features to
591eliminate the need for much of the visitor's infrastructure.
592
593The classes being visited do not need to be programmed to accept visitors. The
594visitor need only define visit methods for classes it is specifically interested
595in; a default visit method can handle the rest.
596
597XXX The magic :meth:`visit` method for visitors.
598
599
600.. function:: walk(tree, visitor[, verbose])
601
602
603.. class:: ASTVisitor()
604
605 The :class:`ASTVisitor` is responsible for walking over the tree in the correct
606 order. A walk begins with a call to :meth:`preorder`. For each node, it checks
607 the *visitor* argument to :meth:`preorder` for a method named 'visitNodeType,'
608 where NodeType is the name of the node's class, e.g. for a :class:`While` node a
609 :meth:`visitWhile` would be called. If the method exists, it is called with the
610 node as its first argument.
611
612 The visitor method for a particular node type can control how child nodes are
613 visited during the walk. The :class:`ASTVisitor` modifies the visitor argument
614 by adding a visit method to the visitor; this method can be used to visit a
615 particular child node. If no visitor is found for a particular node type, the
616 :meth:`default` method is called.
617
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000618 :class:`ASTVisitor` objects have the following methods:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000619
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000620 XXX describe extra arguments
Georg Brandl8ec7f652007-08-15 14:28:01 +0000621
622
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000623 .. method:: default(node[, ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000624
625
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000626 .. method:: dispatch(node[, ...])
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627
628
Benjamin Petersonc7b05922008-04-25 01:29:10 +0000629 .. method:: preorder(tree, visitor)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000630
631
632Bytecode Generation
633===================
634
635The code generator is a visitor that emits bytecodes. Each visit method can
636call the :meth:`emit` method to emit a new bytecode. The basic code generator
637is specialized for modules, classes, and functions. An assembler converts that
638emitted instructions to the low-level bytecode format. It handles things like
Georg Brandlcf3fb252007-10-21 10:52:38 +0000639generation of constant lists of code objects and calculation of jump offsets.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000640