pretty.go 7 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 23 24 25 26 27 28 29 30 31 32 33 34 35
	"sort"
	"strconv"
	"strings"

	"github.com/fatih/color"
	"github.com/robertkrimen/otto"
)

const (
	maxPrettyPrintLevel = 3
	indentString        = "  "
)

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

// 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.
55 56
func prettyPrint(vm *otto.Otto, value otto.Value, w io.Writer) {
	ppctx{vm: vm, w: w}.printValue(value, 0, false)
57 58
}

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
// prettyError writes err to standard output.
func prettyError(vm *otto.Otto, err error, w io.Writer) {
	failure := err.Error()
	if ottoErr, ok := err.(*otto.Error); ok {
		failure = ottoErr.String()
	}
	fmt.Fprint(w, ErrorColor("%s", failure))
}

// jsErrorString adds a backtrace to errors generated by otto.
func jsErrorString(err error) string {
	if ottoErr, ok := err.(*otto.Error); ok {
		return ottoErr.String()
	}
	return err.Error()
}

76
func (re *JSRE) prettyPrintJS(call otto.FunctionCall) otto.Value {
77
	for _, v := range call.ArgumentList {
78 79
		prettyPrint(call.Otto, v, re.output)
		fmt.Fprintln(re.output)
80 81 82 83
	}
	return otto.UndefinedValue()
}

84 85 86 87
type ppctx struct {
	vm *otto.Otto
	w  io.Writer
}
88 89 90 91 92

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

93
func (ctx ppctx) printValue(v otto.Value, level int, inArray bool) {
94 95
	switch {
	case v.IsObject():
96
		ctx.printObject(v.Object(), level, inArray)
97
	case v.IsNull():
98
		fmt.Fprint(ctx.w, SpecialColor("null"))
99
	case v.IsUndefined():
100
		fmt.Fprint(ctx.w, SpecialColor("undefined"))
101 102
	case v.IsString():
		s, _ := v.ToString()
103
		fmt.Fprint(ctx.w, StringColor("%q", s))
104 105
	case v.IsBoolean():
		b, _ := v.ToBoolean()
106
		fmt.Fprint(ctx.w, SpecialColor("%t", b))
107
	case v.IsNaN():
108
		fmt.Fprint(ctx.w, NumberColor("NaN"))
109 110
	case v.IsNumber():
		s, _ := v.ToString()
111
		fmt.Fprint(ctx.w, NumberColor("%s", s))
112
	default:
113
		fmt.Fprint(ctx.w, "<unprintable>")
114 115 116
	}
}

117
func (ctx ppctx) printObject(obj *otto.Object, level int, inArray bool) {
118
	switch obj.Class() {
119
	case "Array", "GoArray":
120 121 122
		lv, _ := obj.Get("length")
		len, _ := lv.ToInteger()
		if len == 0 {
123
			fmt.Fprintf(ctx.w, "[]")
124 125 126
			return
		}
		if level > maxPrettyPrintLevel {
127
			fmt.Fprint(ctx.w, "[...]")
128 129
			return
		}
130
		fmt.Fprint(ctx.w, "[")
131 132 133
		for i := int64(0); i < len; i++ {
			el, err := obj.Get(strconv.FormatInt(i, 10))
			if err == nil {
134
				ctx.printValue(el, level+1, true)
135 136
			}
			if i < len-1 {
137
				fmt.Fprintf(ctx.w, ", ")
138 139
			}
		}
140
		fmt.Fprint(ctx.w, "]")
141 142 143 144

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

	case "Function":
		// Use toString() to display the argument list if possible.
		if robj, err := obj.Call("toString"); err != nil {
176
			fmt.Fprint(ctx.w, FunctionColor("function()"))
177 178 179
		} else {
			desc := strings.Trim(strings.Split(robj.String(), "{")[0], " \t\n")
			desc = strings.Replace(desc, " (", "(", 1)
180
			fmt.Fprint(ctx.w, FunctionColor("%s", desc))
181 182 183
		}

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

	default:
		if v, _ := obj.Get("toString"); v.IsFunction() && level <= maxPrettyPrintLevel {
			s, _ := obj.Call("toString")
189
			fmt.Fprintf(ctx.w, "<%s %s>", obj.Class(), s.String())
190
		} else {
191
			fmt.Fprintf(ctx.w, "<%s>", obj.Class())
192 193 194 195 196 197 198 199 200 201
		}
	}
}

func (ctx ppctx) fields(obj *otto.Object) []string {
	var (
		vals, methods []string
		seen          = make(map[string]bool)
	)
	add := func(k string) {
202
		if seen[k] || boringKeys[k] || strings.HasPrefix(k, "_") {
203 204 205 206 207 208 209 210 211
			return
		}
		seen[k] = true
		if v, _ := obj.Get(k); v.IsFunction() {
			methods = append(methods, k)
		} else {
			vals = append(vals, k)
		}
	}
212
	iterOwnAndConstructorKeys(ctx.vm, obj, add)
213 214 215 216 217
	sort.Strings(vals)
	sort.Strings(methods)
	return append(vals, methods...)
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
func iterOwnAndConstructorKeys(vm *otto.Otto, obj *otto.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 {
		iterOwnKeys(vm, cp, func(prop string) {
			if !seen[prop] {
				f(prop)
			}
		})
	}
}

func iterOwnKeys(vm *otto.Otto, obj *otto.Object, f func(string)) {
	Object, _ := vm.Object("Object")
	rv, _ := Object.Call("getOwnPropertyNames", obj.Value())
236
	gv, _ := rv.Export()
237 238 239 240 241 242 243 244 245 246 247
	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))
248 249 250 251
	}
}

func (ctx ppctx) isBigNumber(v *otto.Object) bool {
252 253 254 255 256 257 258 259 260 261
	// Handle numbers with custom constructor.
	if v, _ := v.Get("constructor"); v.Object() != nil {
		if strings.HasPrefix(toString(v.Object()), "function BigNumber") {
			return true
		}
	}
	// Handle default constructor.
	BigNumber, _ := ctx.vm.Object("BigNumber.prototype")
	if BigNumber == nil {
		return false
262
	}
263 264 265
	bv, _ := BigNumber.Call("isPrototypeOf", v)
	b, _ := bv.ToBoolean()
	return b
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
}

func toString(obj *otto.Object) string {
	s, _ := obj.Call("toString")
	return s.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()
		}
	}
	return nil
}