forked from RustPython/RustPython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
96 lines (72 loc) · 2.23 KB
/
utils.py
File metadata and controls
96 lines (72 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import dataclasses
import pathlib
import re
import sys
import tomllib
ROOT = pathlib.Path(__file__).parents[2].resolve()
DEFAULT_INPUT = ROOT / "crates/compiler-core/src/bytecode/instruction.rs"
DEFAULT_CONF = pathlib.Path(__file__).parent / "conf.toml"
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
class StackEffect:
pushed: str | None = None
popped: str | None = None
@dataclasses.dataclass(frozen=True, kw_only=True, slots=True)
class Override:
is_instrumented: bool | None = None
stack_effect: StackEffect = dataclasses.field(default_factory=StackEffect)
type OverrideConfs = dict[str, Override]
SKIP_STACK_EFFECT = StackEffect()
SKIP_OVERRIDE = Override()
def get_conf(path: pathlib.Path = DEFAULT_CONF) -> OverrideConfs:
data = path.read_text(encoding="utf-8")
conf = tomllib.loads(data)
for k, v in conf.items():
v["stack_effect"] = StackEffect(**v.get("stack_effect", {}))
conf[k] = Override(**v)
return conf
def to_pascal_case(s: str) -> str:
return s.title().replace("_", "")
def to_upper_snake_case(s: str) -> str:
"""
Converts a PascalCaseString to be SNAKE_CASE
Parameters
----------
s : str
Pascal cased string to convert.
Returns
-------
str
Uppercased snake case string.
Examples
--------
>>> to_upper_snake_case("LoadAttr")
LOAD_ATTR
>>> to_upper_snake_case("CallIntrinsic1")
CALL_INTRINSIC_1
"""
res = re.sub(r"(?<=[a-z0-9])([A-Z])", r"_\1", s)
return re.sub(r"(\D)(\d+)$", r"\1_\2", res).upper()
def extract_enum_body(text: str, start: int) -> str:
"""
Extract the rust enum body from a raw rust source code.
Parameters
----------
text : str
Rust source code containing the enum body.
start : int
Offset to start searching from.
Returns
-------
str
Extracted enum body.
"""
assert text[start] == "{"
depth = 0
for i, ch in enumerate(text[start:], start):
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if depth == 0:
return text[start + 1 : i].strip() # exclude the outer braces
raise ValueError("Could not find end to enum body")