aboutsummaryrefslogtreecommitdiffstats
path: root/jsre/jsre.go
blob: a01fb56d83d5c787a4547b898eeb8892b73f9066 (plain) (blame)
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
package jsre

import (
    "fmt"
    "github.com/robertkrimen/otto"
    "io/ioutil"

    "github.com/ethereum/go-ethereum/common"
)

/*
JSRE is a generic JS runtime environment embedding the otto JS interpreter.
It provides some helper functions to
- load code from files
- run code snippets
- require libraries
- bind native go objects
*/
type JSRE struct {
    assetPath string
    vm        *otto.Otto
}

func New(assetPath string) *JSRE {
    re := &JSRE{
        assetPath,
        otto.New(),
    }

    // load prettyprint func definition
    re.vm.Run(pp_js)
    re.vm.Set("loadScript", re.loadScript)

    return re
}

// Exec(file) loads and runs the contents of a file
// if a relative path is given, the jsre's assetPath is used
func (self *JSRE) Exec(file string) error {
    return self.exec(common.AbsolutePath(self.assetPath, file))
}

func (self *JSRE) exec(path string) error {
    code, err := ioutil.ReadFile(path)
    if err != nil {
        return err
    }
    _, err = self.vm.Run(code)
    return err
}

func (self *JSRE) Bind(name string, v interface{}) (err error) {
    self.vm.Set(name, v)
    return
}

func (self *JSRE) Run(code string) (otto.Value, error) {
    return self.vm.Run(code)
}

func (self *JSRE) Get(ns string) (otto.Value, error) {
    return self.vm.Get(ns)
}

func (self *JSRE) Set(ns string, v interface{}) error {
    return self.vm.Set(ns, v)
}

func (self *JSRE) loadScript(call otto.FunctionCall) otto.Value {
    file, err := call.Argument(0).ToString()
    if err != nil {
        return otto.FalseValue()
    }
    if err := self.Exec(file); err != nil {
        fmt.Println("err:", err)
        return otto.FalseValue()
    }

    return otto.TrueValue()
}

func (self *JSRE) PrettyPrint(v interface{}) (val otto.Value, err error) {
    var method otto.Value
    v, err = self.vm.ToValue(v)
    if err != nil {
        return
    }
    method, err = self.vm.Get("prettyPrint")
    if err != nil {
        return
    }
    return method.Call(method, v)
}

func (self *JSRE) ToVal(v interface{}) otto.Value {
    result, err := self.vm.ToValue(v)
    if err != nil {
        fmt.Println("Value unknown:", err)
        return otto.UndefinedValue()
    }
    return result
}

func (self *JSRE) Eval(code string) (s string, err error) {
    var val otto.Value
    val, err = self.Run(code)
    if err != nil {
        return
    }
    val, err = self.PrettyPrint(val)
    if err != nil {
        return
    }
    return fmt.Sprintf("%v", val), nil
}