-
Notifications
You must be signed in to change notification settings - Fork 0
/
yamlscript.go
63 lines (53 loc) · 1.54 KB
/
yamlscript.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
package yamlscript
// #cgo LDFLAGS: -lyamlscript.0.1.83
// #include <libyamlscript.0.1.83.h>
// #include <stdlib.h>
import "C"
import (
"encoding/json"
"errors"
"log"
"runtime"
"unsafe"
)
// Create a new GraalVM isolatethread for life of the YAMLScript instance:
var isolatethread unsafe.Pointer
// Tear down the isolate thread to free resources
func free() {
rc := C.graal_tear_down_isolate((*C.graal_isolatethread_t)(isolatethread))
if rc != 0 {
log.Fatal("Failed to tear down isolate")
}
}
// YAMLScript instance constructor
func init() {
rc := C.graal_create_isolate(nil, nil, (**C.graal_isolatethread_t)(unsafe.Pointer(&isolatethread)))
if rc != 0 {
log.Fatal("Failed to create isolate")
}
runtime.SetFinalizer(&isolatethread, free)
}
// Compile and eval a YAMLScript string and return the result
func Load(input string) (data any, err error) {
cs := C.CString(input)
// Call 'load_ys_to_json' function in libyamlscript shared library:
data_json := C.GoString(C.load_ys_to_json(C.longlong(uintptr(isolatethread)), cs))
C.free(unsafe.Pointer(cs))
// Decode the JSON response:
var resp map[string]any
err = json.Unmarshal([]byte(data_json), &resp)
if err != nil {
return
}
// Check for libyamlscript error in JSON response:
if error_json, ok := resp["error"]; ok {
err = errors.New(error_json.(map[string]any)["cause"].(string))
return
}
// Get the response object from evaluating the YAMLScript string:
var ok bool
if data, ok = resp["data"]; !ok {
err = errors.New("unexpected response from 'libyamlscript'")
}
return
}