parse.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Parser engine for the grammar tables generated by pgen.
  4. The grammar table must be loaded first.
  5. See Parser/parser.c in the Python distribution for additional info on
  6. how this parsing engine works.
  7. """
  8. # Local imports
  9. from . import token
  10. class ParseError(Exception):
  11. """Exception to signal the parser is stuck."""
  12. def __init__(self, msg, type, value, context):
  13. Exception.__init__(self, "%s: type=%r, value=%r, context=%r" %
  14. (msg, type, value, context))
  15. self.msg = msg
  16. self.type = type
  17. self.value = value
  18. self.context = context
  19. def __reduce__(self):
  20. return type(self), (self.msg, self.type, self.value, self.context)
  21. class Parser(object):
  22. """Parser engine.
  23. The proper usage sequence is:
  24. p = Parser(grammar, [converter]) # create instance
  25. p.setup([start]) # prepare for parsing
  26. <for each input token>:
  27. if p.addtoken(...): # parse a token; may raise ParseError
  28. break
  29. root = p.rootnode # root of abstract syntax tree
  30. A Parser instance may be reused by calling setup() repeatedly.
  31. A Parser instance contains state pertaining to the current token
  32. sequence, and should not be used concurrently by different threads
  33. to parse separate token sequences.
  34. See driver.py for how to get input tokens by tokenizing a file or
  35. string.
  36. Parsing is complete when addtoken() returns True; the root of the
  37. abstract syntax tree can then be retrieved from the rootnode
  38. instance variable. When a syntax error occurs, addtoken() raises
  39. the ParseError exception. There is no error recovery; the parser
  40. cannot be used after a syntax error was reported (but it can be
  41. reinitialized by calling setup()).
  42. """
  43. def __init__(self, grammar, convert=None):
  44. """Constructor.
  45. The grammar argument is a grammar.Grammar instance; see the
  46. grammar module for more information.
  47. The parser is not ready yet for parsing; you must call the
  48. setup() method to get it started.
  49. The optional convert argument is a function mapping concrete
  50. syntax tree nodes to abstract syntax tree nodes. If not
  51. given, no conversion is done and the syntax tree produced is
  52. the concrete syntax tree. If given, it must be a function of
  53. two arguments, the first being the grammar (a grammar.Grammar
  54. instance), and the second being the concrete syntax tree node
  55. to be converted. The syntax tree is converted from the bottom
  56. up.
  57. A concrete syntax tree node is a (type, value, context, nodes)
  58. tuple, where type is the node type (a token or symbol number),
  59. value is None for symbols and a string for tokens, context is
  60. None or an opaque value used for error reporting (typically a
  61. (lineno, offset) pair), and nodes is a list of children for
  62. symbols, and None for tokens.
  63. An abstract syntax tree node may be anything; this is entirely
  64. up to the converter function.
  65. """
  66. self.grammar = grammar
  67. self.convert = convert or (lambda grammar, node: node)
  68. def setup(self, start=None):
  69. """Prepare for parsing.
  70. This *must* be called before starting to parse.
  71. The optional argument is an alternative start symbol; it
  72. defaults to the grammar's start symbol.
  73. You can use a Parser instance to parse any number of programs;
  74. each time you call setup() the parser is reset to an initial
  75. state determined by the (implicit or explicit) start symbol.
  76. """
  77. if start is None:
  78. start = self.grammar.start
  79. # Each stack entry is a tuple: (dfa, state, node).
  80. # A node is a tuple: (type, value, context, children),
  81. # where children is a list of nodes or None, and context may be None.
  82. newnode = (start, None, None, [])
  83. stackentry = (self.grammar.dfas[start], 0, newnode)
  84. self.stack = [stackentry]
  85. self.rootnode = None
  86. self.used_names = set() # Aliased to self.rootnode.used_names in pop()
  87. def addtoken(self, type, value, context):
  88. """Add a token; return True iff this is the end of the program."""
  89. # Map from token to label
  90. ilabel = self.classify(type, value, context)
  91. # Loop until the token is shifted; may raise exceptions
  92. while True:
  93. dfa, state, node = self.stack[-1]
  94. states, first = dfa
  95. arcs = states[state]
  96. # Look for a state with this label
  97. for i, newstate in arcs:
  98. t, v = self.grammar.labels[i]
  99. if ilabel == i:
  100. # Look it up in the list of labels
  101. assert t < 256
  102. # Shift a token; we're done with it
  103. self.shift(type, value, newstate, context)
  104. # Pop while we are in an accept-only state
  105. state = newstate
  106. while states[state] == [(0, state)]:
  107. self.pop()
  108. if not self.stack:
  109. # Done parsing!
  110. return True
  111. dfa, state, node = self.stack[-1]
  112. states, first = dfa
  113. # Done with this token
  114. return False
  115. elif t >= 256:
  116. # See if it's a symbol and if we're in its first set
  117. itsdfa = self.grammar.dfas[t]
  118. itsstates, itsfirst = itsdfa
  119. if ilabel in itsfirst:
  120. # Push a symbol
  121. self.push(t, self.grammar.dfas[t], newstate, context)
  122. break # To continue the outer while loop
  123. else:
  124. if (0, state) in arcs:
  125. # An accepting state, pop it and try something else
  126. self.pop()
  127. if not self.stack:
  128. # Done parsing, but another token is input
  129. raise ParseError("too much input",
  130. type, value, context)
  131. else:
  132. # No success finding a transition
  133. raise ParseError("bad input", type, value, context)
  134. def classify(self, type, value, context):
  135. """Turn a token into a label. (Internal)"""
  136. if type == token.NAME:
  137. # Keep a listing of all used names
  138. self.used_names.add(value)
  139. # Check for reserved words
  140. ilabel = self.grammar.keywords.get(value)
  141. if ilabel is not None:
  142. return ilabel
  143. ilabel = self.grammar.tokens.get(type)
  144. if ilabel is None:
  145. raise ParseError("bad token", type, value, context)
  146. return ilabel
  147. def shift(self, type, value, newstate, context):
  148. """Shift a token. (Internal)"""
  149. dfa, state, node = self.stack[-1]
  150. newnode = (type, value, context, None)
  151. newnode = self.convert(self.grammar, newnode)
  152. if newnode is not None:
  153. node[-1].append(newnode)
  154. self.stack[-1] = (dfa, newstate, node)
  155. def push(self, type, newdfa, newstate, context):
  156. """Push a nonterminal. (Internal)"""
  157. dfa, state, node = self.stack[-1]
  158. newnode = (type, None, context, [])
  159. self.stack[-1] = (dfa, newstate, node)
  160. self.stack.append((newdfa, 0, newnode))
  161. def pop(self):
  162. """Pop a nonterminal. (Internal)"""
  163. popdfa, popstate, popnode = self.stack.pop()
  164. newnode = self.convert(self.grammar, popnode)
  165. if newnode is not None:
  166. if self.stack:
  167. dfa, state, node = self.stack[-1]
  168. node[-1].append(newnode)
  169. else:
  170. self.rootnode = newnode
  171. self.rootnode.used_names = self.used_names