-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_wasm.go
More file actions
250 lines (210 loc) · 5.99 KB
/
main_wasm.go
File metadata and controls
250 lines (210 loc) · 5.99 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
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
//go:build js && wasm
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"sync"
"syscall/js"
"github.com/minecraftmetascript/mms/lang"
"github.com/minecraftmetascript/mms/lang/ast"
"github.com/minecraftmetascript/mms/lang/spec"
"github.com/minecraftmetascript/mms/lib"
"github.com/minecraftmetascript/mms/lsp"
"github.com/minecraftmetascript/mms/project"
)
var logger = log.Default()
type packagedProject struct {
Source map[string]string `json:"source"`
Files *lib.FileTreeLike `json:"files"`
Symbols map[string]*ast.Namespace `json:"symbols"`
}
func packageProject() (string, error) {
out := packagedProject{
Source: make(map[string]string),
Files: instanceProject.BuildFsLike("my_mms_project"),
Symbols: instanceProject.Symbols(),
}
for _, file := range instanceProject.Files() {
out.Source[file.Path()] = file.Content()
}
serialized, err := json.Marshal(out)
if err != nil {
log.Println("[Err]: Failed to package project: ", err)
return "\"\"", err
}
return string(serialized), nil
}
func updateFile(_ js.Value, args []js.Value) any {
if len(args) != 3 {
return nil
}
filename := args[0].String()
content := args[1].String()
dst := args[2]
if dst.Type() != js.TypeFunction {
return nil
}
_, err := instanceProject.AddFile(filename, content)
if err != nil {
log.Println("[Err]: Failed to add file:", err)
return nil
}
projectStruct, err := packageProject()
if err != nil {
log.Println("[Err]:", err)
} else {
out := js.Global().Get("Uint8Array").New(len(projectStruct))
js.CopyBytesToJS(out, []byte(projectStruct))
js.Global().Get("setTimeout").Invoke(
js.FuncOf(func(this js.Value, args []js.Value) interface{} {
dst.Invoke(out)
return nil
}),
js.ValueOf(0),
)
}
return nil
}
func getFileDiag(_ js.Value, args []js.Value) any {
if len(args) != 2 {
log.Println("[Err]: Invalid number of arguments, expected 2, given", len(args))
return nil
}
filename := args[0].String()
callback := args[1]
if callback.Type() != js.TypeFunction {
log.Println("[Err]: Invalid callback type, expected function, got", callback.Type())
return nil
}
if file := instanceProject.File(filename); file != nil {
raw, err := json.Marshal(file.Diagnostics())
if err != nil {
log.Println("[Err]:", err)
return nil
}
callback.Invoke(string(raw))
}
return nil
}
var instanceProject *project.Project
func main() {
logger.SetPrefix("[MMS:WASM]: ")
logger.SetFlags(0)
logger.Println("MMS WASM loading")
instanceProject = project.NewProject()
js.Global().Set("updateFile", js.FuncOf(updateFile))
logger.Println("updateFile function registered")
js.Global().Set("getFileDiag", js.FuncOf(getFileDiag))
logger.Println("getFileDiag function registered")
js.Global().Set("getMmsSpec", js.FuncOf(func(this js.Value, args []js.Value) any {
val := spec.GenerateSpecString(lang.Blocks)
dest := js.Global().Get("Uint8Array").New(len(val))
js.CopyBytesToJS(dest, []byte(val))
return dest
}))
logger.Println("getMmsSpec function registered")
logger.Println("MMS WASM loaded")
// JS function used to deliver bytes to the client (Go -> JS)
jsLspTo := js.Global().Get("mmsLspRead")
if jsLspTo.Type() != js.TypeFunction {
panic("mmsLspRead is not a defined function")
}
// Create single duplex stream instance
stream := NewWasmStream(jsLspTo)
// Register the function that JS will call to send data to Go (JS -> Go)
js.Global().Set("mmsLspWrite", js.FuncOf(stream.fromJs))
// Start LSP using the same stream for both reading and writing
err := lsp.StartStreaming(stream)
if err != nil {
panic(err)
}
select {} // Keep Go WASM running
}
type WasmStream struct {
// toJs is the JS function to invoke when Go writes bytes to the client.
toJs js.Value
// Internal incoming buffer (JS -> Go)
mu sync.Mutex
cond *sync.Cond
buf bytes.Buffer
closed bool
}
// NewWasmStream constructs a new stream with a ready condition variable.
func NewWasmStream(toJS js.Value) *WasmStream {
ws := &WasmStream{toJs: toJS}
ws.cond = sync.NewCond(&ws.mu)
return ws
}
// fromJs is exposed to JS as mmsLspWrite. It accepts a single string argument
// and appends it to the internal buffer for Read() to consume.
func (w *WasmStream) fromJs(_ js.Value, args []js.Value) any {
if len(args) != 1 {
log.Println("[Err]: Invalid number of arguments, expected 1, given", len(args))
return nil
}
var data []byte
switch args[0].Type() {
case js.TypeString:
data = []byte(args[0].String())
case js.TypeObject:
// Support Uint8Array input
uint8Array := js.Global().Get("Uint8Array")
if uint8Array.Truthy() && args[0].InstanceOf(uint8Array) {
length := args[0].Get("byteLength").Int()
data = make([]byte, length)
js.CopyBytesToGo(data, args[0])
} else {
log.Println("[Err]: Invalid argument type, expected string or Uint8Array")
return nil
}
default:
log.Println("[Err]: Invalid argument type, expected string or Uint8Array, got", args[0].Type())
return nil
}
w.mu.Lock()
defer w.mu.Unlock()
if w.closed {
// Ignore incoming data if closed
return nil
}
w.buf.Write(data)
w.cond.Signal()
return nil
}
// Read blocks until data is available or the stream is closed.
// Returns io.EOF if closed and no more data is available.
func (w *WasmStream) Read(p []byte) (n int, err error) {
w.mu.Lock()
defer w.mu.Unlock()
for w.buf.Len() == 0 && !w.closed {
w.cond.Wait()
}
if w.buf.Len() == 0 && w.closed {
return 0, io.EOF
}
res, e := w.buf.Read(p)
return res, e
}
// Write sends bytes to JS via the provided function.
func (w *WasmStream) Write(p []byte) (n int, err error) {
if w.toJs.Type() != js.TypeFunction {
return 0, fmt.Errorf("destination JS function is not defined")
}
out := js.Global().Get("Uint8Array").New(len(p))
js.CopyBytesToJS(out, p)
w.toJs.Invoke(out)
return len(p), nil
}
// Close marks the stream as closed and wakes any waiting readers.
func (w *WasmStream) Close() error {
w.mu.Lock()
defer w.mu.Unlock()
if !w.closed {
w.closed = true
w.cond.Broadcast()
}
return nil
}