-
Notifications
You must be signed in to change notification settings - Fork 7
/
repl.go
237 lines (208 loc) · 6.07 KB
/
repl.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
// Example repl is a simple REPL (read-eval-print loop) for GO using
// http://github.com/0xfaded/eval to the heavy lifting to implement
// the eval() part.
//
// The intent here is to show how more to use the library, rather than
// be a full-featured REPL.
//
// A more complete REPL including command history, tab completion and
// readline editing is available as a separate package:
// http://github.com/rocky/go-fish
//
// (rocky) My intent here is also to have something that I can debug in
// the ssa-debugger tortoise/gub.sh. Right now that can't handle the
// unsafe package, pointers, and calls to C code. So that let's out
// go-gnureadline and lineedit.
package main
import (
"bufio"
"fmt"
"go/parser"
"io"
"os"
"reflect"
"strings"
"github.com/0xfaded/eval"
)
// Simple replacement for GNU readline
func readline(prompt string, in *bufio.Reader) (string, error) {
fmt.Printf(prompt)
line, err := in.ReadString('\n')
if err == nil {
line = strings.TrimRight(line, "\r\n")
}
return line, err
}
func intro_text() {
fmt.Printf(`=== A simple Go eval REPL ===
Results of expression are stored in variable slice "results".
The environment is stored in global variable "env".
Enter expressions to be evaluated at the "go>" prompt.
To see all results, type: "results".
To quit, enter: "quit" or Ctrl-D (EOF).
`)
}
// REPL is the a read, eval, and print loop.
func REPL(env *eval.SimpleEnv) {
var err error
// A place to store result values of expressions entered
// interactively
results := make([]interface{}, 0, 10)
env.Vars["results"] = reflect.ValueOf(&results)
exprs := 0
in := bufio.NewReader(os.Stdin)
line, err := readline("go> ", in)
for line != "quit" {
if err != nil {
if err == io.EOF { break }
panic(err)
}
if expr, err := parser.ParseExpr(line); err != nil {
if pair := eval.FormatErrorPos(line, err.Error()); len(pair) == 2 {
fmt.Println(pair[0])
fmt.Println(pair[1])
}
fmt.Printf("parse error: %s\n", err)
} else if cexpr, errs := eval.CheckExpr(expr, env); len(errs) != 0 {
for _, cerr := range errs {
fmt.Printf("check error: %v\n", cerr)
}
} else if vals, err := eval.EvalExpr(cexpr, env); err != nil {
fmt.Printf("panic: %s\n", err)
} else if len(vals) == 0 {
fmt.Printf("Kind=Slice\nvoid\n")
} else if len(vals) == 1 {
value := (vals)[0]
if value.IsValid() {
kind := value.Kind().String()
typ := value.Type().String()
if typ != kind {
fmt.Printf("Kind = %v\n", kind)
fmt.Printf("Type = %v\n", typ)
} else {
fmt.Printf("Kind = Type = %v\n", kind)
}
fmt.Printf("results[%d] = %s\n", exprs, eval.Inspect(value))
exprs += 1
results = append(results, (vals)[0].Interface())
} else {
fmt.Printf("%s\n", value)
}
} else {
fmt.Printf("Kind = Multi-Value\n")
size := len(vals)
for i, v := range vals {
fmt.Printf("%s", eval.Inspect(v))
if i < size-1 { fmt.Printf(", ") }
}
fmt.Printf("\n")
exprs += 1
results = append(results, vals)
}
line, err = readline("go> ", in)
}
}
type XI interface { x() }
type YI interface { y() }
type ZI interface { x() }
type X int
type Y int
type Z int
func (X) x() {}
func (Y) y() {}
func (Z) x() {}
// Create an eval.Env environment to use in evaluation.
// This is a bit ugly here, because we are rolling everything by hand, but
// we want some sort of environment to show off in demo'ing.
// The artifical environment we create here consists of
// fmt:
// fns: fmt.Println, fmt.Printf
// os:
// types: MyInt
// vars: Stdout, Args
// main:
// type Alice
// var alice, aliceptr
//
// (REPL also adds var results to main)
//
// See make_env in github.com/rocky/go-fish for an automated way to
// create more complete environment from a starting import.
func makeBogusEnv() *eval.SimpleEnv {
// A copule of things from the fmt package.
var fmt_funcs map[string] reflect.Value = make(map[string] reflect.Value)
fmt_funcs["Println"] = reflect.ValueOf(fmt.Println)
fmt_funcs["Printf"] = reflect.ValueOf(fmt.Printf)
// A simple type for demo
type MyInt int
// A stripped down package environment. See
// http://github.com/rocky/go-fish and repl_imports.go for a more
// complete environment.
pkgs := map[string] eval.Env {
"fmt": &eval.SimpleEnv {
Vars: make(map[string] reflect.Value),
Consts: make(map[string] reflect.Value),
Funcs: fmt_funcs,
Types : make(map[string] reflect.Type),
Pkgs: nil,
}, "os": &eval.SimpleEnv {
Vars: map[string] reflect.Value {
"Stdout": reflect.ValueOf(&os.Stdout),
"Args" : reflect.ValueOf(&os.Args)},
Consts: make(map[string] reflect.Value),
Funcs: make(map[string] reflect.Value),
Types: map[string] reflect.Type{
"MyInt": reflect.TypeOf(*new(MyInt))},
Pkgs: nil,
},
}
mainEnv := eval.MakeSimpleEnv()
mainEnv.Pkgs = pkgs
// Some "alice" things for testing
type Alice struct {
Bob int
Secret string
}
type R rune
alice := Alice{1, "shhh"}
alicePtr := &alice
foo := 10
ints := []int{1, 2, 3, 4}
add := func(a, b int) int {
return a + b
}
sum := func(as ...int) int {
r := 0
for _, a := range as {
r += a
}
return r
}
mainEnv.Vars["alice"] = reflect.ValueOf(&alice)
mainEnv.Vars["alicePtr"] = reflect.ValueOf(&alicePtr)
mainEnv.Vars["foo"] = reflect.ValueOf(&foo)
mainEnv.Vars["ints"] = reflect.ValueOf(&ints)
mainEnv.Consts["bar"] = reflect.ValueOf(eval.NewConstInt64(5))
mainEnv.Funcs["add"] = reflect.ValueOf(add)
mainEnv.Funcs["sum"] = reflect.ValueOf(sum)
mainEnv.Types["Alice"] = reflect.TypeOf(Alice{})
mainEnv.Types["R"] = reflect.TypeOf(R(0))
var xi *XI = new(XI)
var yi *YI = new(YI)
var zi *ZI = new(ZI)
*xi = XI(X(0))
*yi = YI(Y(0))
*zi = ZI(Z(0))
mainEnv.Types["XI"] = reflect.TypeOf(xi).Elem()
mainEnv.Types["YI"] = reflect.TypeOf(yi).Elem()
mainEnv.Types["ZI"] = reflect.TypeOf(zi).Elem()
mainEnv.Types["X"] = reflect.TypeOf(X(0))
mainEnv.Types["Y"] = reflect.TypeOf(Y(0))
mainEnv.Types["Z"] = reflect.TypeOf(Z(0))
return mainEnv
}
func main() {
env := makeBogusEnv()
intro_text()
REPL(env)
}