pretty.go 7.66 KB
Newer Older
1
// Copyright 2016 The go-ethereum Authors
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
// This file is part of the go-ethereum library.
//
// The go-ethereum library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.

package jsre

import (
	"fmt"
21
	"io"
22
	"reflect"
23 24 25 26
	"sort"
	"strconv"
	"strings"

27
	"github.com/dop251/goja"
28 29 30 31 32 33 34 35 36
	"github.com/fatih/color"
)

const (
	maxPrettyPrintLevel = 3
	indentString        = "  "
)

var (
37 38 39 40
	FunctionColor = color.New(color.FgMagenta).SprintfFunc()
	SpecialColor  = color.New(color.Bold).SprintfFunc()
	NumberColor   = color.New(color.FgRed).SprintfFunc()
	StringColor   = color.New(color.FgGreen).SprintfFunc()
41
	ErrorColor    = color.New(color.FgHiRed).SprintfFunc()
42 43 44 45 46 47 48 49 50 51 52 53 54 55
)

// these fields are hidden when printing objects.
var boringKeys = map[string]bool{
	"valueOf":              true,
	"toString":             true,
	"toLocaleString":       true,
	"hasOwnProperty":       true,
	"isPrototypeOf":        true,
	"propertyIsEnumerable": true,
	"constructor":          true,
}

// prettyPrint writes value to standard output.
56
func prettyPrint(vm *goja.Runtime, value goja.Value, w io.Writer) {
57
	ppctx{vm: vm, w: w}.printValue(value, 0, false)
58 59
}

60
// prettyError writes err to standard output.
61
func prettyError(vm *goja.Runtime, err error, w io.Writer) {
62
	failure := err.Error()
63 64
	if gojaErr, ok := err.(*goja.Exception); ok {
		failure = gojaErr.String()
65 66 67 68
	}
	fmt.Fprint(w, ErrorColor("%s", failure))
}

69 70 71
func (re *JSRE) prettyPrintJS(call goja.FunctionCall) goja.Value {
	for _, v := range call.Arguments {
		prettyPrint(re.vm, v, re.output)
72
		fmt.Fprintln(re.output)
73
	}
74
	return goja.Undefined()
75 76
}

77
type ppctx struct {
78
	vm *goja.Runtime
79 80
	w  io.Writer
}
81 82 83 84 85

func (ctx ppctx) indent(level int) string {
	return strings.Repeat(indentString, level)
}

86 87 88 89 90 91
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()
92
	switch {
93 94 95 96 97 98
	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()))
99
	default:
100 101 102 103 104
		if obj, ok := v.(*goja.Object); ok {
			ctx.printObject(obj, level, inArray)
		} else {
			fmt.Fprintf(ctx.w, "<unprintable %T>", v)
		}
105 106 107
	}
}

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
// 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() {
124
	case "Array", "GoArray":
125 126
		lv := obj.Get("length")
		len := lv.ToInteger()
127
		if len == 0 {
128
			fmt.Fprintf(ctx.w, "[]")
129 130 131
			return
		}
		if level > maxPrettyPrintLevel {
132
			fmt.Fprint(ctx.w, "[...]")
133 134
			return
		}
135
		fmt.Fprint(ctx.w, "[")
136
		for i := int64(0); i < len; i++ {
137 138
			el := obj.Get(strconv.FormatInt(i, 10))
			if el != nil {
139
				ctx.printValue(el, level+1, true)
140 141
			}
			if i < len-1 {
142
				fmt.Fprintf(ctx.w, ", ")
143 144
			}
		}
145
		fmt.Fprint(ctx.w, "]")
146 147 148 149

	case "Object":
		// Print values from bignumber.js as regular numbers.
		if ctx.isBigNumber(obj) {
150
			fmt.Fprint(ctx.w, NumberColor("%s", toString(obj)))
151 152 153 154 155
			return
		}
		// Otherwise, print all fields indented, but stop if we're too deep.
		keys := ctx.fields(obj)
		if len(keys) == 0 {
156
			fmt.Fprint(ctx.w, "{}")
157 158 159
			return
		}
		if level > maxPrettyPrintLevel {
160
			fmt.Fprint(ctx.w, "{...}")
161 162
			return
		}
