1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5from __future__ import annotations
6
7from astroid import context, nodes
8from astroid.brain.helpers import register_module_extender
9from astroid.builder import _extract_single_node, parse
10from astroid.const import PY311_PLUS
11from astroid.inference_tip import inference_tip
12from astroid.manager import AstroidManager
13
14
15def _re_transform() -> nodes.Module:
16 # The RegexFlag enum exposes all its entries by updating globals()
17 # In 3.6-3.10 all flags come from sre_compile
18 # On 3.11+ all flags come from re._compiler
19 if PY311_PLUS:
20 import_compiler = "import re._compiler as _compiler"
21 else:
22 import_compiler = "import sre_compile as _compiler"
23 return parse(f"""
24 {import_compiler}
25 NOFLAG = 0
26 ASCII = _compiler.SRE_FLAG_ASCII
27 IGNORECASE = _compiler.SRE_FLAG_IGNORECASE
28 LOCALE = _compiler.SRE_FLAG_LOCALE
29 UNICODE = _compiler.SRE_FLAG_UNICODE
30 MULTILINE = _compiler.SRE_FLAG_MULTILINE
31 DOTALL = _compiler.SRE_FLAG_DOTALL
32 VERBOSE = _compiler.SRE_FLAG_VERBOSE
33 TEMPLATE = _compiler.SRE_FLAG_TEMPLATE
34 DEBUG = _compiler.SRE_FLAG_DEBUG
35 A = ASCII
36 I = IGNORECASE
37 L = LOCALE
38 U = UNICODE
39 M = MULTILINE
40 S = DOTALL
41 X = VERBOSE
42 T = TEMPLATE
43 """)
44
45
46CLASS_GETITEM_TEMPLATE = """
47@classmethod
48def __class_getitem__(cls, item):
49 return cls
50"""
51
52
53def _looks_like_pattern_or_match(node: nodes.Call) -> bool:
54 """Check for re.Pattern or re.Match call in stdlib.
55
56 Match these patterns from stdlib/re.py
57 ```py
58 Pattern = type(...)
59 Match = type(...)
60 ```
61 """
62 return (
63 node.root().name == "re"
64 and isinstance(node.func, nodes.Name)
65 and node.func.name == "type"
66 and isinstance(node.parent, nodes.Assign)
67 and len(node.parent.targets) == 1
68 and isinstance(node.parent.targets[0], nodes.AssignName)
69 and node.parent.targets[0].name in {"Pattern", "Match"}
70 )
71
72
73def infer_pattern_match(node: nodes.Call, ctx: context.InferenceContext | None = None):
74 """Infer re.Pattern and re.Match as classes.
75
76 For PY39+ add `__class_getitem__`.
77 """
78 class_def = nodes.ClassDef(
79 name=node.parent.targets[0].name,
80 lineno=node.lineno,
81 col_offset=node.col_offset,
82 parent=node.parent,
83 end_lineno=node.end_lineno,
84 end_col_offset=node.end_col_offset,
85 )
86 func_to_add = _extract_single_node(CLASS_GETITEM_TEMPLATE)
87 class_def.locals["__class_getitem__"] = [func_to_add]
88 return iter([class_def])
89
90
91def register(manager: AstroidManager) -> None:
92 register_module_extender(manager, "re", _re_transform)
93 manager.register_transform(
94 nodes.Call, inference_tip(infer_pattern_match), _looks_like_pattern_or_match
95 )