/Demo/parser/example.py

http://unladen-swallow.googlecode.com/ · Python · 190 lines · 145 code · 28 blank · 17 comment · 24 complexity · 79b641ff026fada1f22579cf307c16f3 MD5 · raw file

  1. """Simple code to extract class & function docstrings from a module.
  2. This code is used as an example in the library reference manual in the
  3. section on using the parser module. Refer to the manual for a thorough
  4. discussion of the operation of this code.
  5. """
  6. import os
  7. import parser
  8. import symbol
  9. import token
  10. import types
  11. from types import ListType, TupleType
  12. def get_docs(fileName):
  13. """Retrieve information from the parse tree of a source file.
  14. fileName
  15. Name of the file to read Python source code from.
  16. """
  17. source = open(fileName).read()
  18. basename = os.path.basename(os.path.splitext(fileName)[0])
  19. ast = parser.suite(source)
  20. return ModuleInfo(ast.totuple(), basename)
  21. class SuiteInfoBase:
  22. _docstring = ''
  23. _name = ''
  24. def __init__(self, tree = None):
  25. self._class_info = {}
  26. self._function_info = {}
  27. if tree:
  28. self._extract_info(tree)
  29. def _extract_info(self, tree):
  30. # extract docstring
  31. if len(tree) == 2:
  32. found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
  33. else:
  34. found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
  35. if found:
  36. self._docstring = eval(vars['docstring'])
  37. # discover inner definitions
  38. for node in tree[1:]:
  39. found, vars = match(COMPOUND_STMT_PATTERN, node)
  40. if found:
  41. cstmt = vars['compound']
  42. if cstmt[0] == symbol.funcdef:
  43. name = cstmt[2][1]
  44. self._function_info[name] = FunctionInfo(cstmt)
  45. elif cstmt[0] == symbol.classdef:
  46. name = cstmt[2][1]
  47. self._class_info[name] = ClassInfo(cstmt)
  48. def get_docstring(self):
  49. return self._docstring
  50. def get_name(self):
  51. return self._name
  52. def get_class_names(self):
  53. return self._class_info.keys()
  54. def get_class_info(self, name):
  55. return self._class_info[name]
  56. def __getitem__(self, name):
  57. try:
  58. return self._class_info[name]
  59. except KeyError:
  60. return self._function_info[name]
  61. class SuiteFuncInfo:
  62. # Mixin class providing access to function names and info.
  63. def get_function_names(self):
  64. return self._function_info.keys()
  65. def get_function_info(self, name):
  66. return self._function_info[name]
  67. class FunctionInfo(SuiteInfoBase, SuiteFuncInfo):
  68. def __init__(self, tree = None):
  69. self._name = tree[2][1]
  70. SuiteInfoBase.__init__(self, tree and tree[-1] or None)
  71. class ClassInfo(SuiteInfoBase):
  72. def __init__(self, tree = None):
  73. self._name = tree[2][1]
  74. SuiteInfoBase.__init__(self, tree and tree[-1] or None)
  75. def get_method_names(self):
  76. return self._function_info.keys()
  77. def get_method_info(self, name):
  78. return self._function_info[name]
  79. class ModuleInfo(SuiteInfoBase, SuiteFuncInfo):
  80. def __init__(self, tree = None, name = "<string>"):
  81. self._name = name
  82. SuiteInfoBase.__init__(self, tree)
  83. if tree:
  84. found, vars = match(DOCSTRING_STMT_PATTERN, tree[1])
  85. if found:
  86. self._docstring = vars["docstring"]
  87. def match(pattern, data, vars=None):
  88. """Match `data' to `pattern', with variable extraction.
  89. pattern
  90. Pattern to match against, possibly containing variables.
  91. data
  92. Data to be checked and against which variables are extracted.
  93. vars
  94. Dictionary of variables which have already been found. If not
  95. provided, an empty dictionary is created.
  96. The `pattern' value may contain variables of the form ['varname'] which
  97. are allowed to match anything. The value that is matched is returned as
  98. part of a dictionary which maps 'varname' to the matched value. 'varname'
  99. is not required to be a string object, but using strings makes patterns
  100. and the code which uses them more readable.
  101. This function returns two values: a boolean indicating whether a match
  102. was found and a dictionary mapping variable names to their associated
  103. values.
  104. """
  105. if vars is None:
  106. vars = {}
  107. if type(pattern) is ListType: # 'variables' are ['varname']
  108. vars[pattern[0]] = data
  109. return 1, vars
  110. if type(pattern) is not TupleType:
  111. return (pattern == data), vars
  112. if len(data) != len(pattern):
  113. return 0, vars
  114. for pattern, data in map(None, pattern, data):
  115. same, vars = match(pattern, data, vars)
  116. if not same:
  117. break
  118. return same, vars
  119. # This pattern identifies compound statements, allowing them to be readily
  120. # differentiated from simple statements.
  121. #
  122. COMPOUND_STMT_PATTERN = (
  123. symbol.stmt,
  124. (symbol.compound_stmt, ['compound'])
  125. )
  126. # This pattern will match a 'stmt' node which *might* represent a docstring;
  127. # docstrings require that the statement which provides the docstring be the
  128. # first statement in the class or function, which this pattern does not check.
  129. #
  130. DOCSTRING_STMT_PATTERN = (
  131. symbol.stmt,
  132. (symbol.simple_stmt,
  133. (symbol.small_stmt,
  134. (symbol.expr_stmt,
  135. (symbol.testlist,
  136. (symbol.test,
  137. (symbol.and_test,
  138. (symbol.not_test,
  139. (symbol.comparison,
  140. (symbol.expr,
  141. (symbol.xor_expr,
  142. (symbol.and_expr,
  143. (symbol.shift_expr,
  144. (symbol.arith_expr,
  145. (symbol.term,
  146. (symbol.factor,
  147. (symbol.power,
  148. (symbol.atom,
  149. (token.STRING, ['docstring'])
  150. )))))))))))))))),
  151. (token.NEWLINE, '')
  152. ))