-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathmain_js.go
110 lines (90 loc) · 2.25 KB
/
main_js.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
// 版权 @2022 凹语言 作者。保留所有权利。
//go:build wasm
// +build wasm
// wa 命令 js/wasm 版本, 用于 playground 环境.
package main
import (
"fmt"
"syscall/js"
"wa-lang.org/wa/api"
"wa-lang.org/wa/internal/backends/compiler_wat"
"wa-lang.org/wa/internal/config"
"wa-lang.org/wa/internal/loader"
"wa-lang.org/wa/internal/logger"
)
var waError error
func main() {
window := js.Global().Get("window")
// __WA_FILE_NAME__ 表示文件名, 用于区分中英文语法
// __WA_CODE__ 代码内容
waName := getJsValue(window, "__WA_FILE_NAME__", "hello.wa")
waCode := getJsValue(window, "__WA_CODE__", "// no code")
waClearError()
outWat := waGenerateWat(waName, waCode)
outFmt := waFormatCode(waName, waCode)
if !window.IsNull() && !window.IsUndefined() {
window.Set("__WA_WAT__", outWat)
window.Set("__WA_FMT_CODE__", outFmt)
window.Set("__WA_ERROR__", waGetErrorText())
} else {
fmt.Println(outWat)
}
}
func waGenerateWat(filename, code string) string {
cfg := api.DefaultConfig()
cfg.Target = api.WaOS_js
wat, err := waBuildFile(cfg, filename, code)
if err != nil {
if waGetError() == nil {
waSetError(err)
}
return ""
}
return string(wat)
}
func waFormatCode(filename, code string) string {
newCode, err := api.FormatCode(filename, code)
if err != nil {
if waGetError() == nil {
waSetError(err)
}
return code
}
return newCode
}
// 构建 wat 目标
func waBuildFile(cfg *config.Config, filename string, src interface{}) (wat []byte, err error) {
prog, err := loader.LoadProgramFile(cfg, filename, src)
if err != nil || prog == nil {
logger.Tracef(&config.EnableTrace_api, "LoadProgramVFS failed, err = %v", err)
return nil, err
}
watOut, err := compiler_wat.New().Compile(prog)
return []byte(watOut), err
}
func getJsValue(window js.Value, key, defaultValue string) string {
if window.IsNull() || window.IsUndefined() {
return defaultValue
}
if x := window.Get(key); x.IsNull() || x.IsUndefined() {
return defaultValue
} else {
return x.String()
}
}
func waGetError() error {
return waError
}
func waGetErrorText() string {
if waError != nil {
return waError.Error()
} else {
return ""
}
}
func waSetError(err error) {
waError = err
}
func waClearError() {
waError = nil
}