@@ -1626,37 +1626,6 @@ def simpleMatch(token, pattern):
16261626 '<*>' : lambda tok : tok .link if tok .str == '<' and tok .link else None ,
16271627}
16281628
1629- def match_atom (token , p ):
1630- if not token :
1631- return None
1632- if not p :
1633- return None
1634- if token .str == p :
1635- return token
1636- if p in ['!' , '|' , '||' , '%' , '!=' , '*' ]:
1637- return None
1638- if p in patterns :
1639- return patterns [p ](token )
1640- if '|' in p :
1641- for x in p .split ('|' ):
1642- t = match_atom (token , x )
1643- if t :
1644- return t
1645- elif p .startswith ('!!' ):
1646- t = match_atom (token , p [2 :])
1647- if not t :
1648- return token
1649- elif p .startswith ('**' ):
1650- a = p [2 :]
1651- t = token
1652- while t :
1653- if match_atom (t , a ):
1654- return t
1655- if t .link and t .str in ['(' , '[' , '<' , '{' ]:
1656- t = t .link
1657- t = t .next
1658- return None
1659-
16601629class MatchResult :
16611630 def __init__ (self , matches , bindings = None , keys = None ):
16621631 self .__dict__ .update (bindings or {})
@@ -1680,22 +1649,139 @@ def bind_split(s):
16801649 return (p [0 ], p [2 ])
16811650 return (s , None )
16821651
1652+ class CompiledPattern :
1653+ """
1654+ A match() pattern compiled once so it can be matched against many tokens.
1655+
1656+ Each word of the pattern is compiled into a matcher: a function that takes
1657+ a token (never None) and returns the last token the word matched, or None.
1658+
1659+ Attributes:
1660+ pattern The pattern string
1661+ atoms List of (matcher, binding name) for each word in the pattern
1662+ failed The MatchResult returned when the pattern does not match
1663+ """
1664+
1665+ _literal_atoms = frozenset (['!' , '|' , '||' , '|=' , '%' , '!=' , '*' ])
1666+ _link_open = frozenset (['(' , '[' , '<' , '{' ])
1667+
1668+ def __init__ (self , pattern ):
1669+ self .pattern = pattern
1670+ words = [bind_split (word ) for word in pattern .split ()]
1671+ self .atoms = [(self .compile_atom (p ), b ) for p , b in words ]
1672+ keys = [b for p , b in words ] + ['end' ] if words else []
1673+ self .failed = MatchResult (False , keys = keys )
1674+
1675+ def __repr__ (self ):
1676+ return "CompiledPattern(pattern={})" .format (repr (self .pattern ))
1677+
1678+ def match (self , token ):
1679+ if not self .atoms :
1680+ # empty pattern (or only whitespace) never matches
1681+ return self .failed
1682+ end = None
1683+ bindings = {}
1684+ for m , b in self .atoms :
1685+ if token is None :
1686+ return self .failed
1687+ t = m (token )
1688+ if b :
1689+ bindings [b ] = token
1690+ if t is None :
1691+ return self .failed
1692+ end = t
1693+ token = t .next
1694+ bindings ['end' ] = end
1695+ return MatchResult (True , bindings = bindings )
1696+
1697+ @classmethod
1698+ def compile_atom (cls , p ):
1699+ """Compile one pattern word into a matcher."""
1700+ if not p :
1701+ return cls ._match_none
1702+ if p in cls ._literal_atoms :
1703+ return cls ._match_literal (p )
1704+ if p in patterns :
1705+ return patterns [p ]
1706+ prefix , word = p [:2 ], p [2 :]
1707+ if prefix == '!!' :
1708+ # as in the C++ Token::Match, '!!' is checked before alternation
1709+ # and the rest is compared as a whole: '!!a|b' is "not the token a|b"
1710+ inner = cls ._match_literal (word ) if '|' in word else cls .compile_atom (word )
1711+ return cls ._match_negation (inner )
1712+ if prefix == '**' :
1713+ # '**a|b' searches ahead for a or b
1714+ return cls ._match_forward (cls .compile_atom (word ))
1715+ if '|' in p :
1716+ return cls ._match_alternatives ([cls .compile_atom (x ) for x in p .split ('|' )])
1717+ return cls ._match_literal (p )
1718+
1719+ @staticmethod
1720+ def _match_none (tok ):
1721+ return None
1722+
1723+ @staticmethod
1724+ def _match_literal (p ):
1725+ def m (tok ):
1726+ return tok if tok .str == p else None
1727+ return m
1728+
1729+ @staticmethod
1730+ def _match_alternatives (alternatives ):
1731+ def m (tok ):
1732+ for a in alternatives :
1733+ t = a (tok )
1734+ if t :
1735+ return t
1736+ return None
1737+ return m
1738+
1739+ @staticmethod
1740+ def _match_negation (inner ):
1741+ def m (tok ):
1742+ return None if inner (tok ) else tok
1743+ return m
1744+
1745+ @classmethod
1746+ def _match_forward (cls , inner ):
1747+ link_open = cls ._link_open
1748+ def m (tok ):
1749+ t = tok
1750+ while t :
1751+ if inner (t ):
1752+ return t
1753+ if t .link and t .str in link_open :
1754+ t = t .link
1755+ t = t .next
1756+ return None
1757+ return m
1758+
1759+ @functools .lru_cache (maxsize = 1024 )
1760+ def compile_pattern (pattern ):
1761+ """
1762+ Return the CompiledPattern for a pattern string.
1763+
1764+ The most recently used patterns are kept, so compiling the same pattern
1765+ string again is cheap.
1766+ """
1767+ return CompiledPattern (pattern )
1768+
16831769def match (token , pattern ):
1770+ """
1771+ Match the tokens starting at token against pattern.
1772+
1773+ Returns a MatchResult, which is true when the pattern matches.
1774+
1775+ Use constant pattern strings. A pattern is compiled the first time it is
1776+ used and only a limited number of compiled patterns are kept, so a pattern
1777+ string built at run time, such as name + ' (', is compiled again for every
1778+ new string. Compare the varying part separately instead:
1779+
1780+ match(tok, '%name% (') and tok.str == name
1781+ """
16841782 if not pattern :
16851783 return MatchResult (False )
1686- end = None
1687- bindings = {}
1688- words = [bind_split (word ) for word in pattern .split ()]
1689- for p , b in words :
1690- t = match_atom (token , p )
1691- if b :
1692- bindings [b ] = token
1693- if not t :
1694- return MatchResult (False , keys = [xx for pp , xx in words ]+ ['end' ])
1695- end = t
1696- token = t .next
1697- bindings ['end' ] = end
1698- return MatchResult (True , bindings = bindings )
1784+ return compile_pattern (pattern ).match (token )
16991785
17001786def get_function_call_name_args (token ):
17011787 """Get function name and arguments for function call
0 commit comments