pytree.py 27 KB

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