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