Debian Codegraph @

hypothesis-python/src/hypothesis/strategies/_internal/regex.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 import operator
12 import re
13
14 from hypothesis.errors import InvalidArgument
15 from hypothesis.internal import charmap
16 from hypothesis.strategies._internal.lazy import unwrap_strategies
17 from hypothesis.strategies._internal.strings import OneCharStringStrategy
18
19 try: # pragma: no cover
20 import re._constants as sre
21 import re._parser as sre_parse
22
23 ATOMIC_GROUP = sre.ATOMIC_GROUP
24 POSSESSIVE_REPEAT = sre.POSSESSIVE_REPEAT
25 except ImportError: # Python < 3.11
26 import sre_constants as sre
27 import sre_parse
28
29 ATOMIC_GROUP = object()
30 POSSESSIVE_REPEAT = object()
31
32 from hypothesis import reject, strategies as st
33 from hypothesis.internal.charmap import as_general_categories, categories
34 from hypothesis.internal.compat import add_note, int_to_byte
35
36 UNICODE_CATEGORIES = set(categories())
37
38
39 SPACE_CHARS = set(" \t\n\r\f\v")
40 UNICODE_SPACE_CHARS = SPACE_CHARS | set("\x1c\x1d\x1e\x1f\x85")
41 UNICODE_DIGIT_CATEGORIES = {"Nd"}
42 UNICODE_SPACE_CATEGORIES = set(as_general_categories(["Z"]))
43 UNICODE_LETTER_CATEGORIES = set(as_general_categories(["L"]))
44 UNICODE_WORD_CATEGORIES = set(as_general_categories(["L", "N"]))
45
46 # This is verbose, but correct on all versions of Python
47 BYTES_ALL = {int_to_byte(i) for i in range(256)}
48 BYTES_DIGIT = {b for b in BYTES_ALL if re.match(b"\\d", b)}
49 BYTES_SPACE = {b for b in BYTES_ALL if re.match(b"\\s", b)}
50 BYTES_WORD = {b for b in BYTES_ALL if re.match(b"\\w", b)}
51 BYTES_LOOKUP = {
52 sre.CATEGORY_DIGIT: BYTES_DIGIT,
53 sre.CATEGORY_SPACE: BYTES_SPACE,
54 sre.CATEGORY_WORD: BYTES_WORD,
55 sre.CATEGORY_NOT_DIGIT: BYTES_ALL - BYTES_DIGIT,
56 sre.CATEGORY_NOT_SPACE: BYTES_ALL - BYTES_SPACE,
57 sre.CATEGORY_NOT_WORD: BYTES_ALL - BYTES_WORD,
58 }
59
60
61 GROUP_CACHE_STRATEGY: st.SearchStrategy[dict] = st.shared(
62 st.builds(dict), key="hypothesis.regex.group_cache"
63 )
64
65
66 class IncompatibleWithAlphabet(InvalidArgument):
67 pass
68
69
70 @st.composite
71 def update_group(draw, group_name, strategy):
72 cache = draw(GROUP_CACHE_STRATEGY)
73 result = draw(strategy)
74 cache[group_name] = result
75 return result
76
77
78 @st.composite
79 def reuse_group(draw, group_name):
80 cache = draw(GROUP_CACHE_STRATEGY)
81 try:
82 return cache[group_name]
83 except KeyError:
84 reject()
85
86
87 @st.composite
88 def group_conditional(draw, group_name, if_yes, if_no):
89 cache = draw(GROUP_CACHE_STRATEGY)
90 if group_name in cache:
91 return draw(if_yes)
92 else:
93 return draw(if_no)
94
95
96 @st.composite
97 def clear_cache_after_draw(draw, base_strategy):
98 cache = draw(GROUP_CACHE_STRATEGY)
99 result = draw(base_strategy)
100 cache.clear()
101 return result
102
103
104 def chars_not_in_alphabet(alphabet, string):
105 # Given a string, return a tuple of the characters which are not in alphabet
106 if alphabet is None:
107 return ()
108 intset = unwrap_strategies(alphabet).intervals
109 return tuple(c for c in string if c not in intset)
110
111
112 class Context:
113 __slots__ = ["flags"]
114
115 def __init__(self, flags):
116 self.flags = flags
117
118
119 class CharactersBuilder:
120 """Helper object that allows to configure `characters` strategy with
121 various unicode categories and characters. Also allows negation of
122 configured set.
123
124 :param negate: If True, configure :func:`hypothesis.strategies.characters`
125 to match anything other than configured character set
126 :param flags: Regex flags. They affect how and which characters are matched
127 """
128
129 def __init__(self, *, negate=False, flags=0, alphabet):
130 self._categories = set()
131 self._whitelist_chars = set()
132 self._blacklist_chars = set()
133 self._negate = negate
134 self._ignorecase = flags & re.IGNORECASE
135 self.code_to_char = chr
136 self._alphabet = unwrap_strategies(alphabet)
137 if flags & re.ASCII:
138 self._alphabet = OneCharStringStrategy(
139 self._alphabet.intervals & charmap.query(max_codepoint=127)
140 )
141
142 @property
143 def strategy(self):
144 """Returns resulting strategy that generates configured char set."""
145 # Start by getting the set of all characters allowed by the pattern
146 white_chars = self._whitelist_chars - self._blacklist_chars
147 multi_chars = {c for c in white_chars if len(c) > 1}
148 intervals = charmap.query(
149 categories=self._categories,
150 exclude_characters=self._blacklist_chars,
151 include_characters=white_chars - multi_chars,
152 )
153 # Then take the complement if this is from a negated character class
154 if self._negate:
155 intervals = charmap.query() - intervals
156 multi_chars.clear()
157 # and finally return the intersection with our alphabet
158 return OneCharStringStrategy(intervals & self._alphabet.intervals) | (
159 st.sampled_from(sorted(multi_chars)) if multi_chars else st.nothing()
160 )
161
162 def add_category(self, category):
163 """Update unicode state to match sre_parse object ``category``."""
164 if category == sre.CATEGORY_DIGIT:
165 self._categories |= UNICODE_DIGIT_CATEGORIES
166 elif category == sre.CATEGORY_NOT_DIGIT:
167 self._categories |= UNICODE_CATEGORIES - UNICODE_DIGIT_CATEGORIES
168 elif category == sre.CATEGORY_SPACE:
169 self._categories |= UNICODE_SPACE_CATEGORIES
170 self._whitelist_chars |= UNICODE_SPACE_CHARS
171 elif category == sre.CATEGORY_NOT_SPACE:
172 self._categories |= UNICODE_CATEGORIES - UNICODE_SPACE_CATEGORIES
173 self._blacklist_chars |= UNICODE_SPACE_CHARS
174 elif category == sre.CATEGORY_WORD:
175 self._categories |= UNICODE_WORD_CATEGORIES
176 self._whitelist_chars.add("_")
177 elif category == sre.CATEGORY_NOT_WORD:
178 self._categories |= UNICODE_CATEGORIES - UNICODE_WORD_CATEGORIES
179 self._blacklist_chars.add("_")
180 else:
181 raise NotImplementedError(f"Unknown character category: {category}")
182
183 def add_char(self, c):
184 """Add given char to the whitelist."""
185 self._whitelist_chars.add(c)
186 if (
187 self._ignorecase
188 and re.match(re.escape(c), c.swapcase(), flags=re.IGNORECASE) is not None
189 ):
190 # Note that it is possible that `len(c.swapcase()) > 1`
191 self._whitelist_chars.add(c.swapcase())
192
193
194 class BytesBuilder(CharactersBuilder):
195 def __init__(self, *, negate=False, flags=0):
196 self._whitelist_chars = set()
197 self._blacklist_chars = set()
198 self._negate = negate
199 self._alphabet = None
200 self._ignorecase = flags & re.IGNORECASE
201 self.code_to_char = int_to_byte
202
203 @property
204 def strategy(self):
205 """Returns resulting strategy that generates configured char set."""
206 allowed = self._whitelist_chars
207 if self._negate:
208 allowed = BYTES_ALL - allowed
209 return st.sampled_from(sorted(allowed))
210
211 def add_category(self, category):
212 """Update characters state to match sre_parse object ``category``."""
213 self._whitelist_chars |= BYTES_LOOKUP[category]
214
215
216 @st.composite
217 def maybe_pad(draw, regex, strategy, left_pad_strategy, right_pad_strategy):
218 """Attempt to insert padding around the result of a regex draw while
219 preserving the match."""
220 result = draw(strategy)
221 left_pad = draw(left_pad_strategy)
222 if left_pad and regex.search(left_pad + result):
223 result = left_pad + result
224 right_pad = draw(right_pad_strategy)
225 if right_pad and regex.search(result + right_pad):
226 result += right_pad
227 return result
228
229
230 def base_regex_strategy(regex, parsed=None, alphabet=None):
231 if parsed is None:
232 parsed = sre_parse.parse(regex.pattern, flags=regex.flags)
233 try:
234 s = _strategy(
235 parsed,
236 context=Context(flags=regex.flags),
237 is_unicode=isinstance(regex.pattern, str),
238 alphabet=alphabet,
239 )
240 except Exception as err:
241 add_note(err, f"{alphabet=} {regex=}")
242 raise
243 return clear_cache_after_draw(s)
244
245
246 def regex_strategy(
247 regex, fullmatch, *, alphabet, _temp_jsonschema_hack_no_end_newline=False
248 ):
249 if not hasattr(regex, "pattern"):
250 regex = re.compile(regex)
251
252 is_unicode = isinstance(regex.pattern, str)
253
254 parsed = sre_parse.parse(regex.pattern, flags=regex.flags)
255
256 if fullmatch:
257 if not parsed:
258 return st.just("" if is_unicode else b"")
259 return base_regex_strategy(regex, parsed, alphabet).filter(regex.fullmatch)
260
261 if not parsed:
262 if is_unicode:
263 return st.text(alphabet=alphabet)
264 else:
265 return st.binary()
266
267 if is_unicode:
268 base_padding_strategy = st.text(alphabet=alphabet)
269 empty = st.just("")
270 newline = st.just("\n")
271 else:
272 base_padding_strategy = st.binary()
273 empty = st.just(b"")
274 newline = st.just(b"\n")
275
276 right_pad = base_padding_strategy
277 left_pad = base_padding_strategy
278
279 if parsed[-1][0] == sre.AT:
280 if parsed[-1][1] == sre.AT_END_STRING:
281 right_pad = empty
282 elif parsed[-1][1] == sre.AT_END:
283 if regex.flags & re.MULTILINE:
284 right_pad = st.one_of(
285 empty, st.builds(operator.add, newline, right_pad)
286 )
287 else:
288 right_pad = st.one_of(empty, newline)
289
290 # This will be removed when a regex-syntax-translation library exists.
291 # It's a pretty nasty hack, but means that we can match the semantics
292 # of JSONschema's compatible subset of ECMA regex, which is important
293 # for hypothesis-jsonschema and Schemathesis. See e.g.
294 # https://github.com/schemathesis/schemathesis/issues/1241
295 if _temp_jsonschema_hack_no_end_newline:
296 right_pad = empty
297
298 if parsed[0][0] == sre.AT:
299 if parsed[0][1] == sre.AT_BEGINNING_STRING:
300 left_pad = empty
301 elif parsed[0][1] == sre.AT_BEGINNING:
302 if regex.flags & re.MULTILINE:
303 left_pad = st.one_of(empty, st.builds(operator.add, left_pad, newline))
304 else:
305 left_pad = empty
306
307 base = base_regex_strategy(regex, parsed, alphabet).filter(regex.search)
308
309 return maybe_pad(regex, base, left_pad, right_pad)
310
311
312 def _strategy(codes, context, is_unicode, *, alphabet):
313 """Convert SRE regex parse tree to strategy that generates strings matching
314 that regex represented by that parse tree.
315
316 `codes` is either a list of SRE regex elements representations or a
317 particular element representation. Each element is a tuple of element code
318 (as string) and parameters. E.g. regex 'ab[0-9]+' compiles to following
319 elements:
320
321 [
322 (LITERAL, 97),
323 (LITERAL, 98),
324 (MAX_REPEAT, (1, 4294967295, [
325 (IN, [
326 (RANGE, (48, 57))
327 ])
328 ]))
329 ]
330
331 The function recursively traverses regex element tree and converts each
332 element to strategy that generates strings that match that element.
333
334 Context stores
335 1. List of groups (for backreferences)
336 2. Active regex flags (e.g. IGNORECASE, DOTALL, UNICODE, they affect
337 behavior of various inner strategies)
338 """
339
340 def recurse(codes):
341 return _strategy(codes, context, is_unicode, alphabet=alphabet)
342
343 if is_unicode:
344 empty = ""
345 to_char = chr
346 else:
347 empty = b""
348 to_char = int_to_byte
349 binary_char = st.binary(min_size=1, max_size=1)
350
351 if not isinstance(codes, tuple):
352 # List of codes
353 strategies = []
354
355 i = 0
356 while i < len(codes):
357 if codes[i][0] == sre.LITERAL and not context.flags & re.IGNORECASE:
358 # Merge subsequent "literals" into one `just()` strategy
359 # that generates corresponding text if no IGNORECASE
360 j = i + 1
361 while j < len(codes) and codes[j][0] == sre.LITERAL:
362 j += 1
363
364 if i + 1 < j:
365 chars = empty.join(to_char(charcode) for _, charcode in codes[i:j])
366 if invalid := chars_not_in_alphabet(alphabet, chars):
367 raise IncompatibleWithAlphabet(
368 f"Literal {chars!r} contains characters {invalid!r} "
369 f"which are not in the specified alphabet"
370 )
371 strategies.append(st.just(chars))
372 i = j
373 continue
374
375 strategies.append(recurse(codes[i]))
376 i += 1
377
378 # We handle this separately at the top level, but some regex can
379 # contain empty lists internally, so we need to handle this here too.
380 if not strategies:
381 return st.just(empty)
382
383 if len(strategies) == 1:
384 return strategies[0]
385 return st.tuples(*strategies).map(empty.join)
386 else:
387 # Single code
388 code, value = codes
389 if code == sre.LITERAL:
390 # Regex 'a' (single char)
391 c = to_char(value)
392 if chars_not_in_alphabet(alphabet, c):
393 raise IncompatibleWithAlphabet(
394 f"Literal {c!r} is not in the specified alphabet"
395 )
396 if (
397 context.flags & re.IGNORECASE
398 and c != c.swapcase()
399 and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None
400 and not chars_not_in_alphabet(alphabet, c.swapcase())
401 ):
402 # We do the explicit check for swapped-case matching because
403 # eg 'ß'.upper() == 'SS' and ignorecase doesn't match it.
404 return st.sampled_from([c, c.swapcase()])
405 return st.just(c)
406
407 elif code == sre.NOT_LITERAL:
408 # Regex '[^a]' (negation of a single char)
409 c = to_char(value)
410 blacklist = {c}
411 if (
412 context.flags & re.IGNORECASE
413 and re.match(re.escape(c), c.swapcase(), re.IGNORECASE) is not None
414 ):
415 # There are a few cases where .swapcase() returns two characters,
416 # but is still a case-insensitive match. In such cases we add *both*
417 # characters to our blacklist, to avoid doing the wrong thing for
418 # patterns such as r"[^\u0130]+" where "i\u0307" matches.
419 #
420 # (that's respectively 'Latin letter capital I with dot above' and
421 # 'latin latter i' + 'combining dot above'; see issue #2657)
422 #
423 # As a final additional wrinkle, "latin letter capital I" *also*
424 # case-insensitive-matches, with or without combining dot character.
425 # We therefore have to chain .swapcase() calls until a fixpoint.
426 stack = [c.swapcase()]
427 while stack:
428 for char in stack.pop():
429 blacklist.add(char)
430 stack.extend(set(char.swapcase()) - blacklist)
431
432 if is_unicode:
433 return OneCharStringStrategy(
434 unwrap_strategies(alphabet).intervals
435 & charmap.query(exclude_characters=blacklist)
436 )
437 else:
438 return binary_char.filter(lambda c: c not in blacklist)
439
440 elif code == sre.IN:
441 # Regex '[abc0-9]' (set of characters)
442 negate = value[0][0] == sre.NEGATE
443 if is_unicode:
444 builder = CharactersBuilder(
445 flags=context.flags, negate=negate, alphabet=alphabet
446 )
447 else:
448 builder = BytesBuilder(flags=context.flags, negate=negate)
449
450 for charset_code, charset_value in value:
451 if charset_code == sre.NEGATE:
452 # Regex '[^...]' (negation)
453 # handled by builder = CharactersBuilder(...) above
454 pass
455 elif charset_code == sre.LITERAL:
456 # Regex '[a]' (single char)
457 c = builder.code_to_char(charset_value)
458 if chars_not_in_alphabet(builder._alphabet, c):
459 raise IncompatibleWithAlphabet(
460 f"Literal {c!r} is not in the specified alphabet"
461 )
462 builder.add_char(c)
463 elif charset_code == sre.RANGE:
464 # Regex '[a-z]' (char range)
465 low, high = charset_value
466 chars = empty.join(map(builder.code_to_char, range(low, high + 1)))
467 if len(chars) == len(
468 invalid := set(chars_not_in_alphabet(alphabet, chars))
469 ):
470 raise IncompatibleWithAlphabet(
471 f"Charset '[{chr(low)}-{chr(high)}]' contains characters {invalid!r} "
472 f"which are not in the specified alphabet"
473 )
474 for c in chars:
475 if isinstance(c, int):
476 c = int_to_byte(c)
477 if c not in invalid:
478 builder.add_char(c)
479 elif charset_code == sre.CATEGORY:
480 # Regex '[\w]' (char category)
481 builder.add_category(charset_value)
482 else:
483 # Currently there are no known code points other than
484 # handled here. This code is just future proofing
485 raise NotImplementedError(f"Unknown charset code: {charset_code}")
486 return builder.strategy
487
488 elif code == sre.ANY:
489 # Regex '.' (any char)
490 if is_unicode:
491 assert alphabet is not None
492 if context.flags & re.DOTALL:
493 return alphabet
494 return OneCharStringStrategy(
495 unwrap_strategies(alphabet).intervals
496 & charmap.query(exclude_characters="\n")
497 )
498 else:
499 if context.flags & re.DOTALL:
500 return binary_char
501 return binary_char.filter(lambda c: c != b"\n")
502
503 elif code == sre.AT:
504 # Regexes like '^...', '...$', '\bfoo', '\Bfoo'
505 # An empty string (or newline) will match the token itself, but
506 # we don't and can't check the position (eg '%' at the end)
507 return st.just(empty)
508
509 elif code == sre.SUBPATTERN:
510 # Various groups: '(...)', '(:...)' or '(?P<name>...)'
511 old_flags = context.flags
512 context.flags = (context.flags | value[1]) & ~value[2]
513
514 strat = _strategy(value[-1], context, is_unicode, alphabet=alphabet)
515
516 context.flags = old_flags
517
518 if value[0]:
519 strat = update_group(value[0], strat)
520
521 return strat
522
523 elif code == sre.GROUPREF:
524 # Regex '\\1' or '(?P=name)' (group reference)
525 return reuse_group(value)
526
527 elif code == sre.ASSERT:
528 # Regex '(?=...)' or '(?<=...)' (positive lookahead/lookbehind)
529 return recurse(value[1])
530
531 elif code == sre.ASSERT_NOT:
532 # Regex '(?!...)' or '(?<!...)' (negative lookahead/lookbehind)
533 return st.just(empty)
534
535 elif code == sre.BRANCH:
536 # Regex 'a|b|c' (branch)
537 branches = []
538 errors = []
539 for branch in value[1]:
540 try:
541 branches.append(recurse(branch))
542 except IncompatibleWithAlphabet as e:
543 errors.append(str(e))
544 if errors and not branches:
545 raise IncompatibleWithAlphabet("\n".join(errors))
546 return st.one_of(branches)
547
548 elif code in [sre.MIN_REPEAT, sre.MAX_REPEAT, POSSESSIVE_REPEAT]:
549 # Regexes 'a?', 'a*', 'a+' and their non-greedy variants
550 # (repeaters)
551 at_least, at_most, subregex = value
552 if at_most == sre.MAXREPEAT:
553 at_most = None
554 if at_least == 0 and at_most == 1:
555 return st.just(empty) | recurse(subregex)
556 return st.lists(recurse(subregex), min_size=at_least, max_size=at_most).map(
557 empty.join
558 )
559
560 elif code == sre.GROUPREF_EXISTS:
561 # Regex '(?(id/name)yes-pattern|no-pattern)'
562 # (if group exists choice)
563 return group_conditional(
564 value[0],
565 recurse(value[1]),
566 recurse(value[2]) if value[2] else st.just(empty),
567 )
568 elif code == ATOMIC_GROUP: # pragma: no cover # new in Python 3.11
569 return _strategy(value, context, is_unicode, alphabet=alphabet)
570
571 else:
572 # Currently there are no known code points other than handled here.
573 # This code is just future proofing
574 raise NotImplementedError(
575 f"Unknown code point: {code!r}. Please open an issue."
576 )