-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__init__.py
More file actions
70 lines (52 loc) · 1.48 KB
/
__init__.py
File metadata and controls
70 lines (52 loc) · 1.48 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
import inspect
import types
from typing import Optional, TypeVar
def caller_module():
frame = inspect.stack()[2]
module = inspect.getmodule(frame[0])
for frame in inspect.stack():
print(frame)
return module
def imports():
mod = caller_module()
return {
val.__name__
for val in mod.__dict__.values()
if isinstance(val, types.ModuleType)
}
def try_else(job, onSucceed, onFail):
try:
ret = job()
except BaseException as e:
return onFail(e)
else:
return onSucceed(ret)
def find_column(_input: str, lexpos: int):
line_start = _input.rfind("\n", 0, lexpos)
return lexpos - line_start
def get_line(_input: str, lineno: int):
lines = get_line.__dict__.setdefault(_input, _input.splitlines())
return lines[lineno - 1]
def get_grammar(path: Optional[str] = None):
import re
from frontend.lexer import lex
lexes = tuple(
(val, name.removeprefix("t_"))
for name, val in lex.__dict__.items()
if (
isinstance(val, str)
and not name.startswith("_")
and not name.startswith("t_ignore_")
)
) + tuple(lex.reserved.items())
lexes = map(
lambda t: (re.compile(f"'{t[0]}'"), t[1]),
lexes,
)
with open(path if path else "grammar", "r") as f:
grammar = f.read()
for reg, tokname in lexes:
grammar = reg.sub(tokname, grammar)
return grammar
T = TypeVar("T")
U = TypeVar("U")