/
generator.go
658 lines (558 loc) · 18.7 KB
/
generator.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
package generator
import (
"bytes"
"context"
"embed"
"fmt"
"go/format"
"go/token"
"log"
"os"
"path"
"reflect"
"sort"
"strconv"
"strings"
"text/template"
"unicode"
"github.com/jerbob92/wazero-emscripten-embind"
"github.com/tetratelabs/wazero"
"github.com/tetratelabs/wazero/api"
"github.com/tetratelabs/wazero/imports/emscripten"
"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1"
"golang.org/x/tools/go/packages"
)
var (
//go:embed templates/*
templates embed.FS
)
func Generate(dir string, fileName string, wasm []byte, initFunction string) error {
fset := token.NewFileSet()
pkgs, err := packages.Load(&packages.Config{
Fset: fset,
Mode: packages.NeedSyntax | packages.NeedName | packages.NeedModule | packages.NeedTypes | packages.NeedTypesInfo,
}, fmt.Sprintf("file=%s", fileName))
if err != nil {
return err
}
ctx := context.Background()
runtimeConfig := wazero.NewRuntimeConfigInterpreter()
r := wazero.NewRuntimeWithConfig(ctx, runtimeConfig)
defer r.Close(ctx)
// Create a WASI module and compile it so that we can check for missing
// functions and add them.
wasiBuilder := r.NewHostModuleBuilder(wasi_snapshot_preview1.ModuleName)
wasiExporter := wasi_snapshot_preview1.NewFunctionExporter()
wasiExporter.ExportFunctions(wasiBuilder)
compiledWasi, err := wasiBuilder.Compile(ctx)
if err != nil {
return err
}
// Compile the module so that we can dynamically generate the needed
// functions in the Emscripten package.
compiledModule, err := r.CompileModule(ctx, wasm)
if err != nil {
return err
}
// Create a new env module, which is where the Emscripten and embind host
// function calls are in.
envBuilder := r.NewHostModuleBuilder("env")
emscriptenExporter, err := emscripten.NewFunctionExporterForModule(compiledModule)
if err != nil {
return err
}
// Export the Emscripten host functions to the env module builder.
emscriptenExporter.ExportFunctions(envBuilder)
// Create a new embind engine and export the embind functions to the
// env module builder.
engine := embind.CreateEngine(nil)
ctx = engine.Attach(ctx)
// Dynamically generate the needed embind host functions by looking at the
// compiled module of the WASM file.
embindExporter := engine.NewFunctionExporterForModule(compiledModule)
err = embindExporter.ExportFunctions(envBuilder)
if err != nil {
return err
}
// Compile the env module in its current state so that we can check for
// missing functions and add them.
compiledEnv, err := envBuilder.Compile(ctx)
if err != nil {
return err
}
compiledModules := map[string]wazero.CompiledModule{
compiledEnv.Name(): compiledEnv,
compiledWasi.Name(): compiledWasi,
}
builders := map[string]wazero.HostModuleBuilder{
compiledEnv.Name(): envBuilder,
compiledWasi.Name(): wasiBuilder,
}
// Generate any missing imports.
importedFunctions := compiledModule.ImportedFunctions()
for i := range importedFunctions {
module, importName, _ := importedFunctions[i].Import()
var dummyFunc = api.GoModuleFunc(func(ctx context.Context, mod api.Module, stack []uint64) {
log.Fatalf("called wazero-emscripten-embind dummy host method \"%s.%s\", this should not happen.", module, importName)
})
// Add function to existing module.
compiledModule, compiledModuleExists := compiledModules[module]
if compiledModuleExists {
exportedModuleFunctions := compiledModule.ExportedFunctions()
// If the function doesn't exist yet, add it. Except _embind and
// _emval functions, those indicate an issue with the implementation.
if _, isset := exportedModuleFunctions[importName]; !isset {
if module == "env" && strings.HasPrefix(importName, "_embind") || strings.HasPrefix(importName, "_emval") {
return fmt.Errorf("missing host method \"%s\", this indicates a missing feature in wazero-emscripten-embind", importName)
}
builders[module].NewFunctionBuilder().
WithName(importName).
WithGoModuleFunction(dummyFunc, importedFunctions[i].ParamTypes(), importedFunctions[i].ResultTypes()).
Export(importName)
}
continue
}
// Create a builder for this module if it doesn't exist yet.
_, builderExists := builders[module]
if !builderExists {
builders[module] = r.NewHostModuleBuilder(module)
}
// Add the missing function to the builder. If it's not in a compiled
// module the function will always be missing, so we don't have to
// check for that.
builders[module].NewFunctionBuilder().
WithName(importName).
WithGoModuleFunction(dummyFunc, importedFunctions[i].ParamTypes(), importedFunctions[i].ResultTypes()).
Export(importName)
}
// Compile and register all the builders with the runtime.
for module := range builders {
_, err = builders[module].Instantiate(ctx)
if err != nil {
return err
}
}
moduleConfig := wazero.NewModuleConfig().
WithStartFunctions("").
WithName("")
mod, err := r.InstantiateModule(ctx, compiledModule, moduleConfig)
if err != nil {
return err
}
initFunc := mod.ExportedFunction(initFunction)
if initFunc == nil {
log.Fatalf("init function %s does not exist", initFunction)
}
res, err := initFunc.Call(ctx)
if res != nil {
return fmt.Errorf("could not call init function %w", err)
}
packageName := pkgs[0].Name
packagePath := pkgs[0].PkgPath
templates, err := template.New("").
Funcs(TemplateFunctions). // Custom functions
ParseFS(templates, "templates/*.tmpl")
if err != nil {
panic(err)
}
data := TemplateData{
Pkg: packageName,
PkgPath: packagePath,
Symbols: []TemplateSymbol{},
Constants: []TemplateConstant{},
Enums: []TemplateEnum{},
Classes: []TemplateClass{},
}
generateGoName := func(name string) string {
if len(name) == 0 {
return name
}
upperFirst := string(unicode.ToUpper(rune(name[0]))) + name[1:]
return upperFirst
}
typeNameToGeneratedName := func(name string, isClass, isEnum, isArgument bool) string {
if isClass {
name = strings.TrimPrefix(name, "*")
name = "Class" + generateGoName(name)
name = "*" + name
if isArgument {
name = "embind.ClassBase"
}
} else if isEnum {
name = "Enum" + generateGoName(name)
}
return name
}
typeNameToErrorValue := func(name string, isClass, isEnum bool) string {
convertedName := typeNameToGeneratedName(name, isClass, isEnum, false)
if isClass || convertedName == "any" || strings.HasPrefix(convertedName, "[]") || strings.HasPrefix(convertedName, "map[") {
return "nil"
}
if convertedName == "string" {
return "\"\""
}
if convertedName == "bool" {
return convertedName + "(false)"
}
// Default other types take 0
return convertedName + "(0)"
}
constants := engine.GetConstants()
for i := range constants {
constantValue := constants[i].Value()
formattedConstantValue := fmt.Sprintf("%#v", constantValue)
constant := TemplateConstant{
Name: constants[i].Name(),
GoName: "Constant_" + constants[i].Name(),
Value: formattedConstantValue,
CanBeConstant: true,
GoType: typeNameToGeneratedName(constants[i].Type().Type(), constants[i].Type().IsClass(), constants[i].Type().IsEnum(), false),
ValuePrefix: "(",
ValueSuffix: ")",
}
if constantValue != nil {
typeOfConstant := reflect.TypeOf(constantValue)
switch typeOfConstant.Kind() {
case reflect.Map, reflect.Pointer, reflect.Struct, reflect.Slice,
reflect.Array, reflect.UnsafePointer, reflect.Chan:
constant.CanBeConstant = false
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32,
reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16,
reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
// Pretty print numbers
constant.Value = fmt.Sprintf("%v", constantValue)
}
}
data.Constants = append(data.Constants, constant)
}
sort.Slice(data.Constants, func(i, j int) bool {
return data.Constants[i].Name < data.Constants[j].Name
})
symbols := engine.GetSymbols()
for i := range symbols {
exposedArgumentTypes := symbols[i].ArgumentTypes()
argumentTypes := make([]string, len(exposedArgumentTypes))
for i := range exposedArgumentTypes {
argumentTypes[i] = typeNameToGeneratedName(exposedArgumentTypes[i].Type(), exposedArgumentTypes[i].IsClass(), exposedArgumentTypes[i].IsEnum(), true)
}
goName := generateGoName(symbols[i].Symbol())
if symbols[i].IsOverload() && symbols[i].OverloadCount() > 1 {
goName += strconv.Itoa(len(argumentTypes))
}
symbol := TemplateSymbol{
Symbol: symbols[i].Symbol(),
GoName: goName,
ArgumentTypes: argumentTypes,
ReturnType: "any",
ErrorValue: "nil",
}
returnType := symbols[i].ReturnType()
if returnType != nil {
symbol.ReturnType = typeNameToGeneratedName(returnType.Type(), returnType.IsClass(), returnType.IsEnum(), true)
symbol.ErrorValue = typeNameToErrorValue(returnType.Type(), returnType.IsClass(), returnType.IsEnum())
}
data.Symbols = append(data.Symbols, symbol)
}
sort.Slice(data.Symbols, func(i, j int) bool {
if data.Symbols[i].GoName == data.Symbols[j].GoName {
return data.Symbols[i].Symbol < data.Symbols[j].Symbol
}
return data.Symbols[i].GoName < data.Symbols[j].GoName
})
// Prevent duplicate names.
seenNames := map[string]bool{}
for i := range data.Symbols {
_, ok := seenNames[data.Symbols[i].GoName]
if ok {
data.Symbols[i].GoName += "_"
}
seenNames[data.Symbols[i].GoName] = true
}
enums := engine.GetEnums()
for i := range enums {
enum := TemplateEnum{
Name: enums[i].Name(),
GoName: "Enum" + generateGoName(enums[i].Name()),
GoType: typeNameToGeneratedName(enums[i].Type().Type(), enums[i].Type().IsClass(), enums[i].Type().IsEnum(), false),
Values: []TemplateEnumValue{},
}
values := enums[i].Values()
for i := range values {
enum.Values = append(enum.Values, TemplateEnumValue{
Name: values[i].Name(),
GoName: values[i].Name(),
Value: fmt.Sprintf("%v", values[i].Value()),
})
}
sort.Slice(enum.Values, func(i, j int) bool {
return enum.Values[i].GoName < enum.Values[j].GoName
})
data.Enums = append(data.Enums, enum)
}
sort.Slice(data.Enums, func(i, j int) bool {
return data.Enums[i].GoName < data.Enums[j].GoName
})
classes := engine.GetClasses()
for i := range classes {
class := TemplateClass{
Name: classes[i].Name(),
GoName: "Class" + generateGoName(classes[i].Name()),
Constructors: []TemplateClassConstructor{},
}
constructors := classes[i].Constructors()
for ci := range constructors {
exposedArgumentTypes := constructors[ci].ArgumentTypes()
argumentTypes := make([]string, len(exposedArgumentTypes))
for i := range exposedArgumentTypes {
argumentTypes[i] = typeNameToGeneratedName(exposedArgumentTypes[i].Type(), exposedArgumentTypes[i].IsClass(), exposedArgumentTypes[i].IsEnum(), true)
}
constructor := TemplateClassConstructor{
Name: constructors[ci].Name(),
ArgumentTypes: argumentTypes,
}
class.Constructors = append(class.Constructors, constructor)
}
sort.Slice(class.Constructors, func(i, j int) bool {
return class.Constructors[i].Name < class.Constructors[j].Name
})
properties := classes[i].Properties()
for pi := range properties {
property := TemplateClassProperty{
Name: properties[pi].Name(),
GoName: generateGoName(properties[pi].Name()),
ReadOnly: properties[pi].ReadOnly(),
GetterType: "any",
ErrorValue: "nil",
}
getterType := properties[pi].GetterType()
if getterType != nil {
property.GetterType = typeNameToGeneratedName(getterType.Type(), getterType.IsClass(), getterType.IsEnum(), true)
property.ErrorValue = typeNameToErrorValue(getterType.Type(), getterType.IsClass(), getterType.IsEnum())
}
if !property.ReadOnly {
setterType := properties[pi].SetterType()
if setterType != nil {
property.SetterType = typeNameToGeneratedName(setterType.Type(), setterType.IsClass(), setterType.IsEnum(), true)
} else {
property.SetterType = "any"
}
}
class.Properties = append(class.Properties, property)
}
sort.Slice(class.Properties, func(i, j int) bool {
return class.Properties[i].GoName < class.Properties[j].GoName
})
staticProperties := classes[i].StaticProperties()
for pi := range staticProperties {
property := TemplateClassProperty{
Name: staticProperties[pi].Name(),
GoName: generateGoName(staticProperties[pi].Name()),
ReadOnly: staticProperties[pi].ReadOnly(),
GetterType: "any",
ErrorValue: "nil",
}
getterType := staticProperties[pi].GetterType()
if getterType != nil {
property.GetterType = typeNameToGeneratedName(getterType.Type(), getterType.IsClass(), getterType.IsEnum(), true)
property.ErrorValue = typeNameToErrorValue(getterType.Type(), getterType.IsClass(), getterType.IsEnum())
}
if !property.ReadOnly {
setterType := staticProperties[pi].SetterType()
if setterType != nil {
property.SetterType = typeNameToGeneratedName(setterType.Type(), setterType.IsClass(), setterType.IsEnum(), true)
} else {
property.SetterType = "any"
}
}
class.StaticProperties = append(class.StaticProperties, property)
}
sort.Slice(class.StaticProperties, func(i, j int) bool {
return class.StaticProperties[i].GoName < class.StaticProperties[j].GoName
})
methods := classes[i].Methods()
for mi := range methods {
exposedArgumentTypes := methods[mi].ArgumentTypes()
argumentTypes := make([]string, len(exposedArgumentTypes))
for i := range exposedArgumentTypes {
argumentTypes[i] = typeNameToGeneratedName(exposedArgumentTypes[i].Type(), exposedArgumentTypes[i].IsClass(), exposedArgumentTypes[i].IsEnum(), true)
}
goName := generateGoName(methods[mi].Symbol())
if methods[mi].IsOverload() && methods[mi].OverloadCount() > 1 {
goName += strconv.Itoa(len(argumentTypes))
}
method := TemplateClassMethod{
Name: methods[mi].Symbol(),
GoName: goName,
ArgumentTypes: argumentTypes,
ReturnType: "any",
ErrorValue: "nil",
}
returnType := methods[mi].ReturnType()
if returnType != nil {
method.ReturnType = typeNameToGeneratedName(returnType.Type(), returnType.IsClass(), returnType.IsEnum(), true)
method.ErrorValue = typeNameToErrorValue(returnType.Type(), returnType.IsClass(), returnType.IsEnum())
}
class.Methods = append(class.Methods, method)
}
sort.Slice(class.Methods, func(i, j int) bool {
return class.Methods[i].GoName < class.Methods[j].GoName
})
staticMethods := classes[i].StaticMethods()
for smi := range staticMethods {
exposedArgumentTypes := staticMethods[smi].ArgumentTypes()
argumentTypes := make([]string, len(exposedArgumentTypes))
for i := range exposedArgumentTypes {
argumentTypes[i] = typeNameToGeneratedName(exposedArgumentTypes[i].Type(), exposedArgumentTypes[i].IsClass(), exposedArgumentTypes[i].IsEnum(), true)
}
goName := generateGoName(staticMethods[smi].Symbol())
if staticMethods[smi].IsOverload() && staticMethods[smi].OverloadCount() > 1 {
goName += strconv.Itoa(len(argumentTypes))
}
method := TemplateClassMethod{
Name: staticMethods[smi].Symbol(),
GoName: goName,
ArgumentTypes: argumentTypes,
ReturnType: "any",
ErrorValue: "nil",
}
returnType := staticMethods[smi].ReturnType()
if returnType != nil {
method.ReturnType = typeNameToGeneratedName(returnType.Type(), returnType.IsClass(), returnType.IsEnum(), true)
method.ErrorValue = typeNameToErrorValue(returnType.Type(), returnType.IsClass(), returnType.IsEnum())
}
class.StaticMethods = append(class.StaticMethods, method)
}
sort.Slice(class.StaticMethods, func(i, j int) bool {
return class.StaticMethods[i].GoName < class.StaticMethods[j].GoName
})
data.Classes = append(data.Classes, class)
}
sort.Slice(data.Classes, func(i, j int) bool {
return data.Classes[i].GoName < data.Classes[j].GoName
})
if len(data.Classes) > 0 {
err = ExecuteTemplate(templates, "classes.tmpl", path.Join(dir, "classes.go"), data)
if err != nil {
return err
}
} else {
_ = os.Remove(path.Join(dir, "classes.go"))
}
if len(data.Constants) > 0 {
err = ExecuteTemplate(templates, "constants.tmpl", path.Join(dir, "constants.go"), data)
if err != nil {
return err
}
} else {
_ = os.Remove(path.Join(dir, "constants.go"))
}
if len(data.Symbols) > 0 {
err = ExecuteTemplate(templates, "functions.tmpl", path.Join(dir, "functions.go"), data)
if err != nil {
return err
}
} else {
_ = os.Remove(path.Join(dir, "functions.go"))
}
if len(data.Enums) > 0 {
err = ExecuteTemplate(templates, "enums.tmpl", path.Join(dir, "enums.go"), data)
if err != nil {
return err
}
} else {
_ = os.Remove(path.Join(dir, "enums.go"))
}
err = ExecuteTemplate(templates, "engine.tmpl", path.Join(dir, "engine.go"), data)
if err != nil {
return err
}
return nil
}
var TemplateFunctions = template.FuncMap{
"lower": strings.ToLower,
}
func ExecuteTemplate(tmpl *template.Template, name string, path string, data TemplateData) error {
writer := bytes.NewBuffer(nil)
err := tmpl.ExecuteTemplate(writer, name, data)
if err != nil {
return err
}
fileBytes := writer.Bytes()
formattedSource, err := format.Source(fileBytes)
if err != nil {
return fmt.Errorf("could not format %s: %w\nsource:\n%s", name, err, fileBytes)
}
fileWriter, err := os.Create(path)
if err != nil {
return err
}
defer fileWriter.Close()
_, err = fileWriter.Write(formattedSource)
if err != nil {
return err
}
return nil
}
type TemplateData struct {
Pkg string
PkgPath string
Enums []TemplateEnum
Symbols []TemplateSymbol
Constants []TemplateConstant
Classes []TemplateClass
}
type TemplateConstant struct {
Name string
GoName string
Value string
GoType string
ValuePrefix string
ValueSuffix string
CanBeConstant bool
}
type TemplateEnum struct {
Name string
GoName string
GoType string
Values []TemplateEnumValue
}
type TemplateEnumValue struct {
Name string
GoName string
Value string
}
type TemplateClass struct {
Name string
GoName string
Constructors []TemplateClassConstructor
Properties []TemplateClassProperty
StaticProperties []TemplateClassProperty
Methods []TemplateClassMethod
StaticMethods []TemplateClassMethod
}
type TemplateClassProperty struct {
GoName string
Name string
SetterType string
GetterType string
ReadOnly bool
ErrorValue string
}
type TemplateClassMethod struct {
GoName string
Name string
ArgumentTypes []string
ReturnType string
ErrorValue string
}
type TemplateClassConstructor struct {
Name string
ArgumentTypes []string
}
type TemplateSymbol struct {
Symbol string
GoName string
ArgumentTypes []string
ReturnType string
ErrorValue string
}