Repository navigation
Expand file tree
/
Copy pathwasm.go
More file actions
81 lines (64 loc) · 1.66 KB
/
Copy pathwasm.go
File metadata and controls
81 lines (64 loc) · 1.66 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
//go:build wasm
// +build wasm
package main
import (
"backend/emulator"
"backend/genhex"
"fmt"
"syscall/js"
)
func main() {
js.Global().Set("RunCode", js.FuncOf(run))
js.Global().Set("GenHex", js.FuncOf(genMachineLanguage))
select {}
}
func run(this js.Value, args []js.Value) interface{} {
if len(args) < 1 {
return map[string]interface{}{
"error": "hex string required",
}
}
hexInput := args[0].String()
cpu := emulator.NewCPU()
code, err := emulator.ParseHexString(hexInput)
if err != nil {
return map[string]interface{}{
"error": fmt.Sprintf("error parsing hex input: %v", err),
}
}
decoder := emulator.NewDecoder(code)
for decoder.HasMore() {
inst, err := decoder.DecodeNext()
if err != nil {
return map[string]interface{}{
"error": fmt.Sprintf("decode error: %v", err),
}
}
if err := cpu.Execute(inst); err != nil {
return map[string]interface{}{
"error": fmt.Sprintf("execute error: %v", err),
}
}
}
//return fmt.Sprintf("%x", int32(cpu.GetResult()))
return map[string]interface{}{
"value": fmt.Sprintf("%x", int32(cpu.GetResult())),
}
}
func genMachineLanguage(this js.Value, args []js.Value) interface{} {
if len(args) < 1 {
return map[string]interface{}{"error": "int argument required"}
}
level := args[0].Int()
if level < 1 || level > 4 {
return map[string]interface{}{"error": "invalid level"}
}
spaceHex, noSpaceHex, err := genhex.GenerateHex(level)
if err != nil {
return map[string]interface{}{"error": fmt.Sprintf("error generating hex: %v", err)}
}
//return []interface{}{spaceHex, noSpaceHex}
return map[string]interface{}{
"value": []interface{}{spaceHex, noSpaceHex},
}
}