/
annotator.go
1398 lines (1203 loc) · 33 KB
/
annotator.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package godebug
import (
"fmt"
"go/ast"
"go/token"
"go/types"
"strconv"
"strings"
"github.com/jmigpin/editor/util/goutil"
)
type Annotator struct {
fset *token.FileSet
typesInfo *types.Info
nodeAnnTypes map[ast.Node]AnnotationType
fileIndex int
dopt *AnnSetDebugOpt
debugVarNameIndex int
debugNIndexes int // n indexes were used
testModeMainFunc bool
hasMainFunc bool
simplify bool // document simplifications
pkg *types.Package
ctxData struct {
debugIndex int
visited map[ast.Stmt]struct{}
}
}
func NewAnnotator(fset *token.FileSet, ti *types.Info, dopt *AnnSetDebugOpt) *Annotator {
ann := &Annotator{fset: fset, typesInfo: ti, dopt: dopt}
ann.simplify = true // always true
ann.ctxData.visited = map[ast.Stmt]struct{}{}
ann.nodeAnnTypes = map[ast.Node]AnnotationType{}
ann.pkg = ann.typesPkg()
return ann
}
//----------
func (ann *Annotator) AnnotateAstFile(astFile *ast.File) {
defer func() { // always run, even on error
ann.debugNIndexes = ann.correctDebugIndexes(astFile)
// fix issues like "//go:embed" comments staying in place
//ann.removeInnerFuncComments(astFile) // failing
astFile.Comments = nil // seems to work!
}()
ctx := newCtx(ann)
if err := ann.visFile(ctx, astFile); err != nil {
ann.logf("annotate error: %v", err)
}
ann.addImports(astFile)
}
//----------
func (ann *Annotator) log(args ...any) {
//log.Print(args...)
s := fmt.Sprint(args...)
s = strings.TrimRight(s, "\n") + "\n"
fmt.Print(s)
}
func (ann *Annotator) logf(f string, args ...any) {
ann.log(fmt.Sprintf(f, args...))
}
//----------
//----------
func (ann *Annotator) visFile(ctx *Ctx, file *ast.File) error {
ctx = ctx.withNoAnnotationsUpdated(file)
for _, decl := range file.Decls {
if err := ann.visDecl(ctx, decl); err != nil {
return err
}
}
return nil
}
func (ann *Annotator) visDecl(ctx *Ctx, decl ast.Decl) error {
ctx = ctx.withNoAnnotationsUpdated(decl)
switch t := decl.(type) {
case *ast.BadDecl:
return nil
case *ast.GenDecl:
return ann.visGenDecl(ctx, t)
case *ast.FuncDecl:
return ann.visFuncDecl(ctx, t)
default:
return goutil.TodoErrorType(decl)
}
}
func (ann *Annotator) visStmt(ctx *Ctx, stmt ast.Stmt) error {
if ctx.stmtVisited(stmt) {
return nil
}
ctx.setStmtVisited(stmt, true)
ctx = ctx.withFixedDebugIndex(true) // each stmt uses a fixed index
ctx = ctx.withNoAnnotationsUpdated(stmt)
//----------
switch t := stmt.(type) {
case *ast.AssignStmt:
return ann.visAssignStmt(ctx, t)
case *ast.BadStmt:
return nil
case *ast.BlockStmt:
return ann.visStmts(ctx, &t.List)
case *ast.BranchStmt:
return ann.visBranchStmt(ctx, t)
case *ast.CaseClause:
return ann.visCaseClause(ctx, t)
case *ast.CommClause:
return ann.visCommClause(ctx, t)
case *ast.DeclStmt:
return ann.visDecl(ctx, t.Decl)
case *ast.DeferStmt:
return ann.visAsyncStmt(ctx, &t.Call)
case *ast.EmptyStmt:
return nil
case *ast.ExprStmt:
return ann.visExprStmt(ctx, t)
case *ast.ForStmt:
return ann.visForStmt(ctx, t)
case *ast.GoStmt:
return ann.visAsyncStmt(ctx, &t.Call)
case *ast.IfStmt:
return ann.visIfStmt(ctx, t)
case *ast.IncDecStmt:
return ann.visIncDecStmt(ctx, t)
case *ast.LabeledStmt:
return ann.visLabeledStmt(ctx, t)
case *ast.RangeStmt:
return ann.visRangeStmt(ctx, t)
case *ast.ReturnStmt:
return ann.visReturnStmt(ctx, t)
case *ast.SelectStmt:
return ann.visSelectStmt(ctx, t)
case *ast.SendStmt:
return ann.visSendStmt(ctx, t)
case *ast.SwitchStmt:
return ann.visSwitchStmt(ctx, t)
case *ast.TypeSwitchStmt:
return ann.visTypeSwitchStmt(ctx, t)
default:
return goutil.TodoErrorType(stmt)
}
}
func (ann *Annotator) visExpr(ctx *Ctx, expr0 *ast.Expr) (DebugExpr, error) {
ctx = ctx.withValue(cidnExpr, expr0)
expr := *expr0
switch t := expr.(type) {
case *ast.ArrayType:
return ann.resultDE(ctx, t)
case *ast.BadExpr:
return nil, nil
case *ast.BasicLit:
return ann.visBasicLit(ctx, t)
case *ast.BinaryExpr:
return ann.visBinaryExpr(ctx, t)
case *ast.CallExpr:
return ann.visCallExpr(ctx, t)
case *ast.ChanType:
return ann.resultDE(ctx, t)
case *ast.CompositeLit:
return ann.visCompositeLit(ctx, t)
case *ast.Ellipsis:
return ann.visExpr(ctx, &t.Elt) // TODO: review
case *ast.FuncLit:
return ann.visFuncLit(ctx, t)
case *ast.FuncType:
return ann.visFuncType(ctx, t)
case *ast.Ident:
return ann.visIdent(ctx, t)
case *ast.IndexExpr:
return ann.visIndexExpr(ctx, t)
case *ast.InterfaceType:
return ann.resultDE(ctx, t)
case *ast.KeyValueExpr:
return ann.visKeyValueExpr(ctx, t)
case *ast.MapType:
return ann.resultDE(ctx, t)
case *ast.ParenExpr:
return ann.visParenExprs(ctx, t)
case *ast.SelectorExpr:
return ann.visSelectorExpr(ctx, t)
case *ast.SliceExpr:
return ann.visSliceExpr(ctx, t)
case *ast.StarExpr:
return ann.visStarExpr(ctx, t)
case *ast.StructType:
return ann.resultDE(ctx, t)
case *ast.TypeAssertExpr:
return ann.visTypeAssertExpr(ctx, t)
case *ast.UnaryExpr:
return ann.visUnaryExpr(ctx, t)
default:
return nil, goutil.TodoErrorType(expr)
}
}
func (ann *Annotator) visSpec(ctx *Ctx, spec ast.Spec) error {
// NOTE: a spec can have initial values
switch t := spec.(type) {
case *ast.ImportSpec:
return nil
case *ast.TypeSpec:
return nil
case *ast.ValueSpec:
// inside a func node
if _, _, ok := ctx.value(cidnFuncNode); ok {
de, err := ann.visExprs(ctx, &t.Values, t.Pos())
if err != nil {
return err
}
// TODO: insert after?
ann.insertDebugLineStmt(ctx, de)
return nil
}
return nil
default:
_ = t
return goutil.TodoErrorType(spec)
}
}
//----------
//----------
func (ann *Annotator) visGenDecl(ctx *Ctx, gd *ast.GenDecl) error {
// split into individual decls to be able to insert debug lines
// TODO: can't split CONST
canSplit := gd.Tok == token.VAR
if _, _, ok := ctx.value(cidnFuncNode); ok && canSplit {
for _, spec := range gd.Specs {
gd := &ast.GenDecl{Tok: gd.Tok, Specs: []ast.Spec{spec}}
ds := &ast.DeclStmt{Decl: gd}
ctx.insertStmt(ds)
ctx.setStmtVisited(ds, false)
}
ctx.replaceStmt(&ast.EmptyStmt{})
return nil
}
for i := range gd.Specs {
// TODO: can't visit CONST
canVisit := gd.Tok == token.VAR
if !canVisit {
continue
}
ctx2 := ctx
//if gd.Tok == token.CONST {
// ctx2 = ctx2.withValue(cidnIsConstSpec, gd.Specs[i])
//}
if err := ann.visSpec(ctx2, gd.Specs[i]); err != nil {
return err
}
}
return nil
}
func (ann *Annotator) visFuncDecl(ctx *Ctx, fd *ast.FuncDecl) error {
if fd.Body == nil {
return nil
}
ctx = ctx.withValue(cidnFuncNode, fd) // ex: returnstmt needs this
ctx2 := ctx.withStmts(&fd.Body.List)
if err, ok := ann.insertMainClose(ctx2, fd); ok && err != nil {
return err
}
if name, ok := ann.detectJumps(ctx2, fd); ok {
// insert a not annotated step
s := fmt.Sprintf("TODO: forward jump label detected: %s", name)
de := ann.newDebugCE("INAnn", basicLitStringQ(s, fd.Pos()))
ann.insertDebugLineStmt(ctx2, de)
return nil
}
u := (ast.Expr)(fd.Type)
de, err := ann.visExpr(ctx2, &u)
if err != nil {
return err
}
ann.insertDebugLineStmt(ctx2, de)
return ann.visStmt(ctx, fd.Body)
}
//----------
//----------
func (ann *Annotator) visStmts(ctx *Ctx, stmts *[]ast.Stmt) error {
ctx = ctx.withNoAnnotationsInstance()
ctx = ctx.withFixedDebugIndex(false)
si := newStmtsIter(ctx, stmts)
ctx = ctx.withValue(cidStmtsIter, si)
return si.iterate(func(stmt ast.Stmt) error {
return ann.visStmt(ctx, stmt)
})
}
//----------
func (ann *Annotator) visAssignStmt(ctx *Ctx, as *ast.AssignStmt) error {
// ex: a,b=c,d
// ex:"switch a:=b.(type)"
rhsOnly := false
if ctx.valueMatch2(cidnIsTypeSwitchStmtAssign, as) {
rhsOnly = true
}
if !rhsOnly && ann.simplify {
allowedTok := func() bool {
return as.Tok == token.DEFINE ||
as.Tok == token.ASSIGN
}
allIds := func() bool {
for _, e := range as.Lhs {
if !isIdentsSequence(e) {
return false
}
}
return true
}
rhsOnly = allowedTok() && allIds()
}
lhs := (DebugExpr)(nil)
if !rhsOnly {
ctx2 := ctx.withValue(cidnResNotReplaceable, &as.Lhs)
//ctx2 = ctx2.withValue(cidnResAssignDebugToVar, &as.Lhs) // commented: cannot be used, won't work for all cases
lhs2, err := ann.visExprs(ctx2, &as.Lhs, as.Lhs[0].Pos())
if err != nil {
return err
}
lhs = lhs2
}
ctx3 := ctx
ctx3 = ctx3.withValue(cidnResAssignDebugToVar, &as.Rhs)
rhs, err := ann.visExprs(ctx3, &as.Rhs, as.Rhs[0].Pos())
if err != nil {
return err
}
if rhsOnly {
ann.insertDebugLineStmt(ctx, rhs)
return nil
}
opbl := basicLitInt(int(as.Tok), as.TokPos)
e3 := ann.newDebugCE("IA", lhs, opbl, rhs)
ctx4 := ctx.withValue(cidbInsertStmtAfter, true)
ann.insertDebugLineStmt(ctx4, e3)
return nil
}
func (ann *Annotator) visBranchStmt(ctx *Ctx, bs *ast.BranchStmt) error {
// show step in
de := ann.newDebugISt(bs.Pos())
ann.insertDebugLineStmt(ctx, de)
return nil
}
func (ann *Annotator) visCaseClause(ctx *Ctx, cc *ast.CaseClause) error {
for i := range cc.List {
expr := &cc.List[i]
//// decide what to wrap
//expr2 := bypassParenExpr(*expr)
//wrap := false
//switch expr2.(type) {
//// need to run for each case before actually matching
//case *ast.CallExpr, *ast.BinaryExpr:
// wrap = true
//}
//if !wrap {
// continue
//}
// wrap in funclit
tt, ok := ann.newTType2(*expr)
if ok &&
//!func() bool { _, ok := tt.constValue(); return ok }() &&
!tt.isType() &&
!tt.isBasicInfo(types.IsUntyped) &&
tt.isBasicInfo(types.IsOrdered|
types.IsBoolean|
types.IsInteger|
types.IsUnsigned|
types.IsFloat|
types.IsString|
types.IsComplex) {
typeName := fmt.Sprintf("%s", tt.Type)
fl := newFuncLitRetType(typeName)
rs := &ast.ReturnStmt{Results: []ast.Expr{*expr}}
fl.Body.List = append(fl.Body.List, rs)
if err := ann.visStmt(ctx, fl.Body); err != nil {
return err
}
*expr = &ast.CallExpr{Fun: fl}
}
}
// show debug step entering the clause
de := ann.newDebugISt(cc.Colon)
ctx2 := ctx.withStmts(&cc.Body)
ann.insertDebugLineStmt(ctx2, de)
return ann.visStmts(ctx, &cc.Body)
}
func (ann *Annotator) visCommClause(ctx *Ctx, cc *ast.CommClause) error {
// TODO
//cc.Comm
// show debug step entering the clause
de := ann.newDebugISt(cc.Pos())
ctx2 := ctx.withStmts(&cc.Body)
ann.insertDebugLineStmt(ctx2, de)
return ann.visStmts(ctx, &cc.Body)
}
func (ann *Annotator) visAsyncStmt(ctx *Ctx, ce0 **ast.CallExpr) error {
// used by: ast.DeferStmt and ast.GoStmt
ce := *ce0
// funclit that will run now
runFl := newFuncLit()
retType := &ast.FuncType{Params: &ast.FieldList{}}
runFl.Type.Results.List = []*ast.Field{
{Type: retType},
}
runFlCtx := ctx.withStmts(&runFl.Body.List)
// visit fun
if !isIdentsSequence(ce.Fun) {
de, err := ann.visExpr(runFlCtx, &ce.Fun)
if err != nil {
return err
}
ann.insertDebugLineStmt(runFlCtx, de)
}
// visit args
de, err := ann.visExprs(runFlCtx, &ce.Args, ce.Pos())
if err != nil {
return err
}
if !isNilIdent(de) {
ann.insertDebugLineStmt(runFlCtx, de)
}
// funclit that will run later
asyncFl := newFuncLit()
asyncFlCtx := ctx.withStmts(&asyncFl.Body.List)
rs := &ast.ReturnStmt{Results: []ast.Expr{asyncFl}}
runFlCtx.insertStmt(rs)
es := &ast.ExprStmt{X: ce}
asyncFlCtx.insertStmt(es)
asyncFlCtx.setStmtVisited(es, false)
if err := ann.visStmt(ctx, asyncFl.Body); err != nil {
return err
}
// replace
ce2 := &ast.CallExpr{Fun: runFl}
*ce0 = &ast.CallExpr{Fun: ce2}
return nil
}
func (ann *Annotator) visExprStmt(ctx *Ctx, es *ast.ExprStmt) error {
ctx = ctx.withValue(cidnIsExprStmtExpr, es.X)
de, err := ann.visExpr(ctx, &es.X)
if err != nil {
return err
}
// special case: don't insert after if panic (won't compile)
if ce, ok := bypassParenExpr(es.X).(*ast.CallExpr); ok {
tt, ok := ann.newTType2(ce.Fun)
if ok && tt.isBuiltinWithName("panic") {
as := newAssignToAnons(de)
ctx.insertStmt(as)
return nil
}
}
ctx2 := ctx
if ctx2.valueMatch2(cidnIsTypeSwitchStmtAssign, es) {
// ex: "switch a.(int)"
} else {
ctx = ctx.withValue(cidbInsertStmtAfter, true)
}
ann.insertDebugLineStmt(ctx, de)
return nil
}
func (ann *Annotator) visForStmt(ctx *Ctx, fs *ast.ForStmt) error {
// wrap in blockstmt to have vars valid only inside the stmt
canInit := !ctx.valueMatch2(cidnIsLabeledStmtStmt, fs)
if canInit && fs.Init != nil {
stmt, init := fs, &fs.Init
bs := &ast.BlockStmt{}
bs.List = append(bs.List, *init, stmt)
ctx2 := ctx.withStmts(&bs.List)
if err := ann.visStmt(ctx2, *init); err != nil {
return err
}
*init = nil
ctx.replaceStmt(bs)
}
// wrap in funclit that returns bool
if fs.Cond != nil {
fl := newFuncLitRetBool()
rs := &ast.ReturnStmt{Results: []ast.Expr{fs.Cond}}
fl.Body.List = append(fl.Body.List, rs)
if err := ann.visStmt(ctx, fl.Body); err != nil {
return err
}
fs.Cond = &ast.CallExpr{Fun: fl}
}
// wrap in funclit, there are no new variables
if fs.Post != nil {
fl := newFuncLit()
fl.Body.List = append(fl.Body.List, fs.Post)
if err := ann.visStmt(ctx, fl.Body); err != nil {
return err
}
fs.Post = &ast.ExprStmt{X: &ast.CallExpr{Fun: fl}}
}
return ann.visStmt(ctx, fs.Body)
}
func (ann *Annotator) visIfStmt(ctx *Ctx, is *ast.IfStmt) error {
// wrap in blockstmt to have vars that belong only to the forstmt
if is.Init != nil {
bs := &ast.BlockStmt{}
bs.List = append(bs.List, is.Init, is)
ctx2 := ctx.withStmts(&bs.List)
if err := ann.visStmt(ctx2, is.Init); err != nil {
return err
}
is.Init = nil
ctx.replaceStmt(bs) // replaces is with bs in stmts
}
// wrap in funclit with bool return value
if is.Cond != nil {
fl := newFuncLitRetBool()
rs := &ast.ReturnStmt{Results: []ast.Expr{is.Cond}}
fl.Body.List = append(fl.Body.List, rs)
if err := ann.visStmt(ctx, fl.Body); err != nil {
return err
}
is.Cond = &ast.CallExpr{Fun: fl}
}
if err := ann.visStmt(ctx, is.Body); err != nil {
return err
}
if is.Else != nil {
ctx2 := ctx.withStmt(&is.Else)
return ann.visStmt(ctx2, is.Else)
}
return nil
}
func (ann *Annotator) visIncDecStmt(ctx *Ctx, rs *ast.IncDecStmt) error {
// ex: a++
// ex: *f()++
ctx2 := ctx.withValue(cidnResNotReplaceable, rs.X)
// commented: not showing the value before
//de, err := ann.visExpr(ctx2, &rs.X)
//if err != nil {
// return err
//}
//ann.insertDebugLineStmt(ctx2, de)
result, err := ann.resultDE(ctx2, rs.X)
if err != nil {
return err
}
ctx3 := ctx2.withValue(cidbInsertStmtAfter, true) // TODO: review
ann.insertDebugLineStmt(ctx3, result)
return nil
}
func (ann *Annotator) visLabeledStmt(ctx *Ctx, ls *ast.LabeledStmt) error {
ctx = ctx.withValue(cidnIsLabeledStmtStmt, ls.Stmt)
// these can't detach the label or the program could be altered
// ex: setting labelstmt.stmt as empty will fail to compile continue/break labels ("invalid break label X")
//*ast.ForStmt, // visStmtWithInit, !stepin
//*ast.RangeStmt, // no init, !stepin
//*ast.SwitchStmt, // visStmtWithInit, stepin
//*ast.TypeSwitchStmt, // visStmtWithInit, stepin by assignstmt
//*ast.SelectStmt: // no init, stepin
switch ls.Stmt.(type) {
case *ast.ForStmt,
*ast.RangeStmt,
*ast.SwitchStmt,
*ast.TypeSwitchStmt,
*ast.SelectStmt:
return ann.visStmt(ctx, ls.Stmt)
default:
// detach stmt
ctx2 := ctx.withValue(cidbInsertStmtAfter, true)
ctx2.insertStmt(ls.Stmt)
ctx2.setStmtVisited(ls.Stmt, false)
ls.Stmt = &ast.EmptyStmt{}
return nil
}
}
func (ann *Annotator) visRangeStmt(ctx *Ctx, rs *ast.RangeStmt) error {
// lenght of x
id := &ast.Ident{Name: "len", NamePos: rs.X.Pos()}
ce2 := &ast.CallExpr{Fun: id, Args: []ast.Expr{rs.X}}
de2 := ann.newDebugCE("IVr", ce2)
ann.insertDebugLineStmt(ctx, de2)
// key and value inside the range body
rsBodyCtx := ctx.withStmts(&rs.Body.List)
kv := []DebugExpr{}
if rs.Key != nil {
ctx2 := rsBodyCtx
ctx2 = ctx2.withValue(cidnResNotReplaceable, rs.Key)
de, err := ann.visExpr(ctx2, &rs.Key)
if err != nil {
return err
}
kv = append(kv, de)
}
if rs.Value != nil {
ctx2 := rsBodyCtx
ctx2 = ctx2.withValue(cidnResNotReplaceable, rs.Value)
de, err := ann.visExpr(ctx2, &rs.Value)
if err != nil {
return err
}
kv = append(kv, de)
}
if len(kv) > 0 {
de := ann.newDebugIL(kv...)
ann.insertDebugLineStmt(rsBodyCtx, de)
}
return ann.visStmt(ctx, rs.Body)
}
func (ann *Annotator) visReturnStmt(ctx *Ctx, rs *ast.ReturnStmt) error {
fn, ft, _ := ctx.funcNode()
tt, err := ann.newTType(fn)
if err != nil {
return err
}
if len(rs.Results) == 0 {
// just show debug step
if tt.nResults2(true) == 0 {
de := ann.newDebugISt(rs.Pos())
ann.insertDebugLineStmt(ctx, de)
return nil
}
// naked return, nresults>=1
if err := ann.nameMissingFieldListNames(ft.Results); err != nil {
return err
}
rs.Results = ann.fieldListNames(ft.Results)
} else {
//// TODO:***
//// fix "return nil" has no type
//tes := ann.fieldListTypeExprs(ft.Results)
//if err := ann.setNilsTypes(rs.Results, tes); err != nil {
// return err
//}
}
de, err := ann.visExprs(ctx, &rs.Results, rs.Pos())
if err != nil {
return err
}
ann.insertDebugLineStmt(ctx, de)
return nil
}
func (ann *Annotator) visSelectStmt(ctx *Ctx, ss *ast.SelectStmt) error {
// show debug step entering the switch
de := ann.newDebugISt(ss.Pos())
ann.insertDebugLineStmt(ctx, de)
return ann.visStmt(ctx, ss.Body)
}
func (ann *Annotator) visSendStmt(ctx *Ctx, ss *ast.SendStmt) error {
ch, err := ann.visExpr(ctx, &ss.Chan)
if err != nil {
return err
}
val, err := ann.visExpr(ctx, &ss.Value)
if err != nil {
return err
}
de := ann.newDebugCE("IS", ch, val)
ann.insertDebugLineStmt(ctx, de)
return nil
}
func (ann *Annotator) visSwitchStmt(ctx *Ctx, ss *ast.SwitchStmt) error {
// show debug step entering the switch
if ss.Init == nil && ss.Tag == nil {
de := ann.newDebugISt(ss.Pos())
ann.insertDebugLineStmt(ctx, de)
}
ctx3 := ctx // used in ss.tag
// wrap in blockstmt to have vars valid only inside the stmt
canInit := !ctx.valueMatch2(cidnIsLabeledStmtStmt, ss)
if canInit && ss.Init != nil {
stmt, init := ss, &ss.Init
bs := &ast.BlockStmt{}
bs.List = append(bs.List, *init, stmt)
ctx2 := ctx.withStmts(&bs.List)
if err := ann.visStmt(ctx2, *init); err != nil {
return err
}
*init = nil
ctx.replaceStmt(bs)
ctx3 = ctx2
ctx3.stmtsIter().index++
}
if canInit && ss.Tag != nil {
// TODO: only possible with funclit+returntypes?
de, err := ann.visExpr(ctx3, &ss.Tag)
if err != nil {
return err
}
//ctx2 := ctx.withValue(cidbInsertStmtAfter, true)
ann.insertDebugLineStmt(ctx3, de)
}
return ann.visStmt(ctx, ss.Body)
}
func (ann *Annotator) visTypeSwitchStmt(ctx *Ctx, tss *ast.TypeSwitchStmt) error {
// wrap in blockstmt to have vars valid only inside the stmt
canInit := !ctx.valueMatch2(cidnIsLabeledStmtStmt, tss)
if canInit && tss.Init != nil {
stmt, init := tss, &tss.Init
bs := &ast.BlockStmt{}
bs.List = append(bs.List, *init, stmt)
ctx2 := ctx.withStmts(&bs.List)
if err := ann.visStmt(ctx2, *init); err != nil {
return err
}
*init = nil
ctx.replaceStmt(bs)
}
ctx2 := ctx.withValue(cidnIsTypeSwitchStmtAssign, tss.Assign)
ctx2 = ctx2.withValue(cidnResNotReplaceable, tss.Assign)
if err := ann.visStmt(ctx2, tss.Assign); err != nil {
return err
}
return ann.visStmt(ctx, tss.Body)
}
//----------
//----------
func (ann *Annotator) visExprs(ctx *Ctx, exprs0 *[]ast.Expr, noExprsPos token.Pos) (DebugExpr, error) {
ctx = ctx.withValue(cidnExprs, exprs0)
exprs := *exprs0
// performance: avoid lengthy run times
limit := 30
if l, ok := ctx.integer(cidiSliceExprsLimit); ok {
limit = l
}
// inherit ctxs
cids := []ctxId{
cidnResNotReplaceable,
cidnResAssignDebugToVar,
}
cids2 := ctx.valueMatch3(cids, exprs0)
w := []DebugExpr{}
for i := range exprs {
ctx2 := ctx.withValue2(cids2, exprs[i]) // inherit ctxs
de, err := ann.visExpr(ctx2, &exprs[i])
if err != nil {
return nil, err
}
w = append(w, de)
// simplification/performance/usability: annotated executable becomes unusable if there is no limit. Ex: files with big number of constants will be really slow.
if limit > 0 && i+1 >= limit {
rest := len(exprs) - (i + 1)
if rest > 0 {
s := fmt.Sprintf("(+%v elems)", rest)
de2 := ann.newDebugIVs(s, exprs[0].Pos())
w = append(w, de2)
break
}
}
}
return ann.newDebugILOrNilIdent(noExprsPos, w...), nil
}
//----------
func (ann *Annotator) visBasicLit(ctx *Ctx, bl *ast.BasicLit) (DebugExpr, error) {
return ann.resultDE(ctx, bl)
//return ann.newDebugCE("IVi", t), nil
}
func (ann *Annotator) visBinaryExpr(ctx *Ctx, be *ast.BinaryExpr) (DebugExpr, error) {
switch be.Op {
case token.LAND, token.LOR:
return ann.visBinaryExprAndOr(ctx, be)
default:
return ann.visBinaryExpr2(ctx, be)
}
}
func (ann *Annotator) visBinaryExpr2(ctx *Ctx, be *ast.BinaryExpr) (DebugExpr, error) {
// NOTE: the need for cidnAssignDebugToVar for x and y is because in the case of the assign stmt, a var in x/y might be changed in the lhs, and getting the current value in the inserted line after the assignment will be wrong
ctx2 := ctx.withValue(cidnResAssignDebugToVar, be.X)
x, err := ann.visExpr(ctx2, &be.X)
if err != nil {
return nil, err
}
ctx3 := ctx.withValue(cidnResAssignDebugToVar, be.Y)
y, err := ann.visExpr(ctx3, &be.Y)
if err != nil {
return nil, err
}
//// TODO: cast to the correct type?
// in some cases a cast is needed
// ex: b |= 1<<a, b is byte, 1<<a will be int if assigned to a new var
ctx4 := ctx
ctx4 = ctx4.withValue(cidnResReplaceWithVar, be) // needs casting in some cases
//ctx4 = ctx4.withValue(cidnResNotReplaceable, be) // need to be careful about being able to then not debug the value directly if changed in an assign lhs
//ctx4 = ctx4.withValue(cidnResAssignDebugToVar, be) // must keep result in case of assign lhs
result, err := ann.resultDE(ctx4, be)
if err != nil {
return nil, err
}
opbl := basicLitInt(int(be.Op), be.Pos())
de := ann.newDebugCE("IB", x, opbl, y, result)
return de, nil
}
func (ann *Annotator) visBinaryExprAndOr(ctx *Ctx, be *ast.BinaryExpr) (DebugExpr, error) {
// ex: f1() || f2() // f2 should not be called if f1 is true
// ex: f1() && f2() // f2 should not be called if f1 is false
x, err := ann.visExpr(ctx, &be.X)
if err != nil {
return nil, err
}
// init value var with be.X
value, err := ann.insertAssignToIdent(ctx, be.X)
if err != nil {
return nil, err
}
ctx.replaceExprs(value)
// init y result var (in case be.Y doesn't run)
y, err := ann.insertAssignToIdent(ctx, ann.newDebugIVs("?", be.Y.Pos()))
if err != nil {
return nil, err
}
// build ifstmt to test x result to decide whether to run y
ifs := &ast.IfStmt{If: be.Pos(), Body: &ast.BlockStmt{}}
ifs.Cond = be.X
if be.Op == token.LOR {
// negate
ifs.Cond = &ast.UnaryExpr{Op: token.NOT, X: ifs.Cond}
}
ctx.insertStmt(ifs)
// inside ifstmt: walk be.Y inside ifstmt
ifsBodyCtx := ctx.withStmts(&ifs.Body.List)
y2, err := ann.visExpr(ifsBodyCtx, &be.Y)
if err != nil {
return nil, err
}
// inside ifstmt: assign debug result to y
as2 := newAssignStmtA11(y, y2)
ifsBodyCtx.insertStmt(as2)
// inside ifstmt: assign be.Y to result var
as3 := newAssignStmtA11(value, be.Y)
ifsBodyCtx.insertStmt(as3)
result := ann.newDebugIVi(value)
opbl := basicLitInt(int(be.Op), be.Pos())
de := ann.newDebugCE("IB", x, opbl, y, result)
return de, nil
}
//----------
func (ann *Annotator) visCallExpr(ctx *Ctx, ce *ast.CallExpr) (DebugExpr, error) {
ctx2 := ctx.withValue(cidnNameInsteadOfValue, ce.Fun)
ctx2 = ctx2.withValue(cidnIsCallExprFun, ce.Fun)
fun, err := ann.visExpr(ctx2, &ce.Fun)
if err != nil {
return nil, err
}
args, err := ann.visExprs(ctx, &ce.Args, ce.Pos())
if err != nil {
return nil, err
}
// don't show stepin/result if type casting or calling a builtin
stepIn := true
if ann.simplify {
//u := bypassParenExpr(ce.Fun) // TODO needed?
u := ce.Fun // detects type casts
if tt, ok := ann.newTType2(u); ok {
switch {
case tt.isType():
stepIn = false
if tt.isBasicInfo(types.IsNumeric) {
// show result
} else {
ctx = ctx.withValue(cidnResNil, ce)
}
case tt.isBuiltinWithName("len"):
stepIn = false
case tt.isBuiltinWithName("panic"):
// show step in
case tt.isBuiltin():
stepIn = false
ctx = ctx.withValue(cidnResNil, ce)
}
}
}
// show stepping in (insert before func call)
e4 := ann.newDebugCE("ICe", fun, args)
if stepIn {
u, err := ann.insertAssignToIdent(ctx, e4) // avoid double call
if err != nil {