-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathviper.py
More file actions
72 lines (63 loc) · 2.07 KB
/
Copy pathviper.py
File metadata and controls
72 lines (63 loc) · 2.07 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
#!/usr/bin/env python3
"""
viper — Python-to-C++ transpiler CLI
Usage: python viper.py <file1.py> [file2.py ...] [-o output.cpp]
"""
import ast
import argparse
import os
import sys
from core import Transpiler, TranspileError
from resolver import ImportResolver
def main():
parser = argparse.ArgumentParser(
prog="viper",
description="Viper: transpile typed Python to C++17",
)
parser.add_argument("files", nargs="+", help="Python source files")
parser.add_argument("-o", "--output", help="Output file (default: stdout)")
args = parser.parse_args()
modules: list = []
module_names: list = []
for path in args.files:
try:
with open(path, encoding="utf-8") as f:
src = f.read()
except OSError as e:
print(f"viper: cannot open '{path}': {e}", file=sys.stderr)
sys.exit(1)
try:
tree = ast.parse(src, filename=path)
except SyntaxError as e:
print(f"viper: syntax error in '{path}': {e}", file=sys.stderr)
sys.exit(1)
modules.append(tree)
module_names.append(os.path.splitext(os.path.basename(path))[0])
# Recursively resolve all imports (stubs or Python source)
resolver = ImportResolver(set(module_names))
try:
extra = resolver.collect(modules)
except TranspileError as e:
print(f"viper: {e}", file=sys.stderr)
sys.exit(1)
for tree, name in extra:
modules.append(tree)
module_names.append(name)
transpiler = Transpiler(modules, module_names)
try:
result = transpiler.transpile()
except TranspileError as e:
print(f"viper: {e}", file=sys.stderr)
sys.exit(1)
if args.output:
try:
with open(args.output, "w", encoding="utf-8") as f:
f.write(result)
except OSError as e:
print(f"viper: cannot write '{args.output}': {e}", file=sys.stderr)
sys.exit(1)
print(f"Written to {args.output}")
else:
print(result)
if __name__ == "__main__":
main()