console, internal/jsre: use github.com/dop251/goja (#20470)
This replaces the JavaScript interpreter used by the console with goja, which is actively maintained and a lot faster than otto. Clef still uses otto and eth/tracers still uses duktape, so we are currently dependent on three different JS interpreters. We're looking to replace the remaining uses of otto soon though.
This commit is contained in:
committed by
Felix Lange
parent
60deeb103e
commit
7b68975a00
@ -20,35 +20,43 @@ import (
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/robertkrimen/otto"
|
||||
"github.com/dop251/goja"
|
||||
)
|
||||
|
||||
// CompleteKeywords returns potential continuations for the given line. Since line is
|
||||
// evaluated, callers need to make sure that evaluating line does not have side effects.
|
||||
func (jsre *JSRE) CompleteKeywords(line string) []string {
|
||||
var results []string
|
||||
jsre.Do(func(vm *otto.Otto) {
|
||||
jsre.Do(func(vm *goja.Runtime) {
|
||||
results = getCompletions(vm, line)
|
||||
})
|
||||
return results
|
||||
}
|
||||
|
||||
func getCompletions(vm *otto.Otto, line string) (results []string) {
|
||||
func getCompletions(vm *goja.Runtime, line string) (results []string) {
|
||||
parts := strings.Split(line, ".")
|
||||
objRef := "this"
|
||||
prefix := line
|
||||
if len(parts) > 1 {
|
||||
objRef = strings.Join(parts[0:len(parts)-1], ".")
|
||||
prefix = parts[len(parts)-1]
|
||||
}
|
||||
|
||||
obj, _ := vm.Object(objRef)
|
||||
if obj == nil {
|
||||
if len(parts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Find the right-most fully named object in the line. e.g. if line = "x.y.z"
|
||||
// and "x.y" is an object, obj will reference "x.y".
|
||||
obj := vm.GlobalObject()
|
||||
for i := 0; i < len(parts)-1; i++ {
|
||||
v := obj.Get(parts[i])
|
||||
if v == nil {
|
||||
return nil // No object was found
|
||||
}
|
||||
obj = v.ToObject(vm)
|
||||
}
|
||||
|
||||
// Go over the keys of the object and retain the keys matching prefix.
|
||||
// Example: if line = "x.y.z" and "x.y" exists and has keys "zebu", "zebra"
|
||||
// and "platypus", then "x.y.zebu" and "x.y.zebra" will be added to results.
|
||||
prefix := parts[len(parts)-1]
|
||||
iterOwnAndConstructorKeys(vm, obj, func(k string) {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
if objRef == "this" {
|
||||
if len(parts) == 1 {
|
||||
results = append(results, k)
|
||||
} else {
|
||||
results = append(results, strings.Join(parts[:len(parts)-1], ".")+"."+k)
|
||||
@ -59,9 +67,9 @@ func getCompletions(vm *otto.Otto, line string) (results []string) {
|
||||
// Append opening parenthesis (for functions) or dot (for objects)
|
||||
// if the line itself is the only completion.
|
||||
if len(results) == 1 && results[0] == line {
|
||||
obj, _ := vm.Object(line)
|
||||
obj := obj.Get(parts[len(parts)-1])
|
||||
if obj != nil {
|
||||
if obj.Class() == "Function" {
|
||||
if _, isfunc := goja.AssertFunction(obj); isfunc {
|
||||
results[0] += "("
|
||||
} else {
|
||||
results[0] += "."
|
||||
|
@ -39,6 +39,10 @@ func TestCompleteKeywords(t *testing.T) {
|
||||
input string
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
input: "St",
|
||||
want: []string{"String"},
|
||||
},
|
||||
{
|
||||
input: "x",
|
||||
want: []string{"x."},
|
||||
|
@ -26,30 +26,30 @@ import (
|
||||
"math/rand"
|
||||
"time"
|
||||
|
||||
"github.com/dop251/goja"
|
||||
"github.com/ethereum/go-ethereum/common"
|
||||
"github.com/ethereum/go-ethereum/internal/jsre/deps"
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
var (
|
||||
BignumberJs = deps.MustAsset("bignumber.js")
|
||||
Web3Js = deps.MustAsset("web3.js")
|
||||
)
|
||||
|
||||
/*
|
||||
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
|
||||
*/
|
||||
// JSRE is a JS runtime environment embedding the goja interpreter.
|
||||
// It provides helper functions to load code from files, run code snippets
|
||||
// and bind native go objects to JS.
|
||||
//
|
||||
// The runtime runs all code on a dedicated event loop and does not expose the underlying
|
||||
// goja runtime directly. To use the runtime, call JSRE.Do. When binding a Go function,
|
||||
// use the Call type to gain access to the runtime.
|
||||
type JSRE struct {
|
||||
assetPath string
|
||||
output io.Writer
|
||||
evalQueue chan *evalReq
|
||||
stopEventLoop chan bool
|
||||
closed chan struct{}
|
||||
vm *goja.Runtime
|
||||
}
|
||||
|
||||
// Call is the argument type of Go functions which are callable from JS.
|
||||
type Call struct {
|
||||
goja.FunctionCall
|
||||
VM *goja.Runtime
|
||||
}
|
||||
|
||||
// jsTimer is a single timer instance with a callback function
|
||||
@ -57,12 +57,12 @@ type jsTimer struct {
|
||||
timer *time.Timer
|
||||
duration time.Duration
|
||||
interval bool
|
||||
call otto.FunctionCall
|
||||
call goja.FunctionCall
|
||||
}
|
||||
|
||||
// evalReq is a serialized vm execution request processed by runEventLoop.
|
||||
type evalReq struct {
|
||||
fn func(vm *otto.Otto)
|
||||
fn func(vm *goja.Runtime)
|
||||
done chan bool
|
||||
}
|
||||
|
||||
@ -74,9 +74,10 @@ func New(assetPath string, output io.Writer) *JSRE {
|
||||
closed: make(chan struct{}),
|
||||
evalQueue: make(chan *evalReq),
|
||||
stopEventLoop: make(chan bool),
|
||||
vm: goja.New(),
|
||||
}
|
||||
go re.runEventLoop()
|
||||
re.Set("loadScript", re.loadScript)
|
||||
re.Set("loadScript", MakeCallback(re.vm, re.loadScript))
|
||||
re.Set("inspect", re.prettyPrintJS)
|
||||
return re
|
||||
}
|
||||
@ -99,21 +100,20 @@ func randomSource() *rand.Rand {
|
||||
// serialized way and calls timer callback functions at the appropriate time.
|
||||
|
||||
// Exported functions always access the vm through the event queue. You can
|
||||
// call the functions of the otto vm directly to circumvent the queue. These
|
||||
// call the functions of the goja vm directly to circumvent the queue. These
|
||||
// functions should be used if and only if running a routine that was already
|
||||
// called from JS through an RPC call.
|
||||
func (re *JSRE) runEventLoop() {
|
||||
defer close(re.closed)
|
||||
|
||||
vm := otto.New()
|
||||
r := randomSource()
|
||||
vm.SetRandomSource(r.Float64)
|
||||
re.vm.SetRandSource(r.Float64)
|
||||
|
||||
registry := map[*jsTimer]*jsTimer{}
|
||||
ready := make(chan *jsTimer)
|
||||
|
||||
newTimer := func(call otto.FunctionCall, interval bool) (*jsTimer, otto.Value) {
|
||||
delay, _ := call.Argument(1).ToInteger()
|
||||
newTimer := func(call goja.FunctionCall, interval bool) (*jsTimer, goja.Value) {
|
||||
delay := call.Argument(1).ToInteger()
|
||||
if 0 >= delay {
|
||||
delay = 1
|
||||
}
|
||||
@ -128,47 +128,43 @@ func (re *JSRE) runEventLoop() {
|
||||
ready <- timer
|
||||
})
|
||||
|
||||
value, err := call.Otto.ToValue(timer)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return timer, value
|
||||
return timer, re.vm.ToValue(timer)
|
||||
}
|
||||
|
||||
setTimeout := func(call otto.FunctionCall) otto.Value {
|
||||
setTimeout := func(call goja.FunctionCall) goja.Value {
|
||||
_, value := newTimer(call, false)
|
||||
return value
|
||||
}
|
||||
|
||||
setInterval := func(call otto.FunctionCall) otto.Value {
|
||||
setInterval := func(call goja.FunctionCall) goja.Value {
|
||||
_, value := newTimer(call, true)
|
||||
return value
|
||||
}
|
||||
|
||||
clearTimeout := func(call otto.FunctionCall) otto.Value {
|
||||
timer, _ := call.Argument(0).Export()
|
||||
clearTimeout := func(call goja.FunctionCall) goja.Value {
|
||||
timer := call.Argument(0).Export()
|
||||
if timer, ok := timer.(*jsTimer); ok {
|
||||
timer.timer.Stop()
|
||||
delete(registry, timer)
|
||||
}
|
||||
return otto.UndefinedValue()
|
||||
return goja.Undefined()
|
||||
}
|
||||
vm.Set("_setTimeout", setTimeout)
|
||||
vm.Set("_setInterval", setInterval)
|
||||
vm.Run(`var setTimeout = function(args) {
|
||||
re.vm.Set("_setTimeout", setTimeout)
|
||||
re.vm.Set("_setInterval", setInterval)
|
||||
re.vm.RunString(`var setTimeout = function(args) {
|
||||
if (arguments.length < 1) {
|
||||
throw TypeError("Failed to execute 'setTimeout': 1 argument required, but only 0 present.");
|
||||
}
|
||||
return _setTimeout.apply(this, arguments);
|
||||
}`)
|
||||
vm.Run(`var setInterval = function(args) {
|
||||
re.vm.RunString(`var setInterval = function(args) {
|
||||
if (arguments.length < 1) {
|
||||
throw TypeError("Failed to execute 'setInterval': 1 argument required, but only 0 present.");
|
||||
}
|
||||
return _setInterval.apply(this, arguments);
|
||||
}`)
|
||||
vm.Set("clearTimeout", clearTimeout)
|
||||
vm.Set("clearInterval", clearTimeout)
|
||||
re.vm.Set("clearTimeout", clearTimeout)
|
||||
re.vm.Set("clearInterval", clearTimeout)
|
||||
|
||||
var waitForCallbacks bool
|
||||
|
||||
@ -178,8 +174,8 @@ loop:
|
||||
case timer := <-ready:
|
||||
// execute callback, remove/reschedule the timer
|
||||
var arguments []interface{}
|
||||
if len(timer.call.ArgumentList) > 2 {
|
||||
tmp := timer.call.ArgumentList[2:]
|
||||
if len(timer.call.Arguments) > 2 {
|
||||
tmp := timer.call.Arguments[2:]
|
||||
arguments = make([]interface{}, 2+len(tmp))
|
||||
for i, value := range tmp {
|
||||
arguments[i+2] = value
|
||||
@ -187,11 +183,12 @@ loop:
|
||||
} else {
|
||||
arguments = make([]interface{}, 1)
|
||||
}
|
||||
arguments[0] = timer.call.ArgumentList[0]
|
||||
_, err := vm.Call(`Function.call.call`, nil, arguments...)
|
||||
if err != nil {
|
||||
fmt.Println("js error:", err, arguments)
|
||||
arguments[0] = timer.call.Arguments[0]
|
||||
call, isFunc := goja.AssertFunction(timer.call.Arguments[0])
|
||||
if !isFunc {
|
||||
panic(re.vm.ToValue("js error: timer/timeout callback is not a function"))
|
||||
}
|
||||
call(goja.Null(), timer.call.Arguments...)
|
||||
|
||||
_, inreg := registry[timer] // when clearInterval is called from within the callback don't reset it
|
||||
if timer.interval && inreg {
|
||||
@ -204,7 +201,7 @@ loop:
|
||||
}
|
||||
case req := <-re.evalQueue:
|
||||
// run the code, send the result back
|
||||
req.fn(vm)
|
||||
req.fn(re.vm)
|
||||
close(req.done)
|
||||
if waitForCallbacks && (len(registry) == 0) {
|
||||
break loop
|
||||
@ -223,7 +220,7 @@ loop:
|
||||
}
|
||||
|
||||
// Do executes the given function on the JS event loop.
|
||||
func (re *JSRE) Do(fn func(*otto.Otto)) {
|
||||
func (re *JSRE) Do(fn func(*goja.Runtime)) {
|
||||
done := make(chan bool)
|
||||
req := &evalReq{fn, done}
|
||||
re.evalQueue <- req
|
||||
@ -246,70 +243,36 @@ func (re *JSRE) Exec(file string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var script *otto.Script
|
||||
re.Do(func(vm *otto.Otto) {
|
||||
script, err = vm.Compile(file, code)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
_, err = vm.Run(script)
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
// Bind assigns value v to a variable in the JS environment
|
||||
// This method is deprecated, use Set.
|
||||
func (re *JSRE) Bind(name string, v interface{}) error {
|
||||
return re.Set(name, v)
|
||||
return re.Compile(file, string(code))
|
||||
}
|
||||
|
||||
// Run runs a piece of JS code.
|
||||
func (re *JSRE) Run(code string) (v otto.Value, err error) {
|
||||
re.Do(func(vm *otto.Otto) { v, err = vm.Run(code) })
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Get returns the value of a variable in the JS environment.
|
||||
func (re *JSRE) Get(ns string) (v otto.Value, err error) {
|
||||
re.Do(func(vm *otto.Otto) { v, err = vm.Get(ns) })
|
||||
func (re *JSRE) Run(code string) (v goja.Value, err error) {
|
||||
re.Do(func(vm *goja.Runtime) { v, err = vm.RunString(code) })
|
||||
return v, err
|
||||
}
|
||||
|
||||
// Set assigns value v to a variable in the JS environment.
|
||||
func (re *JSRE) Set(ns string, v interface{}) (err error) {
|
||||
re.Do(func(vm *otto.Otto) { err = vm.Set(ns, v) })
|
||||
re.Do(func(vm *goja.Runtime) { vm.Set(ns, v) })
|
||||
return err
|
||||
}
|
||||
|
||||
// loadScript executes a JS script from inside the currently executing JS code.
|
||||
func (re *JSRE) loadScript(call otto.FunctionCall) otto.Value {
|
||||
file, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
// TODO: throw exception
|
||||
return otto.FalseValue()
|
||||
}
|
||||
file = common.AbsolutePath(re.assetPath, file)
|
||||
source, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
// TODO: throw exception
|
||||
return otto.FalseValue()
|
||||
}
|
||||
if _, err := compileAndRun(call.Otto, file, source); err != nil {
|
||||
// TODO: throw exception
|
||||
fmt.Println("err:", err)
|
||||
return otto.FalseValue()
|
||||
}
|
||||
// TODO: return evaluation result
|
||||
return otto.TrueValue()
|
||||
// MakeCallback turns the given function into a function that's callable by JS.
|
||||
func MakeCallback(vm *goja.Runtime, fn func(Call) (goja.Value, error)) goja.Value {
|
||||
return vm.ToValue(func(call goja.FunctionCall) goja.Value {
|
||||
result, err := fn(Call{call, vm})
|
||||
if err != nil {
|
||||
panic(vm.NewGoError(err))
|
||||
}
|
||||
return result
|
||||
})
|
||||
}
|
||||
|
||||
// Evaluate executes code and pretty prints the result to the specified output
|
||||
// stream.
|
||||
func (re *JSRE) Evaluate(code string, w io.Writer) error {
|
||||
var fail error
|
||||
|
||||
re.Do(func(vm *otto.Otto) {
|
||||
val, err := vm.Run(code)
|
||||
// Evaluate executes code and pretty prints the result to the specified output stream.
|
||||
func (re *JSRE) Evaluate(code string, w io.Writer) {
|
||||
re.Do(func(vm *goja.Runtime) {
|
||||
val, err := vm.RunString(code)
|
||||
if err != nil {
|
||||
prettyError(vm, err, w)
|
||||
} else {
|
||||
@ -317,19 +280,33 @@ func (re *JSRE) Evaluate(code string, w io.Writer) error {
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
})
|
||||
return fail
|
||||
}
|
||||
|
||||
// Compile compiles and then runs a piece of JS code.
|
||||
func (re *JSRE) Compile(filename string, src interface{}) (err error) {
|
||||
re.Do(func(vm *otto.Otto) { _, err = compileAndRun(vm, filename, src) })
|
||||
func (re *JSRE) Compile(filename string, src string) (err error) {
|
||||
re.Do(func(vm *goja.Runtime) { _, err = compileAndRun(vm, filename, src) })
|
||||
return err
|
||||
}
|
||||
|
||||
func compileAndRun(vm *otto.Otto, filename string, src interface{}) (otto.Value, error) {
|
||||
script, err := vm.Compile(filename, src)
|
||||
// loadScript loads and executes a JS file.
|
||||
func (re *JSRE) loadScript(call Call) (goja.Value, error) {
|
||||
file := call.Argument(0).ToString().String()
|
||||
file = common.AbsolutePath(re.assetPath, file)
|
||||
source, err := ioutil.ReadFile(file)
|
||||
if err != nil {
|
||||
return otto.Value{}, err
|
||||
return nil, fmt.Errorf("Could not read file %s: %v", file, err)
|
||||
}
|
||||
return vm.Run(script)
|
||||
value, err := compileAndRun(re.vm, file, string(source))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Error while compiling or running script: %v", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func compileAndRun(vm *goja.Runtime, filename string, src string) (goja.Value, error) {
|
||||
script, err := goja.Compile(filename, src, false)
|
||||
if err != nil {
|
||||
return goja.Null(), err
|
||||
}
|
||||
return vm.RunProgram(script)
|
||||
}
|
||||
|
@ -20,25 +20,24 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/robertkrimen/otto"
|
||||
"github.com/dop251/goja"
|
||||
)
|
||||
|
||||
type testNativeObjectBinding struct{}
|
||||
type testNativeObjectBinding struct {
|
||||
vm *goja.Runtime
|
||||
}
|
||||
|
||||
type msg struct {
|
||||
Msg string
|
||||
}
|
||||
|
||||
func (no *testNativeObjectBinding) TestMethod(call otto.FunctionCall) otto.Value {
|
||||
m, err := call.Argument(0).ToString()
|
||||
if err != nil {
|
||||
return otto.UndefinedValue()
|
||||
}
|
||||
v, _ := call.Otto.ToValue(&msg{m})
|
||||
return v
|
||||
func (no *testNativeObjectBinding) TestMethod(call goja.FunctionCall) goja.Value {
|
||||
m := call.Argument(0).ToString().String()
|
||||
return no.vm.ToValue(&msg{m})
|
||||
}
|
||||
|
||||
func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) {
|
||||
@ -51,7 +50,8 @@ func newWithTestJS(t *testing.T, testjs string) (*JSRE, string) {
|
||||
t.Fatal("cannot create test.js:", err)
|
||||
}
|
||||
}
|
||||
return New(dir, os.Stdout), dir
|
||||
jsre := New(dir, os.Stdout)
|
||||
return jsre, dir
|
||||
}
|
||||
|
||||
func TestExec(t *testing.T) {
|
||||
@ -66,11 +66,11 @@ func TestExec(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
if val.ExportType().Kind() != reflect.String {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
got := val.ToString().String()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
@ -90,11 +90,11 @@ func TestNatto(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
if val.ExportType().Kind() != reflect.String {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
got := val.ToString().String()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
@ -105,7 +105,7 @@ func TestBind(t *testing.T) {
|
||||
jsre := New("", os.Stdout)
|
||||
defer jsre.Stop(false)
|
||||
|
||||
jsre.Bind("no", &testNativeObjectBinding{})
|
||||
jsre.Set("no", &testNativeObjectBinding{vm: jsre.vm})
|
||||
|
||||
_, err := jsre.Run(`no.TestMethod("testMsg")`)
|
||||
if err != nil {
|
||||
@ -125,11 +125,11 @@ func TestLoadScript(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Errorf("expected no error, got %v", err)
|
||||
}
|
||||
if !val.IsString() {
|
||||
if val.ExportType().Kind() != reflect.String {
|
||||
t.Errorf("expected string value, got %v", val)
|
||||
}
|
||||
exp := "testMsg"
|
||||
got, _ := val.ToString()
|
||||
got := val.ToString().String()
|
||||
if exp != got {
|
||||
t.Errorf("expected '%v', got '%v'", exp, got)
|
||||
}
|
||||
|
@ -19,12 +19,13 @@ package jsre
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/dop251/goja"
|
||||
"github.com/fatih/color"
|
||||
"github.com/robertkrimen/otto"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -52,29 +53,29 @@ var boringKeys = map[string]bool{
|
||||
}
|
||||
|
||||
// prettyPrint writes value to standard output.
|
||||
func prettyPrint(vm *otto.Otto, value otto.Value, w io.Writer) {
|
||||
func prettyPrint(vm *goja.Runtime, value goja.Value, w io.Writer) {
|
||||
ppctx{vm: vm, w: w}.printValue(value, 0, false)
|
||||
}
|
||||
|
||||
// prettyError writes err to standard output.
|
||||
func prettyError(vm *otto.Otto, err error, w io.Writer) {
|
||||
func prettyError(vm *goja.Runtime, err error, w io.Writer) {
|
||||
failure := err.Error()
|
||||
if ottoErr, ok := err.(*otto.Error); ok {
|
||||
failure = ottoErr.String()
|
||||
if gojaErr, ok := err.(*goja.Exception); ok {
|
||||
failure = gojaErr.String()
|
||||
}
|
||||
fmt.Fprint(w, ErrorColor("%s", failure))
|
||||
}
|
||||
|
||||
func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value {
|
||||
for _, v := range call.ArgumentList {
|
||||
prettyPrint(call.Otto, v, re.output)
|
||||
func (re *JSRE) prettyPrintJS(call goja.FunctionCall) goja.Value {
|
||||
for _, v := range call.Arguments {
|
||||
prettyPrint(re.vm, v, re.output)
|
||||
fmt.Fprintln(re.output)
|
||||
}
|
||||
return otto.UndefinedValue()
|
||||
return goja.Undefined()
|
||||
}
|
||||
|
||||
type ppctx struct {
|
||||
vm *otto.Otto
|
||||
vm *goja.Runtime
|
||||
w io.Writer
|
||||
}
|
||||
|
||||
@ -82,35 +83,47 @@ func (ctx ppctx) indent(level int) string {
|
||||
return strings.Repeat(indentString, level)
|
||||
}
|
||||
|
||||
func (ctx ppctx) printValue(v otto.Value, level int, inArray bool) {
|
||||
func (ctx ppctx) printValue(v goja.Value, level int, inArray bool) {
|
||||
if goja.IsNull(v) || goja.IsUndefined(v) {
|
||||
fmt.Fprint(ctx.w, SpecialColor(v.String()))
|
||||
return
|
||||
}
|
||||
kind := v.ExportType().Kind()
|
||||
switch {
|
||||
case v.IsObject():
|
||||
ctx.printObject(v.Object(), level, inArray)
|
||||
case v.IsNull():
|
||||
fmt.Fprint(ctx.w, SpecialColor("null"))
|
||||
case v.IsUndefined():
|
||||
fmt.Fprint(ctx.w, SpecialColor("undefined"))
|
||||
case v.IsString():
|
||||
s, _ := v.ToString()
|
||||
fmt.Fprint(ctx.w, StringColor("%q", s))
|
||||
case v.IsBoolean():
|
||||
b, _ := v.ToBoolean()
|
||||
fmt.Fprint(ctx.w, SpecialColor("%t", b))
|
||||
case v.IsNaN():
|
||||
fmt.Fprint(ctx.w, NumberColor("NaN"))
|
||||
case v.IsNumber():
|
||||
s, _ := v.ToString()
|
||||
fmt.Fprint(ctx.w, NumberColor("%s", s))
|
||||
case kind == reflect.Bool:
|
||||
fmt.Fprint(ctx.w, SpecialColor("%t", v.ToBoolean()))
|
||||
case kind == reflect.String:
|
||||
fmt.Fprint(ctx.w, StringColor("%q", v.String()))
|
||||
case kind >= reflect.Int && kind <= reflect.Complex128:
|
||||
fmt.Fprint(ctx.w, NumberColor("%s", v.String()))
|
||||
default:
|
||||
fmt.Fprint(ctx.w, "<unprintable>")
|
||||
if obj, ok := v.(*goja.Object); ok {
|
||||
ctx.printObject(obj, level, inArray)
|
||||
} else {
|
||||
fmt.Fprintf(ctx.w, "<unprintable %T>", v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
|
||||
switch obj.Class() {
|
||||
// SafeGet attempt to get the value associated to `key`, and
|
||||
// catches the panic that goja creates if an error occurs in
|
||||
// key.
|
||||
func SafeGet(obj *goja.Object, key string) (ret goja.Value) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
ret = goja.Undefined()
|
||||
}
|
||||
}()
|
||||
ret = obj.Get(key)
|
||||
|
||||
return ret
|
||||
}
|
||||
|
||||
func (ctx ppctx) printObject(obj *goja.Object, level int, inArray bool) {
|
||||
switch obj.ClassName() {
|
||||
case "Array", "GoArray":
|
||||
lv, _ := obj.Get("length")
|
||||
len, _ := lv.ToInteger()
|
||||
lv := obj.Get("length")
|
||||
len := lv.ToInteger()
|
||||
if len == 0 {
|
||||
fmt.Fprintf(ctx.w, "[]")
|
||||
return
|
||||
@ -121,8 +134,8 @@ func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
|
||||
}
|
||||
fmt.Fprint(ctx.w, "[")
|
||||
for i := int64(0); i < len; i++ {
|
||||
el, err := obj.Get(strconv.FormatInt(i, 10))
|
||||
if err == nil {
|
||||
el := obj.Get(strconv.FormatInt(i, 10))
|
||||
if el != nil {
|
||||
ctx.printValue(el, level+1, true)
|
||||
}
|
||||
if i < len-1 {
|
||||
@ -149,7 +162,7 @@ func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
|
||||
}
|
||||
fmt.Fprintln(ctx.w, "{")
|
||||
for i, k := range keys {
|
||||
v, _ := obj.Get(k)
|
||||
v := SafeGet(obj, k)
|
||||
fmt.Fprintf(ctx.w, "%s%s: ", ctx.indent(level+1), k)
|
||||
ctx.printValue(v, level+1, false)
|
||||
if i < len(keys)-1 {
|
||||
@ -163,29 +176,25 @@ func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
|
||||
fmt.Fprintf(ctx.w, "%s}", ctx.indent(level))
|
||||
|
||||
case "Function":
|
||||
// Use toString() to display the argument list if possible.
|
||||
if robj, err := obj.Call("toString"); err != nil {
|
||||
fmt.Fprint(ctx.w, FunctionColor("function()"))
|
||||
} else {
|
||||
desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
|
||||
desc = strings.Replace(desc, " (", "(", 1)
|
||||
fmt.Fprint(ctx.w, FunctionColor("%s", desc))
|
||||
}
|
||||
robj := obj.ToString()
|
||||
desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
|
||||
desc = strings.Replace(desc, " (", "(", 1)
|
||||
fmt.Fprint(ctx.w, FunctionColor("%s", desc))
|
||||
|
||||
case "RegExp":
|
||||
fmt.Fprint(ctx.w, StringColor("%s", toString(obj)))
|
||||
|
||||
default:
|
||||
if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
|
||||
s, _ := obj.Call("toString")
|
||||
fmt.Fprintf(ctx.w, "<%s %s>", obj.Class(), s.String())
|
||||
if level <= maxPrettyPrintLevel {
|
||||
s := obj.ToString().String()
|
||||
fmt.Fprintf(ctx.w, "<%s %s>", obj.ClassName(), s)
|
||||
} else {
|
||||
fmt.Fprintf(ctx.w, "<%s>", obj.Class())
|
||||
fmt.Fprintf(ctx.w, "<%s>", obj.ClassName())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) fields(obj *otto.Object) []string {
|
||||
func (ctx ppctx) fields(obj *goja.Object) []string {
|
||||
var (
|
||||
vals, methods []string
|
||||
seen = make(map[string]bool)
|
||||
@ -195,11 +204,22 @@ func (ctx ppctx) fields(obj *otto.Object) []string {
|
||||
return
|
||||
}
|
||||
seen[k] = true
|
||||
if v, _ := obj.Get(k); v.IsFunction() {
|
||||
methods = append(methods, k)
|
||||
} else {
|
||||
|
||||
key := SafeGet(obj, k)
|
||||
if key == nil {
|
||||
// The value corresponding to that key could not be found
|
||||
// (typically because it is backed by an RPC call that is
|
||||
// not supported by this instance. Add it to the list of
|
||||
// values so that it appears as `undefined` to the user.
|
||||
vals = append(vals, k)
|
||||
} else {
|
||||
if _, callable := goja.AssertFunction(key); callable {
|
||||
methods = append(methods, k)
|
||||
} else {
|
||||
vals = append(vals, k)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
iterOwnAndConstructorKeys(ctx.vm, obj, add)
|
||||
sort.Strings(vals)
|
||||
@ -207,13 +227,13 @@ func (ctx ppctx) fields(obj *otto.Object) []string {
|
||||
return append(vals, methods...)
|
||||
}
|
||||
|
||||
func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
|
||||
func iterOwnAndConstructorKeys(vm *goja.Runtime, obj *goja.Object, f func(string)) {
|
||||
seen := make(map[string]bool)
|
||||
iterOwnKeys(vm, obj, func(prop string) {
|
||||
seen[prop] = true
|
||||
f(prop)
|
||||
})
|
||||
if cp := constructorPrototype(obj); cp != nil {
|
||||
if cp := constructorPrototype(vm, obj); cp != nil {
|
||||
iterOwnKeys(vm, cp, func(prop string) {
|
||||
if !seen[prop] {
|
||||
f(prop)
|
||||
@ -222,10 +242,17 @@ func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.Object, f func(string))
|
||||
}
|
||||
}
|
||||
|
||||
func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
|
||||
Object, _ := vm.Object("Object")
|
||||
rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
|
||||
gv, _ := rv.Export()
|
||||
func iterOwnKeys(vm *goja.Runtime, obj *goja.Object, f func(string)) {
|
||||
Object := vm.Get("Object").ToObject(vm)
|
||||
getOwnPropertyNames, isFunc := goja.AssertFunction(Object.Get("getOwnPropertyNames"))
|
||||
if !isFunc {
|
||||
panic(vm.ToValue("Object.getOwnPropertyNames isn't a function"))
|
||||
}
|
||||
rv, err := getOwnPropertyNames(goja.Null(), obj)
|
||||
if err != nil {
|
||||
panic(vm.ToValue(fmt.Sprintf("Error getting object properties: %v", err)))
|
||||
}
|
||||
gv := rv.Export()
|
||||
switch gv := gv.(type) {
|
||||
case []interface{}:
|
||||
for _, v := range gv {
|
||||
@ -240,32 +267,35 @@ func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
|
||||
}
|
||||
}
|
||||
|
||||
func (ctx ppctx) isBigNumber(v *otto.Object) bool {
|
||||
func (ctx ppctx) isBigNumber(v *goja.Object) bool {
|
||||
// Handle numbers with custom constructor.
|
||||
if v, _ := v.Get("constructor"); v.Object() != nil {
|
||||
if strings.HasPrefix(toString(v.Object()), "function BigNumber") {
|
||||
if obj := v.Get("constructor").ToObject(ctx.vm); obj != nil {
|
||||
if strings.HasPrefix(toString(obj), "function BigNumber") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// Handle default constructor.
|
||||
BigNumber, _ := ctx.vm.Object("BigNumber.prototype")
|
||||
BigNumber := ctx.vm.Get("BigNumber").ToObject(ctx.vm)
|
||||
if BigNumber == nil {
|
||||
return false
|
||||
}
|
||||
bv, _ := BigNumber.Call("isPrototypeOf", v)
|
||||
b, _ := bv.ToBoolean()
|
||||
return b
|
||||
prototype := BigNumber.Get("prototype").ToObject(ctx.vm)
|
||||
isPrototypeOf, callable := goja.AssertFunction(prototype.Get("isPrototypeOf"))
|
||||
if !callable {
|
||||
return false
|
||||
}
|
||||
bv, _ := isPrototypeOf(prototype, v)
|
||||
return bv.ToBoolean()
|
||||
}
|
||||
|
||||
func toString(obj *otto.Object) string {
|
||||
s, _ := obj.Call("toString")
|
||||
return s.String()
|
||||
func toString(obj *goja.Object) string {
|
||||
return obj.ToString().String()
|
||||
}
|
||||
|
||||
func constructorPrototype(obj *otto.Object) *otto.Object {
|
||||
if v, _ := obj.Get("constructor"); v.Object() != nil {
|
||||
if v, _ = v.Object().Get("prototype"); v.Object() != nil {
|
||||
return v.Object()
|
||||
func constructorPrototype(vm *goja.Runtime, obj *goja.Object) *goja.Object {
|
||||
if v := obj.Get("constructor"); v != nil {
|
||||
if v := v.ToObject(vm).Get("prototype"); v != nil {
|
||||
return v.ToObject(vm)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
Reference in New Issue
Block a user