This repository was archived by the owner on Mar 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 635
Expand file tree
/
Copy pathgrumpc
More file actions
executable file
·153 lines (126 loc) · 4.7 KB
/
grumpc
File metadata and controls
executable file
·153 lines (126 loc) · 4.7 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
145
146
147
148
149
150
151
152
153
#!/usr/bin/env python
# coding=utf-8
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""A Python -> Go transcompiler."""
from __future__ import unicode_literals
import argparse
import os
import sys
import textwrap
from StringIO import StringIO
from grumpy.compiler import block
from grumpy.compiler import imputil
from grumpy.compiler import stmt
from grumpy.compiler import util
from grumpy import pythonparser
parser = argparse.ArgumentParser()
parser.add_argument('script', help='Python source filename')
parser.add_argument('-modname', default='__main__', help='Python module name')
parser.add_argument('-output', default=None,
help='Golang output file path (defaults to stdout)')
parser.add_argument('-astest', default=False, action='store_true',
help='Output as a test suite.')
def main(args):
for arg in ('script', 'modname'):
if not getattr(args, arg, None):
print >> sys.stderr, '{} arg must not be empty'.format(arg)
return 1
gopath = os.getenv('GOPATH', None)
if not gopath:
print >> sys.stderr, 'GOPATH not set'
return 1
with open(args.script) as py_file:
py_contents = py_file.read()
try:
parsed_module = pythonparser.parse(py_contents)
except SyntaxError as e:
print >> sys.stderr, '{}: line {}: invalid syntax: {}'.format(
e.filename, e.lineno, e.text)
return 2
# Do a pass for compiler directives from `from __future__ import *` statements
try:
future_node, future_features = imputil.parse_future_features(parsed_module)
except util.CompileError as e:
print >> sys.stderr, str(e)
return 2
importer = imputil.Importer(gopath, args.modname, args.script,
future_features.absolute_import)
full_package_name = args.modname.replace('.', '/')
module_block = block.ModuleBlock(importer, full_package_name, args.script,
py_contents, future_features)
visitor = stmt.StatementVisitor(module_block, future_node)
# Indent so that the module body is aligned with the goto labels.
with visitor.writer.indent_block():
try:
visitor.visit(parsed_module)
except util.ParseError as e:
print >> sys.stderr, str(e)
return 2
go_result = StringIO()
writer = util.Writer(go_result)
tmpl = textwrap.dedent("""\
package $package
import πg "grumpy"
$import_testing
var Code *πg.Code
func init() {
\tCode = πg.NewCode("<module>", $script, nil, 0, func(πF *πg.Frame, _ []*πg.Object) (*πg.Object, *πg.BaseException) {
\t\tvar πR *πg.Object; _ = πR
\t\tvar πE *πg.BaseException; _ = πE""")
go_package_name = args.modname.split('.')[-1]
# HACK: Should suppress _test from package name
# See: https://github.com/google/grumpy/issues/383#issuecomment-353394740
if go_package_name.endswith('_test'):
final_package_name = go_package_name[:-5]
else:
final_package_name = go_package_name
modname = util.go_str(args.modname)
writer.write_tmpl(tmpl, package=final_package_name,
import_testing='import πt "testing"' if args.astest else '',
script=util.go_str(args.script))
with writer.indent_block(2):
for s in sorted(module_block.strings):
writer.write('ß{} := πg.InternStr({})'.format(s, util.go_str(s)))
writer.write_temp_decls(module_block)
writer.write_block(module_block, visitor.writer.getvalue())
writer.write_tmpl(textwrap.dedent("""\
\t\treturn nil, πE
\t})
\tπg.RegisterModule($modname, Code)
}"""), modname=modname)
if args.astest:
tmpl = textwrap.dedent("""\
func TestRunCode(t *testing.T) {
\tinit()
\tπg.ImportModule(grumpy.NewRootFrame(), "traceback")
\t//πg.ImportModule(grumpy.NewRootFrame(), $modname)
\tπg.RunMain(Code)
}
""")
writer.write_tmpl(tmpl, modname=modname)
try:
if args.output:
go_output = open(args.output, 'w')
else:
go_output = sys.stdout
except IOError:
print >> sys.stderr, str(e)
return 2
go_result.seek(0)
go_output.write(go_result.read())
go_output.close()
return 0
if __name__ == '__main__':
sys.exit(main(parser.parse_args()))