/Lib/lib2to3/pytree.py

http://unladen-swallow.googlecode.com/ · Python · 802 lines · 481 code · 67 blank · 254 comment · 118 complexity · ccba1a4f53acf6914c1412f2d765e6b8 MD5 · raw file

  1. # Copyright 2006 Google, Inc. All Rights Reserved.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """Python parse tree definitions.
  4. This is a very concrete parse tree; we need to keep every token and
  5. even the comments and whitespace between tokens.
  6. There's also a pattern matching implementation here.
  7. """
  8. __author__ = "Guido van Rossum <guido@python.org>"
  9. import sys
  10. from StringIO import StringIO
  11. HUGE = 0x7FFFFFFF # maximum repeat count, default max
  12. _type_reprs = {}
  13. def type_repr(type_num):
  14. global _type_reprs
  15. if not _type_reprs:
  16. from .pygram import python_symbols
  17. # printing tokens is possible but not as useful
  18. # from .pgen2 import token // token.__dict__.items():
  19. for name, val in python_symbols.__dict__.items():
  20. if type(val) == int: _type_reprs[val] = name
  21. return _type_reprs.setdefault(type_num, type_num)
  22. class Base(object):
  23. """Abstract base class for Node and Leaf.
  24. This provides some default functionality and boilerplate using the
  25. template pattern.
  26. A node may be a subnode of at most one parent.
  27. """
  28. # Default values for instance variables
  29. type = None # int: token number (< 256) or symbol number (>= 256)
  30. parent = None # Parent node pointer, or None
  31. children = () # Tuple of subnodes
  32. was_changed = False
  33. def __new__(cls, *args, **kwds):
  34. """Constructor that prevents Base from being instantiated."""
  35. assert cls is not Base, "Cannot instantiate Base"
  36. return object.__new__(cls)
  37. def __eq__(self, other):
  38. """Compares two nodes for equality.
  39. This calls the method _eq().
  40. """
  41. if self.__class__ is not other.__class__:
  42. return NotImplemented
  43. return self._eq(other)
  44. def __ne__(self, other):
  45. """Compares two nodes for inequality.
  46. This calls the method _eq().
  47. """
  48. if self.__class__ is not other.__class__:
  49. return NotImplemented
  50. return not self._eq(other)
  51. def _eq(self, other):
  52. """Compares two nodes for equality.
  53. This is called by __eq__ and __ne__. It is only called if the
  54. two nodes have the same type. This must be implemented by the
  55. concrete subclass. Nodes should be considered equal if they
  56. have the same structure, ignoring the prefix string and other
  57. context information.
  58. """
  59. raise NotImplementedError
  60. def clone(self):
  61. """Returns a cloned (deep) copy of self.
  62. This must be implemented by the concrete subclass.
  63. """
  64. raise NotImplementedError
  65. def post_order(self):
  66. """Returns a post-order iterator for the tree.
  67. This must be implemented by the concrete subclass.
  68. """
  69. raise NotImplementedError
  70. def pre_order(self):
  71. """Returns a pre-order iterator for the tree.
  72. This must be implemented by the concrete subclass.
  73. """
  74. raise NotImplementedError
  75. def set_prefix(self, prefix):
  76. """Sets the prefix for the node (see Leaf class).
  77. This must be implemented by the concrete subclass.
  78. """
  79. raise NotImplementedError
  80. def get_prefix(self):
  81. """Returns the prefix for the node (see Leaf class).
  82. This must be implemented by the concrete subclass.
  83. """
  84. raise NotImplementedError
  85. def replace(self, new):
  86. """Replaces this node with a new one in the parent."""
  87. assert self.parent is not None, str(self)
  88. assert new is not None
  89. if not isinstance(new, list):
  90. new = [new]
  91. l_children = []
  92. found = False
  93. for ch in self.parent.children:
  94. if ch is self:
  95. assert not found, (self.parent.children, self, new)
  96. if new is not None:
  97. l_children.extend(new)
  98. found = True
  99. else:
  100. l_children.append(ch)
  101. assert found, (self.children, self, new)
  102. self.parent.changed()
  103. self.parent.children = l_children
  104. for x in new:
  105. x.parent = self.parent
  106. self.parent = None
  107. def get_lineno(self):
  108. """Returns the line number which generated the invocant node."""
  109. node = self
  110. while not isinstance(node, Leaf):
  111. if not node.children:
  112. return
  113. node = node.children[0]
  114. return node.lineno
  115. def changed(self):
  116. if self.parent:
  117. self.parent.changed()
  118. self.was_changed = True
  119. def remove(self):
  120. """Remove the node from the tree. Returns the position of the node
  121. in its parent's children before it was removed."""
  122. if self.parent:
  123. for i, node in enumerate(self.parent.children):
  124. if node is self:
  125. self.parent.changed()
  126. del self.parent.children[i]
  127. self.parent = None
  128. return i
  129. def get_next_sibling(self):
  130. """Return the node immediately following the invocant in their
  131. parent's children list. If the invocant does not have a next
  132. sibling, return None."""
  133. if self.parent is None:
  134. return None
  135. # Can't use index(); we need to test by identity
  136. for i, child in enumerate(self.parent.children):
  137. if child is self:
  138. try:
  139. return self.parent.children[i+1]
  140. except IndexError:
  141. return None
  142. def get_prev_sibling(self):
  143. """Return the node immediately preceding the invocant in their
  144. parent's children list. If the invocant does not have a previous
  145. sibling, return None."""
  146. if self.parent is None:
  147. return None
  148. # Can't use index(); we need to test by identity
  149. for i, child in enumerate(self.parent.children):
  150. if child is self:
  151. if i == 0:
  152. return None
  153. return self.parent.children[i-1]
  154. def get_suffix(self):
  155. """Return the string immediately following the invocant node. This
  156. is effectively equivalent to node.get_next_sibling().get_prefix()"""
  157. next_sib = self.get_next_sibling()
  158. if next_sib is None:
  159. return ""
  160. return next_sib.get_prefix()
  161. class Node(Base):
  162. """Concrete implementation for interior nodes."""
  163. def __init__(self, type, children, context=None, prefix=None):
  164. """Initializer.
  165. Takes a type constant (a symbol number >= 256), a sequence of
  166. child nodes, and an optional context keyword argument.
  167. As a side effect, the parent pointers of the children are updated.
  168. """
  169. assert type >= 256, type
  170. self.type = type
  171. self.children = list(children)
  172. for ch in self.children:
  173. assert ch.parent is None, repr(ch)
  174. ch.parent = self
  175. if prefix is not None:
  176. self.set_prefix(prefix)
  177. def __repr__(self):
  178. """Returns a canonical string representation."""
  179. return "%s(%s, %r)" % (self.__class__.__name__,
  180. type_repr(self.type),
  181. self.children)
  182. def __str__(self):
  183. """Returns a pretty string representation.
  184. This reproduces the input source exactly.
  185. """
  186. return "".join(map(str, self.children))
  187. def _eq(self, other):
  188. """Compares two nodes for equality."""
  189. return (self.type, self.children) == (other.type, other.children)
  190. def clone(self):
  191. """Returns a cloned (deep) copy of self."""
  192. return Node(self.type, [ch.clone() for ch in self.children])
  193. def post_order(self):
  194. """Returns a post-order iterator for the tree."""
  195. for child in self.children:
  196. for node in child.post_order():
  197. yield node
  198. yield self
  199. def pre_order(self):
  200. """Returns a pre-order iterator for the tree."""
  201. yield self
  202. for child in self.children:
  203. for node in child.post_order():
  204. yield node
  205. def set_prefix(self, prefix):
  206. """Sets the prefix for the node.
  207. This passes the responsibility on to the first child.
  208. """
  209. if self.children:
  210. self.children[0].set_prefix(prefix)
  211. def get_prefix(self):
  212. """Returns the prefix for the node.
  213. This passes the call on to the first child.
  214. """
  215. if not self.children:
  216. return ""
  217. return self.children[0].get_prefix()
  218. def set_child(self, i, child):
  219. """Equivalent to 'node.children[i] = child'. This method also sets the
  220. child's parent attribute appropriately."""
  221. child.parent = self
  222. self.children[i].parent = None
  223. self.children[i] = child
  224. self.changed()
  225. def insert_child(self, i, child):
  226. """Equivalent to 'node.children.insert(i, child)'. This method also
  227. sets the child's parent attribute appropriately."""
  228. child.parent = self
  229. self.children.insert(i, child)
  230. self.changed()
  231. def append_child(self, child):
  232. """Equivalent to 'node.children.append(child)'. This method also
  233. sets the child's parent attribute appropriately."""
  234. child.parent = self
  235. self.children.append(child)
  236. self.changed()
  237. class Leaf(Base):
  238. """Concrete implementation for leaf nodes."""
  239. # Default values for instance variables
  240. prefix = "" # Whitespace and comments preceding this token in the input
  241. lineno = 0 # Line where this token starts in the input
  242. column = 0 # Column where this token tarts in the input
  243. def __init__(self, type, value, context=None, prefix=None):
  244. """Initializer.
  245. Takes a type constant (a token number < 256), a string value,
  246. and an optional context keyword argument.
  247. """
  248. assert 0 <= type < 256, type
  249. if context is not None:
  250. self.prefix, (self.lineno, self.column) = context
  251. self.type = type
  252. self.value = value
  253. if prefix is not None:
  254. self.prefix = prefix
  255. def __repr__(self):
  256. """Returns a canonical string representation."""
  257. return "%s(%r, %r)" % (self.__class__.__name__,
  258. self.type,
  259. self.value)
  260. def __str__(self):
  261. """Returns a pretty string representation.
  262. This reproduces the input source exactly.
  263. """
  264. return self.prefix + str(self.value)
  265. def _eq(self, other):
  266. """Compares two nodes for equality."""
  267. return (self.type, self.value) == (other.type, other.value)
  268. def clone(self):
  269. """Returns a cloned (deep) copy of self."""
  270. return Leaf(self.type, self.value,
  271. (self.prefix, (self.lineno, self.column)))
  272. def post_order(self):
  273. """Returns a post-order iterator for the tree."""
  274. yield self
  275. def pre_order(self):
  276. """Returns a pre-order iterator for the tree."""
  277. yield self
  278. def set_prefix(self, prefix):
  279. """Sets the prefix for the node."""
  280. self.changed()
  281. self.prefix = prefix
  282. def get_prefix(self):
  283. """Returns the prefix for the node."""
  284. return self.prefix
  285. def convert(gr, raw_node):
  286. """Converts raw node information to a Node or Leaf instance.
  287. This is passed to the parser driver which calls it whenever a
  288. reduction of a grammar rule produces a new complete node, so that
  289. the tree is build strictly bottom-up.
  290. """
  291. type, value, context, children = raw_node
  292. if children or type in gr.number2symbol:
  293. # If there's exactly one child, return that child instead of
  294. # creating a new node.
  295. if len(children) == 1:
  296. return children[0]
  297. return Node(type, children, context=context)
  298. else:
  299. return Leaf(type, value, context=context)
  300. class BasePattern(object):
  301. """A pattern is a tree matching pattern.
  302. It looks for a specific node type (token or symbol), and
  303. optionally for a specific content.
  304. This is an abstract base class. There are three concrete
  305. subclasses:
  306. - LeafPattern matches a single leaf node;
  307. - NodePattern matches a single node (usually non-leaf);
  308. - WildcardPattern matches a sequence of nodes of variable length.
  309. """
  310. # Defaults for instance variables
  311. type = None # Node type (token if < 256, symbol if >= 256)
  312. content = None # Optional content matching pattern
  313. name = None # Optional name used to store match in results dict
  314. def __new__(cls, *args, **kwds):
  315. """Constructor that prevents BasePattern from being instantiated."""
  316. assert cls is not BasePattern, "Cannot instantiate BasePattern"
  317. return object.__new__(cls)
  318. def __repr__(self):
  319. args = [type_repr(self.type), self.content, self.name]
  320. while args and args[-1] is None:
  321. del args[-1]
  322. return "%s(%s)" % (self.__class__.__name__, ", ".join(map(repr, args)))
  323. def optimize(self):
  324. """A subclass can define this as a hook for optimizations.
  325. Returns either self or another node with the same effect.
  326. """
  327. return self
  328. def match(self, node, results=None):
  329. """Does this pattern exactly match a node?
  330. Returns True if it matches, False if not.
  331. If results is not None, it must be a dict which will be
  332. updated with the nodes matching named subpatterns.
  333. Default implementation for non-wildcard patterns.
  334. """
  335. if self.type is not None and node.type != self.type:
  336. return False
  337. if self.content is not None:
  338. r = None
  339. if results is not None:
  340. r = {}
  341. if not self._submatch(node, r):
  342. return False
  343. if r:
  344. results.update(r)
  345. if results is not None and self.name:
  346. results[self.name] = node
  347. return True
  348. def match_seq(self, nodes, results=None):
  349. """Does this pattern exactly match a sequence of nodes?
  350. Default implementation for non-wildcard patterns.
  351. """
  352. if len(nodes) != 1:
  353. return False
  354. return self.match(nodes[0], results)
  355. def generate_matches(self, nodes):
  356. """Generator yielding all matches for this pattern.
  357. Default implementation for non-wildcard patterns.
  358. """
  359. r = {}
  360. if nodes and self.match(nodes[0], r):
  361. yield 1, r
  362. class LeafPattern(BasePattern):
  363. def __init__(self, type=None, content=None, name=None):
  364. """Initializer. Takes optional type, content, and name.
  365. The type, if given must be a token type (< 256). If not given,
  366. this matches any *leaf* node; the content may still be required.
  367. The content, if given, must be a string.
  368. If a name is given, the matching node is stored in the results
  369. dict under that key.
  370. """
  371. if type is not None:
  372. assert 0 <= type < 256, type
  373. if content is not None:
  374. assert isinstance(content, basestring), repr(content)
  375. self.type = type
  376. self.content = content
  377. self.name = name
  378. def match(self, node, results=None):
  379. """Override match() to insist on a leaf node."""
  380. if not isinstance(node, Leaf):
  381. return False
  382. return BasePattern.match(self, node, results)
  383. def _submatch(self, node, results=None):
  384. """Match the pattern's content to the node's children.
  385. This assumes the node type matches and self.content is not None.
  386. Returns True if it matches, False if not.
  387. If results is not None, it must be a dict which will be
  388. updated with the nodes matching named subpatterns.
  389. When returning False, the results dict may still be updated.
  390. """
  391. return self.content == node.value
  392. class NodePattern(BasePattern):
  393. wildcards = False
  394. def __init__(self, type=None, content=None, name=None):
  395. """Initializer. Takes optional type, content, and name.
  396. The type, if given, must be a symbol type (>= 256). If the
  397. type is None this matches *any* single node (leaf or not),
  398. except if content is not None, in which it only matches
  399. non-leaf nodes that also match the content pattern.
  400. The content, if not None, must be a sequence of Patterns that
  401. must match the node's children exactly. If the content is
  402. given, the type must not be None.
  403. If a name is given, the matching node is stored in the results
  404. dict under that key.
  405. """
  406. if type is not None:
  407. assert type >= 256, type
  408. if content is not None:
  409. assert not isinstance(content, basestring), repr(content)
  410. content = list(content)
  411. for i, item in enumerate(content):
  412. assert isinstance(item, BasePattern), (i, item)
  413. if isinstance(item, WildcardPattern):
  414. self.wildcards = True
  415. self.type = type
  416. self.content = content
  417. self.name = name
  418. def _submatch(self, node, results=None):
  419. """Match the pattern's content to the node's children.
  420. This assumes the node type matches and self.content is not None.
  421. Returns True if it matches, False if not.
  422. If results is not None, it must be a dict which will be
  423. updated with the nodes matching named subpatterns.
  424. When returning False, the results dict may still be updated.
  425. """
  426. if self.wildcards:
  427. for c, r in generate_matches(self.content, node.children):
  428. if c == len(node.children):
  429. if results is not None:
  430. results.update(r)
  431. return True
  432. return False
  433. if len(self.content) != len(node.children):
  434. return False
  435. for subpattern, child in zip(self.content, node.children):
  436. if not subpattern.match(child, results):
  437. return False
  438. return True
  439. class WildcardPattern(BasePattern):
  440. """A wildcard pattern can match zero or more nodes.
  441. This has all the flexibility needed to implement patterns like:
  442. .* .+ .? .{m,n}
  443. (a b c | d e | f)
  444. (...)* (...)+ (...)? (...){m,n}
  445. except it always uses non-greedy matching.
  446. """
  447. def __init__(self, content=None, min=0, max=HUGE, name=None):
  448. """Initializer.
  449. Args:
  450. content: optional sequence of subsequences of patterns;
  451. if absent, matches one node;
  452. if present, each subsequence is an alternative [*]
  453. min: optinal minumum number of times to match, default 0
  454. max: optional maximum number of times tro match, default HUGE
  455. name: optional name assigned to this match
  456. [*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is
  457. equivalent to (a b c | d e | f g h); if content is None,
  458. this is equivalent to '.' in regular expression terms.
  459. The min and max parameters work as follows:
  460. min=0, max=maxint: .*
  461. min=1, max=maxint: .+
  462. min=0, max=1: .?
  463. min=1, max=1: .
  464. If content is not None, replace the dot with the parenthesized
  465. list of alternatives, e.g. (a b c | d e | f g h)*
  466. """
  467. assert 0 <= min <= max <= HUGE, (min, max)
  468. if content is not None:
  469. content = tuple(map(tuple, content)) # Protect against alterations
  470. # Check sanity of alternatives
  471. assert len(content), repr(content) # Can't have zero alternatives
  472. for alt in content:
  473. assert len(alt), repr(alt) # Can have empty alternatives
  474. self.content = content
  475. self.min = min
  476. self.max = max
  477. self.name = name
  478. def optimize(self):
  479. """Optimize certain stacked wildcard patterns."""
  480. subpattern = None
  481. if (self.content is not None and
  482. len(self.content) == 1 and len(self.content[0]) == 1):
  483. subpattern = self.content[0][0]
  484. if self.min == 1 and self.max == 1:
  485. if self.content is None:
  486. return NodePattern(name=self.name)
  487. if subpattern is not None and self.name == subpattern.name:
  488. return subpattern.optimize()
  489. if (self.min <= 1 and isinstance(subpattern, WildcardPattern) and
  490. subpattern.min <= 1 and self.name == subpattern.name):
  491. return WildcardPattern(subpattern.content,
  492. self.min*subpattern.min,
  493. self.max*subpattern.max,
  494. subpattern.name)
  495. return self
  496. def match(self, node, results=None):
  497. """Does this pattern exactly match a node?"""
  498. return self.match_seq([node], results)
  499. def match_seq(self, nodes, results=None):
  500. """Does this pattern exactly match a sequence of nodes?"""
  501. for c, r in self.generate_matches(nodes):
  502. if c == len(nodes):
  503. if results is not None:
  504. results.update(r)
  505. if self.name:
  506. results[self.name] = list(nodes)
  507. return True
  508. return False
  509. def generate_matches(self, nodes):
  510. """Generator yielding matches for a sequence of nodes.
  511. Args:
  512. nodes: sequence of nodes
  513. Yields:
  514. (count, results) tuples where:
  515. count: the match comprises nodes[:count];
  516. results: dict containing named submatches.
  517. """
  518. if self.content is None:
  519. # Shortcut for special case (see __init__.__doc__)
  520. for count in xrange(self.min, 1 + min(len(nodes), self.max)):
  521. r = {}
  522. if self.name:
  523. r[self.name] = nodes[:count]
  524. yield count, r
  525. elif self.name == "bare_name":
  526. yield self._bare_name_matches(nodes)
  527. else:
  528. # The reason for this is that hitting the recursion limit usually
  529. # results in some ugly messages about how RuntimeErrors are being
  530. # ignored.
  531. save_stderr = sys.stderr
  532. sys.stderr = StringIO()
  533. try:
  534. for count, r in self._recursive_matches(nodes, 0):
  535. if self.name:
  536. r[self.name] = nodes[:count]
  537. yield count, r
  538. except RuntimeError:
  539. # We fall back to the iterative pattern matching scheme if the recursive
  540. # scheme hits the recursion limit.
  541. for count, r in self._iterative_matches(nodes):
  542. if self.name:
  543. r[self.name] = nodes[:count]
  544. yield count, r
  545. finally:
  546. sys.stderr = save_stderr
  547. def _iterative_matches(self, nodes):
  548. """Helper to iteratively yield the matches."""
  549. nodelen = len(nodes)
  550. if 0 >= self.min:
  551. yield 0, {}
  552. results = []
  553. # generate matches that use just one alt from self.content
  554. for alt in self.content:
  555. for c, r in generate_matches(alt, nodes):
  556. yield c, r
  557. results.append((c, r))
  558. # for each match, iterate down the nodes
  559. while results:
  560. new_results = []
  561. for c0, r0 in results:
  562. # stop if the entire set of nodes has been matched
  563. if c0 < nodelen and c0 <= self.max:
  564. for alt in self.content:
  565. for c1, r1 in generate_matches(alt, nodes[c0:]):
  566. if c1 > 0:
  567. r = {}
  568. r.update(r0)
  569. r.update(r1)
  570. yield c0 + c1, r
  571. new_results.append((c0 + c1, r))
  572. results = new_results
  573. def _bare_name_matches(self, nodes):
  574. """Special optimized matcher for bare_name."""
  575. count = 0
  576. r = {}
  577. done = False
  578. max = len(nodes)
  579. while not done and count < max:
  580. done = True
  581. for leaf in self.content:
  582. if leaf[0].match(nodes[count], r):
  583. count += 1
  584. done = False
  585. break
  586. r[self.name] = nodes[:count]
  587. return count, r
  588. def _recursive_matches(self, nodes, count):
  589. """Helper to recursively yield the matches."""
  590. assert self.content is not None
  591. if count >= self.min:
  592. yield 0, {}
  593. if count < self.max:
  594. for alt in self.content:
  595. for c0, r0 in generate_matches(alt, nodes):
  596. for c1, r1 in self._recursive_matches(nodes[c0:], count+1):
  597. r = {}
  598. r.update(r0)
  599. r.update(r1)
  600. yield c0 + c1, r
  601. class NegatedPattern(BasePattern):
  602. def __init__(self, content=None):
  603. """Initializer.
  604. The argument is either a pattern or None. If it is None, this
  605. only matches an empty sequence (effectively '$' in regex
  606. lingo). If it is not None, this matches whenever the argument
  607. pattern doesn't have any matches.
  608. """
  609. if content is not None:
  610. assert isinstance(content, BasePattern), repr(content)
  611. self.content = content
  612. def match(self, node):
  613. # We never match a node in its entirety
  614. return False
  615. def match_seq(self, nodes):
  616. # We only match an empty sequence of nodes in its entirety
  617. return len(nodes) == 0
  618. def generate_matches(self, nodes):
  619. if self.content is None:
  620. # Return a match if there is an empty sequence
  621. if len(nodes) == 0:
  622. yield 0, {}
  623. else:
  624. # Return a match if the argument pattern has no matches
  625. for c, r in self.content.generate_matches(nodes):
  626. return
  627. yield 0, {}
  628. def generate_matches(patterns, nodes):
  629. """Generator yielding matches for a sequence of patterns and nodes.
  630. Args:
  631. patterns: a sequence of patterns
  632. nodes: a sequence of nodes
  633. Yields:
  634. (count, results) tuples where:
  635. count: the entire sequence of patterns matches nodes[:count];
  636. results: dict containing named submatches.
  637. """
  638. if not patterns:
  639. yield 0, {}
  640. else:
  641. p, rest = patterns[0], patterns[1:]
  642. for c0, r0 in p.generate_matches(nodes):
  643. if not rest:
  644. yield c0, r0
  645. else:
  646. for c1, r1 in generate_matches(rest, nodes[c0:]):
  647. r = {}
  648. r.update(r0)
  649. r.update(r1)
  650. yield c0 + c1, r