-
Notifications
You must be signed in to change notification settings - Fork 19
/
env.go
106 lines (90 loc) · 2.45 KB
/
env.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
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
// Copyright 2019 The Scriggo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package runtime
import (
"context"
"reflect"
"sync"
)
type PrintFunc func(interface{})
// Context represents a context in Show and Text instructions.
type Context byte
// The env type implements the native.Env interface.
type env struct {
ctx context.Context // context.
globals []reflect.Value // global variables.
print PrintFunc // custom print builtin.
typeof TypeOfFunc // typeof function.
done int32
doneChan <-chan struct{}
doneCase reflect.SelectCase
// Only the callPath field can be changed after the vm has been started
// and access to this field must be done with this mutex.
mu sync.Mutex
callPath string // path of the file where the main goroutine is in.
}
func (env *env) CallPath() string {
env.mu.Lock()
callPath := env.callPath
env.mu.Unlock()
return callPath
}
func (env *env) Context() context.Context {
return env.ctx
}
func (env *env) Fatal(v interface{}) {
panic(&fatalError{env: env, msg: v})
}
func (env *env) Print(args ...interface{}) {
for _, arg := range args {
env.doPrint(arg)
}
}
func (env *env) Println(args ...interface{}) {
for i, arg := range args {
if i > 0 {
env.doPrint(" ")
}
env.doPrint(arg)
}
env.doPrint("\n")
}
func (env *env) Stop(err error) {
panic(stopError{err})
}
func (env *env) TypeOf(v reflect.Value) reflect.Type {
return env.typeof(v)
}
func typeOfFunc(v reflect.Value) reflect.Type {
return v.Type()
}
func (env *env) doPrint(arg interface{}) {
if env.print != nil {
env.print(arg)
return
}
r := reflect.ValueOf(arg)
switch r.Kind() {
case reflect.Invalid, reflect.Array, reflect.Func, reflect.Struct:
print(hex(reflect.ValueOf(&arg).Elem().InterfaceData()[1]))
case reflect.Bool:
print(r.Bool())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
print(r.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
print(r.Uint())
case reflect.Float32, reflect.Float64:
print(r.Float())
case reflect.Complex64, reflect.Complex128:
print(r.Complex())
case reflect.Chan, reflect.Map, reflect.UnsafePointer:
print(hex(r.Pointer()))
case reflect.Interface, reflect.Ptr:
print(arg)
case reflect.Slice:
print("[", r.Len(), "/", r.Cap(), "]", hex(r.Pointer()))
case reflect.String:
print(r.String())
}
}