163
		fmt.Fprintln(ctx.w, "{")
164
		for i, k := range keys {
165
			v := SafeGet(obj, k)
166
			fmt.Fprintf(ctx.w, "%s%s: ", ctx.indent(level+1), k)
167
			ctx.printValue(v, level+1, false)
168
			if i < len(keys)-1 {
169
				fmt.Fprintf(ctx.w, ",")
170
			}
171
			fmt.Fprintln(ctx.w)
172
		}
173 174 175
		if inArray {
			level--
		}
176
		fmt.Fprintf(ctx.w, "%s}", ctx.indent(level))
177 178

	case "Function":
179 180 181 182
		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))
183 184

	case "RegExp":
185
		fmt.Fprint(ctx.w, StringColor("%s", toString(obj)))
186 187

	default:
188 189 190
		if level <= maxPrettyPrintLevel {
			s := obj.ToString().String()
			fmt.Fprintf(ctx.w, "<%s %s>", obj.ClassName(), s)
191
		} else {
192
			fmt.Fprintf(ctx.w, "<%s>", obj.ClassName())
193 194 195 196
		}
	}
}

197
func (ctx ppctx) fields(obj *goja.Object) []string {
198 199 200 201 202
	var (
		vals, methods []string
		seen          = make(map[string]bool)
	)
	add := func(k string) {
203
		if seen[k] || boringKeys[k] || strings.HasPrefix(k, "_") {
204 205 206
			return
		}
		seen[k] = true
207 208 209 210 211 212 213

		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.
214
			vals = append(vals, k)
215 216 217 218 219 220
		} else {
			if _, callable := goja.AssertFunction(key); callable {
				methods = append(methods, k)
			} else {
				vals = append(vals, k)
			}
221
		}
222

223
	}
224
	iterOwnAndConstructorKeys(ctx.vm, obj, add)
225 226 227 228 229
	sort.Strings(vals)
	sort.Strings(methods)
	return append(vals, methods...)
}

230
func iterOwnAndConstructorKeys(vm *goja.Runtime, obj *goja.Object, f func(string)) {
231 232 233 234 235
	seen := make(map[string]bool)
	iterOwnKeys(vm, obj, func(prop string) {
		seen[prop] = true
		f(prop)
	})
236
	if cp := constructorPrototype(vm, obj); cp != nil {
237 238 239 240 241 242 243 244
		iterOwnKeys(vm, cp, func(prop string) {
			if !seen[prop] {
				f(prop)
			}
		})
	}
}

245 246 247 248 249 250 251 252 253 254 255
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()
256 257 258 259 260 261 262 263 264 265 266
	switch gv := gv.(type) {
	case []interface{}:
		for _, v := range gv {
			f(v.(string))
		}
	case []string:
		for _, v := range gv {
			f(v)
		}
	default:
		panic(fmt.Errorf("Object.getOwnPropertyNames returned unexpected type %T", gv))
267 268 269
	}
}

270
func (ctx ppctx) isBigNumber(v *goja.Object) bool {
271
	// Handle numbers with custom constructor.
272 273
	if obj := v.Get("constructor").ToObject(ctx.vm); obj != nil {
		if strings.HasPrefix(toString(obj), "function BigNumber") {
274 275 276 277
			return true
		}
	}
	// Handle default constructor.
278
	BigNumber := ctx.vm.Get("BigNumber").ToObject(ctx.vm)
279 280
	if BigNumber == nil {
		return false
281
	}
282 283 284 285 286 287 288
	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()
289 290
}

291 292
func toString(obj *goja.Object) string {
	return obj.ToString().String()
293 294
}

295 296 297 298
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)
299 300 301 302
		}
	}
	return nil
}