Skip to content

Commit 3eae36d

Browse files
authored
cppcheckdata.py: compile match() patterns once (#8999)
`cppcheckdata.match()` re-parsed its pattern string on every call: it split the pattern, split off the `@` bindings, and `match_atom()` ran through a chain of `in`/`startswith` checks for each word before doing the actual comparison. On a failed match it also rebuilt the list of binding keys and allocated a new `MatchResult`. Since an addon typically matches the same handful of pattern strings against every token, almost all of this work was repeated. This PR adds a `CompiledPattern` class that compiles a pattern string once into a list of per-word matcher functions, plus a precomputed `MatchResult` for the failed case. `match(token, pattern)` keeps its signature and looks the compiled pattern up in a cache keyed by the pattern string. The internal `match_atom()` helper is removed; its logic is now `CompiledPattern.compile_atom()`. Two behavior changes, both for degenerate patterns: - A whitespace-only pattern used to report a successful match (with `end = None`). It now fails, the same as an empty pattern. - `|=` is now a literal word. Previously the `|` in it was also read as an alternation of `''` and `=`, so the pattern `|=` matched a `=` token as well. Also `!!||`, `!!|`, `**||` and `**|` no longer split on `|` either. (The C++ `Token::Match` still has that quirk; the Python side no longer shares it.) ## Performance Measured on the first configuration of a `lib/token.cpp` dump (49,349 tokens), Python 3. 12 patterns (`if (*) {`, `%name% (*) ;`, `%var%@lhs = %var%@OP1 | %var%@OP2 ;`, `struct|class %name% {`, `%name% !!(`, `for (*) {*}`, `%comp%`, `::`, …) matched against every token, ~592k calls: | | before | after | speedup | |---|---|---|---| | total time | 0.78 s | 0.21 s | ~3.7× | | per call | ~1.3 µs | ~0.36 µs | | 200,000 calls of `match(tok, '%name% (*) ;')` on one token (per-call overhead, no matching work): | | before | after | speedup | |---|---|---|---| | total time | 0.23 s | 0.04 s | ~5.5× | One-time compile cost per distinct pattern (not cached per word; happens once per pattern string): | pattern | compile | |---|---| | `if (*) {` | 1.6 µs | | `%var%@lhs = %var%@OP1 \| %var%@OP2 ;` | 2.3 µs | | `struct\|class %name% {` | 2.0 µs | | `**{` | 1.3 µs |
1 parent 76fba8d commit 3eae36d

3 files changed

Lines changed: 225 additions & 44 deletions

File tree

‎addons/cppcheckdata.py‎

Lines changed: 130 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -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-
16601629
class 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+
16831769
def 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

17001786
def get_function_call_name_args(token):
17011787
"""Get function name and arguments for function call

‎test/addon/conftest.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ class Shape {
139139
int arr[3];
140140
arr[0] = a;
141141
a += 1;
142+
a |= b;
142143
if (a > b) {
143144
return a;
144145
}

‎test/addon/test_cppcheckdata.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -523,6 +523,7 @@ def test_literal_sequence(self, match_cfg):
523523
def test_empty_pattern_and_no_token(self, match_cfg):
524524
calc_def = find_token(match_cfg, 'calc')
525525
assert not cppcheckdata.match(calc_def, '')
526+
assert not cppcheckdata.match(calc_def, None)
526527
assert not cppcheckdata.match(None, 'calc')
527528

528529
def test_end(self, match_cfg):
@@ -572,6 +573,23 @@ def test_literal_percent(self, match_cfg):
572573
assert cppcheckdata.match(mod, '%')
573574
assert cppcheckdata.match(mod.previous, '%var% % %var% ;')
574575

576+
def test_literal_or_assign(self, match_cfg):
577+
or_assign = find_token(match_cfg, '|=')
578+
assert cppcheckdata.match(or_assign, '|=')
579+
assert cppcheckdata.match(or_assign.previous, '%var% |= %var% ;')
580+
assert cppcheckdata.match(or_assign, '%assign%')
581+
assert not cppcheckdata.match(find_token(match_cfg, '|'), '|=')
582+
# '|=' is a literal, not an alternation of '' and '='
583+
# (unlike the C++ Token::Match, which also matches a '=' token here)
584+
assert not cppcheckdata.match(find_token(match_cfg, '='), '|=')
585+
586+
def test_whitespace_only_pattern(self, match_cfg):
587+
calc_def = find_token(match_cfg, 'calc')
588+
res = cppcheckdata.match(calc_def, ' ')
589+
assert not res
590+
with pytest.raises(AttributeError):
591+
res.end # pylint: disable=W0104
592+
575593
def test_literal_parentheses(self, match_cfg):
576594
calc_call = find_token(match_cfg, 'calc', skip=1)
577595
assert cppcheckdata.match(calc_call, 'calc ( %var% , %var% ) ;')
@@ -696,6 +714,65 @@ def test_negation_keyword(self, match_cfg):
696714
assert cppcheckdata.match(calc_call, '%name% !!%op%')
697715
assert not cppcheckdata.match(calc_call, '%name% !!(')
698716

717+
def test_negation_literal_or_assign(self, match_cfg):
718+
# '!!|=' is "not |=", not an alternation of '!!' and '='
719+
or_assign = find_token(match_cfg, '|=')
720+
assert not cppcheckdata.match(or_assign.previous, '%var% !!|=')
721+
bit_or = find_token(match_cfg, '|')
722+
assert cppcheckdata.match(bit_or.previous, '%var% !!|=')
723+
assert cppcheckdata.match(find_token(match_cfg, '=').previous, '%var% !!|=')
724+
725+
def test_negation_literal_bitwise_or(self, match_cfg):
726+
bit_or = find_token(match_cfg, '|')
727+
assert not cppcheckdata.match(bit_or.previous, '%var% !!|')
728+
assert cppcheckdata.match(find_token(match_cfg, '||').previous, '%var% !!|')
729+
assert cppcheckdata.match(find_token(match_cfg, '|=').previous, '%var% !!|')
730+
731+
def test_negation_literal_logical_or(self, match_cfg):
732+
log_or = find_token(match_cfg, '||')
733+
assert not cppcheckdata.match(log_or.previous, '%var% !!||')
734+
assert cppcheckdata.match(find_token(match_cfg, '|').previous, '%var% !!||')
735+
assert cppcheckdata.match(find_token(match_cfg, '|=').previous, '%var% !!||')
736+
737+
def test_negation_alternatives(self, match_cfg):
738+
# as in the C++ Token::Match, the word after '!!' is not split into
739+
# alternatives: '!!a|b' is "not the token a|b"
740+
struct_tok = find_token(match_cfg, 'struct')
741+
assert cppcheckdata.match(struct_tok, 'struct !!Point|Foo')
742+
assert cppcheckdata.match(struct_tok, 'struct !!Foo|Point')
743+
assert cppcheckdata.match(struct_tok, 'struct !!Foo|Bar')
744+
assert cppcheckdata.match(struct_tok, 'struct !!%name%|;')
745+
746+
def test_find_forward_alternatives(self, match_cfg):
747+
# '**a|b' searches ahead for the first token that is a or b
748+
calc_def = find_token(match_cfg, 'calc')
749+
res = cppcheckdata.match(calc_def, 'calc **{|nosuchtoken')
750+
assert res
751+
assert res.end.str == '{'
752+
res = cppcheckdata.match(calc_def, 'calc **nosuchtoken|{')
753+
assert res
754+
assert res.end.str == '{'
755+
res = cppcheckdata.match(calc_def, 'calc **{|(')
756+
assert res
757+
assert res.end.str == '('
758+
res = cppcheckdata.match(calc_def, 'calc **%op%|{')
759+
assert res
760+
assert res.end.str == '{'
761+
assert not cppcheckdata.match(calc_def, 'calc **nosuchtoken|nosuchtoken2')
762+
763+
def test_find_forward_literal_or_operators(self, match_cfg):
764+
# '**|', '**||' and '**|=' search for the operator as a whole
765+
bit_or_decl = find_token(match_cfg, 'bit_or')
766+
for op in ('|', '||', '|='):
767+
res = cppcheckdata.match(bit_or_decl, 'bit_or **' + op)
768+
assert res
769+
assert res.end.str == op
770+
# past the last '|' and '||' only the '|=' is left to find
771+
arr_decl = find_token(match_cfg, 'arr')
772+
assert not cppcheckdata.match(arr_decl, 'arr **|')
773+
assert not cppcheckdata.match(arr_decl, 'arr **||')
774+
assert cppcheckdata.match(arr_decl, 'arr **|=')
775+
699776
@pytest.mark.xfail(strict=False,
700777
reason='in the C++ Token::Match a negation also matches when there is no token, '
701778
'in match() it does not')
@@ -761,6 +838,23 @@ def test_find_forward(self, match_cfg):
761838
assert res.end.str == '{'
762839
assert not cppcheckdata.match(calc_def, 'calc **nosuchtoken')
763840

841+
# ---- compiled pattern cache ----
842+
843+
def test_compile_pattern_reused(self):
844+
compiled = cppcheckdata.compile_pattern('calc ( %var%')
845+
assert compiled.pattern == 'calc ( %var%'
846+
assert cppcheckdata.compile_pattern('calc ( %var%') is compiled
847+
848+
def test_compiled_patterns_limited(self, match_cfg):
849+
calc_def = find_token(match_cfg, 'calc')
850+
maxsize = cppcheckdata.compile_pattern.cache_info().maxsize
851+
assert maxsize is not None
852+
for i in range(maxsize + 100):
853+
assert not cppcheckdata.match(calc_def, 'nosuchtoken{} ('.format(i))
854+
assert cppcheckdata.compile_pattern.cache_info().currsize == maxsize
855+
# a pattern that was dropped is compiled again and still matches
856+
assert cppcheckdata.match(calc_def, 'calc ( int')
857+
764858

765859
class TestSuppressions:
766860
def make_suppression(self, **kwargs):

0 commit comments

Comments
 (0)