Debian Codegraph @

hypothesis-python/src/hypothesis/extra/lark.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 """
12 This extra can be used to generate strings matching any context-free grammar,
13 using the `Lark parser library <https://github.com/lark-parser/lark>`_.
14
15 It currently only supports Lark's native EBNF syntax, but we plan to extend
16 this to support other common syntaxes such as ANTLR and :rfc:`5234` ABNF.
17 Lark already `supports loading grammars
18 <https://lark-parser.readthedocs.io/en/stable/tools.html#importing-grammars-from-nearley-js>`_
19 from `nearley.js <https://nearley.js.org/>`_, so you may not have to write
20 your own at all.
21 """
22
23 from inspect import signature
24
25 import lark
26 from lark.grammar import NonTerminal, Rule, Symbol, Terminal
27 from lark.lark import Lark
28 from lark.lexer import TerminalDef
29
30 from hypothesis import strategies as st
31 from hypothesis.errors import InvalidArgument
32 from hypothesis.internal.conjecture.data import ConjectureData
33 from hypothesis.internal.conjecture.utils import calc_label_from_name
34 from hypothesis.internal.validation import check_type
35 from hypothesis.strategies._internal.regex import IncompatibleWithAlphabet
36 from hypothesis.strategies._internal.utils import cacheable, defines_strategy
37
38 __all__ = ["from_lark"]
39
40
41 def get_terminal_names(
42 terminals: list[TerminalDef], rules: list[Rule], ignore_names: list[str]
43 ) -> set[str]:
44 """Get names of all terminals in the grammar.
45
46 The arguments are the results of calling ``Lark.grammar.compile()``,
47 so you would think that the ``terminals`` and ``ignore_names`` would
48 have it all... but they omit terminals created with ``@declare``,
49 which appear only in the expansion(s) of nonterminals.
50 """
51 names = {t.name for t in terminals} | set(ignore_names)
52 for rule in rules:
53 names |= {t.name for t in rule.expansion if isinstance(t, Terminal)}
54 return names
55
56
57 class LarkStrategy(st.SearchStrategy):
58 """Low-level strategy implementation wrapping a Lark grammar.
59
60 See ``from_lark`` for details.
61 """
62
63 def __init__(
64 self,
65 grammar: Lark,
66 start: str | None,
67 explicit: dict[str, st.SearchStrategy[str]],
68 alphabet: st.SearchStrategy[str],
69 ) -> None:
70 super().__init__()
71 assert isinstance(grammar, lark.lark.Lark)
72 start: list[str] = grammar.options.start if start is None else [start]
73
74 # This is a total hack, but working around the changes is a nicer user
75 # experience than breaking for anyone who doesn't instantly update their
76 # installation of Lark alongside Hypothesis.
77 compile_args = signature(grammar.grammar.compile).parameters
78 if "terminals_to_keep" in compile_args:
79 terminals, rules, ignore_names = grammar.grammar.compile(start, ())
80 elif "start" in compile_args: # pragma: no cover
81 # Support lark <= 0.10.0, without the terminals_to_keep argument.
82 terminals, rules, ignore_names = grammar.grammar.compile(start) # type: ignore
83 else: # pragma: no cover
84 # This branch is to support lark <= 0.7.1, without the start argument.
85 terminals, rules, ignore_names = grammar.grammar.compile() # type: ignore
86
87 self.names_to_symbols: dict[str, Symbol] = {}
88
89 for r in rules:
90 self.names_to_symbols[r.origin.name] = r.origin
91
92 disallowed = set()
93 self.terminal_strategies: dict[str, st.SearchStrategy[str]] = {}
94 for t in terminals:
95 self.names_to_symbols[t.name] = Terminal(t.name)
96 s = st.from_regex(t.pattern.to_regexp(), fullmatch=True, alphabet=alphabet)
97 try:
98 s.validate()
99 except IncompatibleWithAlphabet:
100 disallowed.add(t.name)
101 else:
102 self.terminal_strategies[t.name] = s
103
104 self.ignored_symbols = tuple(self.names_to_symbols[n] for n in ignore_names)
105
106 all_terminals = get_terminal_names(terminals, rules, ignore_names)
107 if unknown_explicit := sorted(set(explicit) - all_terminals):
108 raise InvalidArgument(
109 "The following arguments were passed as explicit_strategies, but "
110 f"there is no {unknown_explicit} terminal production in this grammar."
111 )
112 if missing_declared := sorted(
113 all_terminals - {t.name for t in terminals} - set(explicit)
114 ):
115 raise InvalidArgument(
116 f"Undefined terminal{'s' * (len(missing_declared) > 1)} "
117 f"{sorted(missing_declared)!r}. Generation does not currently "
118 "support use of %declare unless you pass `explicit`, a dict of "
119 f"names-to-strategies, such as `{{{missing_declared[0]!r}: "
120 'st.just("")}}`'
121 )
122 self.terminal_strategies.update(explicit)
123
124 # can in fact contain any symbol, despite its name.
125 nonterminals: dict[str, list[tuple[Symbol, ...]]] = {}
126
127 for rule in rules:
128 if disallowed.isdisjoint(r.name for r in rule.expansion):
129 nonterminals.setdefault(rule.origin.name, []).append(
130 tuple(rule.expansion)
131 )
132
133 allowed_rules = {*self.terminal_strategies, *nonterminals}
134 while dict(nonterminals) != (
135 nonterminals := {
136 k: clean
137 for k, v in nonterminals.items()
138 if (clean := [x for x in v if all(r.name in allowed_rules for r in x)])
139 }
140 ):
141 allowed_rules = {*self.terminal_strategies, *nonterminals}
142
143 if set(start).isdisjoint(allowed_rules):
144 raise InvalidArgument(
145 f"No start rule {tuple(start)} is allowed by {alphabet=}"
146 )
147 self.start = st.sampled_from(
148 [self.names_to_symbols[s] for s in start if s in allowed_rules]
149 )
150
151 self.nonterminal_strategies = {
152 k: st.sampled_from(sorted(v, key=len)) for k, v in nonterminals.items()
153 }
154
155 self.__rule_labels: dict[str, int] = {}
156
157 def do_draw(self, data: ConjectureData) -> str:
158 state: list[str] = []
159 start = data.draw(self.start)
160 self.draw_symbol(data, start, state)
161 return "".join(state)
162
163 def rule_label(self, name: str) -> int:
164 try:
165 return self.__rule_labels[name]
166 except KeyError:
167 return self.__rule_labels.setdefault(
168 name, calc_label_from_name(f"LARK:{name}")
169 )
170
171 def draw_symbol(
172 self,
173 data: ConjectureData,
174 symbol: Symbol,
175 draw_state: list[str],
176 ) -> None:
177 if isinstance(symbol, Terminal):
178 strategy = self.terminal_strategies[symbol.name]
179 draw_state.append(data.draw(strategy))
180 else:
181 assert isinstance(symbol, NonTerminal)
182 data.start_span(self.rule_label(symbol.name))
183 expansion = data.draw(self.nonterminal_strategies[symbol.name])
184 for e in expansion:
185 self.draw_symbol(data, e, draw_state)
186 self.gen_ignore(data, draw_state)
187 data.stop_span()
188
189 def gen_ignore(self, data: ConjectureData, draw_state: list[str]) -> None:
190 if self.ignored_symbols and data.draw_boolean(1 / 4):
191 emit = data.draw(st.sampled_from(self.ignored_symbols))
192 self.draw_symbol(data, emit, draw_state)
193
194 def calc_has_reusable_values(self, recur):
195 return True
196
197
198 def check_explicit(name):
199 def inner(value):
200 check_type(str, value, "value drawn from " + name)
201 return value
202
203 return inner
204
205
206 @cacheable
207 @defines_strategy(force_reusable_values=True)
208 def from_lark(
209 grammar: lark.lark.Lark,
210 *,
211 start: str | None = None,
212 explicit: dict[str, st.SearchStrategy[str]] | None = None,
213 alphabet: st.SearchStrategy[str] = st.characters(codec="utf-8"),
214 ) -> st.SearchStrategy[str]:
215 """A strategy for strings accepted by the given context-free grammar.
216
217 ``grammar`` must be a ``Lark`` object, which wraps an EBNF specification.
218 The Lark EBNF grammar reference can be found
219 `here <https://lark-parser.readthedocs.io/en/latest/grammar.html>`_.
220
221 ``from_lark`` will automatically generate strings matching the
222 nonterminal ``start`` symbol in the grammar, which was supplied as an
223 argument to the Lark class. To generate strings matching a different
224 symbol, including terminals, you can override this by passing the
225 ``start`` argument to ``from_lark``. Note that Lark may remove unreachable
226 productions when the grammar is compiled, so you should probably pass the
227 same value for ``start`` to both.
228
229 Currently ``from_lark`` does not support grammars that need custom lexing.
230 Any lexers will be ignored, and any undefined terminals from the use of
231 ``%declare`` will result in generation errors. To define strategies for
232 such terminals, pass a dictionary mapping their name to a corresponding
233 strategy as the ``explicit`` argument.
234
235 The :pypi:`hypothesmith` project includes a strategy for Python source,
236 based on a grammar and careful post-processing.
237 """
238 check_type(lark.lark.Lark, grammar, "grammar")
239 if explicit is None:
240 explicit = {}
241 else:
242 check_type(dict, explicit, "explicit")
243 explicit = {
244 k: v.map(check_explicit(f"explicit[{k!r}]={v!r}"))
245 for k, v in explicit.items()
246 }
247 return LarkStrategy(grammar, start, explicit, alphabet)