forked from google/go-jsonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugger.go
349 lines (311 loc) · 7.59 KB
/
debugger.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
package jsonnet
import (
"fmt"
"os"
"path/filepath"
"strings"
"github.com/google/go-jsonnet/ast"
"github.com/google/go-jsonnet/toolutils"
)
type Debugger struct {
// VM evaluating the input
vm *VM
// Interpreter built by the evaluation. Required to look up variables and stack traces
interpreter *interpreter
// breakpoints are stored as the result of the .String function of
// *ast.LocationRange to speed up lookup
breakpoints map[string]bool
// The events channel is used to communicate events happening in the VM with the debugger
events chan DebugEvent
// The cont channel is used to pass continuation events from the frontend to the VM
cont chan continuationEvent
// lastEvaluation stores the result of the last evaluated node
lastEvaluation value
// breakOnNode allows the debugger to request continuation until after a
// certain node has been evaluated (step-out)
breakOnNode ast.Node
// singleStep is used to break on every instruction if set to true
singleStep bool
// skip skips all hooks when performing sub-evaluation (to lookup vars)
skip bool
// current keeps track of the node currently being evaluated
current ast.Node
}
// ContinuationEvents are sent by the debugger frontend. Specifying `until`
// results in continuation until the evaluated node matches the argument
type continuationEvent struct {
until *ast.Node
}
type DebugStopReason int
const (
StopReasonStep DebugStopReason = iota
StopReasonBreakpoint
StopReasonException
)
// A DebugEvent is emitted by the hooks to signal certain events happening in the VM. Examples are:
// - Hitting a breakpoint
// - Catching an exception
// - Program termination
type DebugEvent interface {
anEvent()
}
type DebugEventExit struct {
Output string
Error error
}
func (d *DebugEventExit) anEvent() {}
type DebugEventStop struct {
Reason DebugStopReason
Breakpoint string
Current ast.Node
LastEvaluation *string
Error error
// efmt is used to format the error (if any). Built by the vm so we need to
// keep a reference in the event
efmt ErrorFormatter
}
func (d *DebugEventStop) anEvent() {}
func (d *DebugEventStop) ErrorFmt() string {
return d.efmt.Format(d.Error)
}
func MakeDebugger() *Debugger {
d := &Debugger{
events: make(chan DebugEvent, 2048),
cont: make(chan continuationEvent),
}
vm := MakeVM()
vm.EvalHook = EvalHook{
pre: d.preHook,
post: d.postHook,
}
d.vm = vm
d.breakpoints = make(map[string]bool)
return d
}
func traverse(root ast.Node, f func(node *ast.Node) error) error {
if err := f(&root); err != nil {
return fmt.Errorf("pre error: %w", err)
}
children := toolutils.Children(root)
for _, c := range children {
if err := traverse(c, f); err != nil {
return err
}
}
return nil
}
func (d *Debugger) Continue() {
d.cont <- continuationEvent{}
}
func (d *Debugger) ContinueUntilAfter(n ast.Node) {
d.cont <- continuationEvent{
until: &n,
}
}
func (d *Debugger) Step() {
d.singleStep = true
d.Continue()
}
func (d *Debugger) Terminate() {
d.events <- &DebugEventExit{
Error: fmt.Errorf("terminated"),
}
}
func (d *Debugger) postHook(i *interpreter, n ast.Node, v value, err error) {
d.lastEvaluation = v
if d.skip {
return
}
if err != nil {
d.events <- &DebugEventStop{
Current: n,
Reason: StopReasonException,
Error: err,
efmt: d.vm.ErrorFormatter,
}
d.waitForContinuation()
}
if d.breakOnNode == n {
d.breakOnNode = nil
d.singleStep = true
}
}
func (d *Debugger) waitForContinuation() {
c := <-d.cont
if c.until != nil {
d.breakOnNode = *c.until
}
}
func (d *Debugger) preHook(i *interpreter, n ast.Node) {
d.interpreter = i
d.current = n
if d.skip {
return
}
switch n.(type) {
case *ast.LiteralNull, *ast.LiteralNumber, *ast.LiteralString, *ast.LiteralBoolean:
return
}
l := n.Loc()
if l.File == nil {
return
}
vs, err := valueToString(d.interpreter, d.lastEvaluation)
if err != nil {
return
}
if d.singleStep {
d.singleStep = false
d.events <- &DebugEventStop{
Reason: StopReasonStep,
Current: n,
LastEvaluation: &vs,
}
d.waitForContinuation()
return
}
loc := n.Loc()
if loc == nil || loc.File == nil {
// virtual file such as <std>
return
}
if _, ok := d.breakpoints[loc.String()]; ok {
d.events <- &DebugEventStop{
Reason: StopReasonBreakpoint,
Breakpoint: loc.Begin.String(),
Current: n,
LastEvaluation: &vs,
}
d.waitForContinuation()
}
return
}
func (d *Debugger) ActiveBreakpoints() []string {
bps := []string{}
for k := range d.breakpoints {
bps = append(bps, k)
}
return bps
}
func (d *Debugger) BreakpointLocations(file string) ([]*ast.LocationRange, error) {
abs, err := filepath.Abs(file)
if err != nil {
return nil, err
}
raw, err := os.ReadFile(abs)
if err != nil {
return nil, fmt.Errorf("reading file: %w", err)
}
a, err := SnippetToAST(file, string(raw))
if err != nil {
return nil, fmt.Errorf("invalid source file: %w", err)
}
bps := []*ast.LocationRange{}
traverse(a, func(n *ast.Node) error {
if n != nil {
l := (*n).Loc()
if l.File != nil {
bps = append(bps, l)
}
}
return nil
})
return bps, nil
}
func (d *Debugger) SetBreakpoint(file string, line int, column int) (string, error) {
valid, err := d.BreakpointLocations(file)
if err != nil {
return "", fmt.Errorf("getting valid breakpoint locations: %w", err)
}
target := ""
for _, b := range valid {
if b.Begin.Line == line {
if column < 0 {
target = b.String()
break
} else if b.Begin.Column == column {
target = b.String()
break
}
}
}
if target == "" {
return "", fmt.Errorf("breakpoint location invalid")
}
d.breakpoints[target] = true
return target, nil
}
func (d *Debugger) ClearBreakpoints(file string) {
abs, _ := filepath.Abs(file)
for k := range d.breakpoints {
parts := strings.Split(k, ":")
full, err := filepath.Abs(parts[0])
if err == nil && full == abs {
delete(d.breakpoints, k)
}
}
}
func (d *Debugger) LookupValue(val string) (string, error) {
switch val {
case "self":
return valueToString(d.interpreter, d.interpreter.stack.getSelfBinding().self)
case "super":
return valueToString(d.interpreter, d.interpreter.stack.getSelfBinding().super().self)
default:
v := d.interpreter.stack.lookUpVar(ast.Identifier(val))
if v != nil {
if v.content == nil {
d.skip = true
e, err := func() (rv value, err error) { // closure to use defer->recover
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
rv, err = d.interpreter.rawevaluate(v.body, 0)
return
}()
d.skip = false
if err != nil {
return "", err
}
v.content = e
}
return valueToString(d.interpreter, v.content)
}
}
return "", fmt.Errorf("invalid identifier %s", val)
}
func (d *Debugger) ListVars() []ast.Identifier {
if d.interpreter != nil {
return d.interpreter.stack.listVars()
}
return make([]ast.Identifier, 0)
}
func (d *Debugger) Launch(filename, snippet string, jpaths []string) {
jpaths = append(jpaths, filepath.Dir(filename))
d.vm.Importer(&FileImporter{
JPaths: jpaths,
})
go func() {
out, err := d.vm.EvaluateAnonymousSnippet(filename, snippet)
d.events <- &DebugEventExit{
Output: out,
Error: err,
}
}()
}
func (d *Debugger) Events() chan DebugEvent {
return d.events
}
func (d *Debugger) StackTrace() []TraceFrame {
if d.interpreter == nil || d.current == nil {
return nil
}
trace := d.interpreter.getCurrentStackTrace()
for i, t := range trace {
trace[i].Name = t.Loc.FileName // use pseudo file name as name
}
trace[len(trace)-1].Loc = *d.current.Loc()
return trace
}