-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathmain.py
More file actions
144 lines (115 loc) · 3.77 KB
/
Copy pathmain.py
File metadata and controls
144 lines (115 loc) · 3.77 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
from __future__ import annotations
import argparse
import importlib
import importlib.util
import inspect
import sys
from pathlib import Path
import exo
from contextlib import contextmanager
@contextmanager
def pythonpath(path: Path):
_sys_path = sys.path.copy()
try:
sys.path.insert(0, str(path.resolve(strict=True)))
yield
finally:
sys.path = _sys_path
def exocc(*args, name="exocc"):
sys.setrecursionlimit(10000)
parser = argparse.ArgumentParser(prog=name, description="Compile an Exo library.")
parser.add_argument(
"-o",
"--outdir",
metavar="OUTDIR",
help="output directory for build artifacts",
)
parser.add_argument(
"-p",
"--pythonpath",
metavar="PYTHONPATH",
help=(
"directory to add to PYTHONPATH. Defaults to parent of a single source "
"file or the current working directory for multiple source files."
),
type=Path,
)
parser.add_argument("-s", "--stem", help="base name for .c and .h files")
parser.add_argument(
"-v",
"--version",
action="version",
version=f"%(prog)s version {exo.__version__}",
help="print the version and exit",
)
parser.add_argument(
"source", type=Path, nargs="+", help="source file(s) to compile"
)
args = parser.parse_args(args)
srcname = args.source[0].stem
if not args.outdir:
if len(args.source) == 1:
outdir = Path(srcname)
else:
parser.error("Must provide -o when processing multiple source files.")
else:
outdir = Path(args.outdir)
outdir.mkdir(parents=True, exist_ok=True)
if not args.stem:
if len(args.source) == 1:
args.stem = srcname
else:
parser.error("Must provide --stem when processing multiple source files.")
if not args.pythonpath:
if len(args.source) == 1:
args.pythonpath = args.source[0].parent
else:
args.pythonpath = Path.cwd()
with pythonpath(args.pythonpath):
library = [
proc
for mod in args.source
for proc in get_procs_from_module(load_user_code(mod))
]
exo.compile_procs(library, outdir, f"{args.stem}.c", f"{args.stem}.h")
write_depfile(outdir, args.stem)
def write_depfile(outdir, stem):
modules = set()
for mod in sys.modules.values():
try:
modules.add(inspect.getfile(mod))
except TypeError:
pass # this is the case for built-in modules
c_file = outdir / f"{stem}.c"
h_file = outdir / f"{stem}.h"
depfile = outdir / f"{stem}.d"
sep = " \\\n "
deps = sep.join(sorted(modules))
contents = f"{c_file} {h_file} : {deps}"
depfile.write_text(contents)
def get_procs_from_module(user_module):
symbols = dir(user_module)
has_export_list = "__all__" in symbols
if has_export_list:
exported_symbols = user_module.__dict__["__all__"]
else:
exported_symbols = symbols
library = []
for sym in exported_symbols:
if not sym.startswith("_"):
fn = getattr(user_module, sym)
if isinstance(fn, exo.Procedure) and not fn.is_instr():
library.append(fn)
return library
def load_user_code(path: Path):
module_path = path.resolve(strict=True)
if not module_path.is_file():
raise ValueError(f"Expected path to a file, got: {module_path}")
spec = importlib.util.spec_from_file_location(module_path.stem, str(module_path))
user_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(user_module)
return user_module
def main():
exocc(*sys.argv[1:], name=Path(sys.argv[0]).name)
if __name__ == "__main__":
main()