forked from tardisgo/tardisgo
/
tardisgo.go
336 lines (291 loc) · 9.64 KB
/
tardisgo.go
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Modifications:
// Copyright 2014 Elliott Stoneham and The TARDIS Go Authors
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// TARDIS Go is a Go->Haxe transpiler.
// However the tool is written with a "language" interface type separating the generic from the language specific parts of the code, which will allow other languages to be targeted in future.
// To see example code working in your browser please visit http://tardisgo.github.io .
// For simplicity, the current command line tool is simply a modified version of ssadump: a tool for displaying and interpreting the SSA form of Go programs.
package main
import (
"flag"
"fmt"
"go/build"
"log"
"os"
"runtime"
"runtime/pprof"
"strings"
"golang.org/x/tools/go/loader"
"golang.org/x/tools/go/ssa"
"golang.org/x/tools/go/ssa/interp"
"golang.org/x/tools/go/ssa/ssautil"
"golang.org/x/tools/go/types"
// TARDIS Go additions
"github.com/tardisgo/tardisgo/haxe" // TARDIS Go addition
"github.com/tardisgo/tardisgo/pogo"
)
/*
var buildFlag = flag.String("build", "", `Options controlling the SSA builder.
The value is a sequence of zero or more of these letters:
C perform sanity [C]hecking of the SSA form.
D include [D]ebug info for every function.
P log [P]ackage inventory.
F log [F]unction SSA code.
S log [S]ource locations as SSA builder progresses.
G use binary object files from gc to provide imports (no code).
L build distinct packages seria[L]ly instead of in parallel.
N build [N]aive SSA form: don't replace local loads/stores with registers.
`)
*/
var testFlag = flag.Bool("test", false, "Loads test code (*_test.go) for imported packages.")
var loadTestZipFS = false
const testFS = "tgotestfs.zip"
var runFlag = flag.Bool("run", false, "Invokes the SSA interpreter on the program.")
var interpFlag = flag.String("interp", "", `Options controlling the SSA test interpreter.
The value is a sequence of zero or more more of these letters:
R disable [R]ecover() from panic; show interpreter crash instead.
T [T]race execution of the program. Best for single-threaded programs!
`)
// TARDIS Go addition
var targetFlag = flag.String("target", "haxe", "language to target (default is haxe)")
var allFlag = flag.String("haxe", "", "invokes the Haxe compiler (output ignored) and then runs the compiled program on the command line (OSX only): all=all targets, math=math-safe targets (cpp & js -D fullunsafe), interp=haxe interpreter")
var debugFlag = flag.Bool("debug", false, "Instrument the code to enable debugging, add comments, and give more meaningful information during a stack dump (warning: increased code size)")
var traceFlag = flag.Bool("trace", false, "Output trace information for every block visited (warning: huge output)")
var buidTags = flag.String("tags", "", "build tags separated by spaces")
var tgoroot = flag.String("tgoroot", "", "set goroot to the given value")
var modeFlag = ssa.BuilderModeFlag(flag.CommandLine, "build", 0)
// TODO
//var traceFlag = flag.Bool("v", false, "Verbose compiler mode (including files written)")
//var hxPackFlag = flag.String("hxpack", "tardis", "Sets the Haxe package name to use")
//var hxDirFlag = flag.String("hxdir", "tardis", "Sets the directory in which to output generated Haxe code")
//var hxLibFlag = flag.Bool("hxlib", false, "Generates code suitable for use as a Haxe library (no Dead Code Elimination)")
// TARDIS Go modification TODO review words here
const usage = `SSA builder and TARDIS Go transpiler (experimental).
Usage: tardisgo [<flag> ...] <args> ...
A shameless copy of the ssadump utility, but also writes a 'Go.hx' Haxe file into the 'tardis' sub-directory of the current location (which you must create by hand).
Example:
% tardisgo hello.go
Then to compile the tardis/Go.hx file generated, type the command line: "haxe -main tardis.Go -cp tardis -js tardis/go.js", or whatever Haxe compilation options you want to use.
Use -help to display other options.
`
const ignore = `
Use -help flag to display options.
Examples:
% ssadump -build=FPG hello.go # quickly dump SSA form of a single package
% ssadump -run -interp=T hello.go # interpret a program, with tracing
% ssadump -run unicode -- -test.v # interpret the unicode package's tests, verbosely
` + loader.FromArgsUsage +
`
When -run is specified, ssadump will find the first package that
defines a main function and run it in the interpreter.
If none is found, the tests of each package will be run instead.
`
// end TARDIS Go modification
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func init() {
// If $GOMAXPROCS isn't set, use the full capacity of the machine.
// For small machines, use at least 4 threads.
if os.Getenv("GOMAXPROCS") == "" {
n := runtime.NumCPU()
if n < 4 {
n = 4
}
runtime.GOMAXPROCS(n)
}
}
func main() {
if err := doMain(); err != nil {
fmt.Fprintf(os.Stderr, "TARDISgo: %s\n", err) // TARDISgo alteration
os.Exit(1)
}
os.Exit(0)
}
func doMain() error {
flag.Parse()
args := flag.Args()
return doTestable(args)
}
func doTestable(args []string) error {
conf := loader.Config{
Build: &build.Default,
}
// TARDISgo addition
langName := *targetFlag
langEntry, e := pogo.FindTargetLang(langName)
if e != nil {
return e
}
// TODO(adonovan): make go/types choose its default Sizes from
// build.Default or a specified *build.Context.
var wordSize int64 = 8
switch conf.Build.GOARCH {
case "386", "arm":
wordSize = 4
}
if *runFlag {
// nothing here at the moment
} else {
wordSize = 4 // TARDIS Go addition to force default int size to 32 bits
conf.Build.GOOS = "nacl" // TARDIS Go addition - simplest OS-specific code to emulate?
conf.Build.GOARCH = langName // TARDIS Go addition
}
conf.Build.BuildTags = strings.Split(*buidTags, " ")
conf.TypeChecker.Sizes = &types.StdSizes{ // must equal haxe.haxeStdSizes when (!*runFlag)
MaxAlign: 8,
WordSize: wordSize,
}
var mode ssa.BuilderMode
/*
for _, c := range *buildFlag {
switch c {
case 'D':
mode |= ssa.GlobalDebug
case 'P':
mode |= ssa.PrintPackages
case 'F':
mode |= ssa.PrintFunctions
case 'S':
mode |= ssa.LogSource | ssa.BuildSerially
case 'C':
mode |= ssa.SanityCheckFunctions
case 'N':
mode |= ssa.NaiveForm
case 'L':
mode |= ssa.BuildSerially
case 'I':
mode |= ssa.BareInits
default:
return fmt.Errorf("unknown -build option: '%c'", c)
}
}
*/
// TARDIS go addition
if *debugFlag {
mode |= ssa.GlobalDebug
}
var interpMode interp.Mode
for _, c := range *interpFlag {
switch c {
case 'T':
interpMode |= interp.EnableTracing
case 'R':
interpMode |= interp.DisableRecover
default:
log.Fatalf("Unknown -interp option: '%c'.", c)
}
}
if len(args) == 0 {
//fmt.Fprint(os.Stderr, usage)
return fmt.Errorf("%v", usage)
}
// Profiling support.
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
return err
}
err = pprof.StartCPUProfile(f)
if err != nil {
return err
}
defer pprof.StopCPUProfile()
}
if !(*runFlag) {
if *tgoroot == "" {
if conf.Build.GOPATH == "" {
return fmt.Errorf("GOPATH must be set")
}
langGOROOT := pogo.LanguageList[langEntry].GOROOT
if langGOROOT != "" {
conf.Build.GOROOT = strings.Split(conf.Build.GOPATH, ":")[0] + langGOROOT
} else {
if conf.Build.GOROOT == "" {
return fmt.Errorf("GOROOT must be set (hint: use -tgoroot flag)")
}
}
} else {
conf.Build.GOROOT = *tgoroot
}
}
//fmt.Println("DEBUG GOPATH", conf.Build.GOPATH)
//fmt.Println("DEBUG GOROOT", conf.Build.GOROOT)
if *testFlag {
conf.ImportWithTests(args[0]) // assumes you give the full cannonical name of the package to test
args = args[1:]
}
// Use the initial packages from the command line.
_, err := conf.FromArgs(args, *testFlag)
if err != nil {
return err
}
// The interpreter needs the runtime package.
if *runFlag {
conf.Import("runtime")
} else {
// TARDIS GO additional line to add the language specific go runtime code
rt := pogo.LanguageList[langEntry].Goruntime
if rt != "" {
conf.Import(rt)
}
}
// Load, parse and type-check the whole program.
iprog, err := conf.Load()
if err != nil {
return err
}
// Create and build SSA-form program representation.
*modeFlag |= mode | ssa.SanityCheckFunctions
prog := ssautil.CreateProgram(iprog, *modeFlag)
prog.Build()
var main *ssa.Package
pkgs := prog.AllPackages()
//fmt.Println("DEBUG pkgs:", pkgs)
testFSname := ""
if *testFlag {
// If -test, run all packages' tests.
if len(pkgs) > 0 {
main = prog.CreateTestMainPackage(pkgs...)
}
if main == nil {
return fmt.Errorf("no tests")
}
fd, openErr := os.Open(testFS)
closeErr := fd.Close()
if openErr == nil && closeErr == nil {
loadTestZipFS = true
testFSname = testFS
}
} else {
// Otherwise, run main.main.
for _, pkg := range pkgs {
if pkg.Pkg.Name() == "main" {
main = pkg
if main.Func("main") == nil {
return fmt.Errorf("no func main() in main package")
}
break
}
}
if main == nil {
return fmt.Errorf("no main package")
}
}
if *runFlag { // Run the golang.org/x/tools/go/ssa/interp interpreter.
interp.Interpret(main, interpMode, conf.TypeChecker.Sizes, main.Pkg.Path(), args)
} else {
comp, err := pogo.Compile(main, *debugFlag, *traceFlag, langName, testFSname) // TARDIS Go entry point, returns an error
if err != nil {
return err
}
comp.Recycle()
switch langName {
case "haxe":
haxe.RunHaxe(allFlag, loadTestZipFS, testFSname)
}
}
return nil
}