This repository has been archived by the owner on Apr 28, 2023. It is now read-only.
forked from go-delve/delve
/
rtype.go
666 lines (604 loc) · 16.2 KB
/
rtype.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
// This script checks that the Go runtime hasn't changed in ways that Delve
// doesn't understand. It accomplishes this task by parsing the pkg/proc
// package and extracting rules from all the comments starting with the
// magic string '+rtype'.
//
// COMMAND LINE
//
// go run _scripts/rtype.go (report [output-file]|check)
//
// Invoked with the command 'report' it will extract rules from pkg/proc and
// print them to stdout.
// Invoked with the command 'check' it will actually check that the runtime
// conforms to the rules in pkg/proc.
//
// RTYPE RULES
//
// // +rtype -var V T
//
// checks that variable runtime.V exists and has type T
//
// // +rtype -field S.F T
//
// checks that struct runtime.S has a field called F of type T
//
// const C1 = V // +rtype C2
//
// checks that constant runtime.C2 exists and has value V
//
// case "F": // +rtype -fieldof S T
//
// checks that struct runtime.S has a field called F of type T
//
// v := ... // +rtype T
//
// if v is declared as *proc.Variable it will assume that it has type
// runtime.T and it will then parse the enclosing function, searching for
// all calls to:
// v.loadFieldNamed
// v.fieldVariable
// v.structMember
// and check that type T has the specified fields.
//
// v.loadFieldNamed("F") // +rtype T
// v.loadFieldNamed("F") // +rtype -opt T
//
// checks that field F of the struct type declared for v has type T. Can
// also be used for fieldVariable, structMember and, inside parseG,
// loadInt64Maybe.
// The -opt flag specifies that the field can be missing (but if it exists
// it must have type T).
//
//
// Anywhere a type is required anytype can be used to specify that we don't
// care about its type.
package main
import (
"bytes"
"fmt"
"go/ast"
"go/constant"
"go/printer"
"go/token"
"go/types"
"log"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"golang.org/x/tools/go/packages"
)
const magicCommentPrefix = "+rtype"
var fset = &token.FileSet{}
var checkVarTypeRules = []*checkVarType{}
var checkFieldTypeRules = map[string][]*checkFieldType{}
var checkConstValRules = map[string][]*checkConstVal{}
var showRuleOrigin = false
// rtypeCmnt represents a +rtype comment
type rtypeCmnt struct {
slash token.Pos
txt string
node ast.Node // associated node
toplevel ast.Decl // toplevel declaration that contains the Slash of the comment
stmt ast.Stmt
}
type checkVarType struct {
V, T string // V must have type T
pos token.Pos
}
func (c *checkVarType) String() string {
if showRuleOrigin {
pos := fset.Position(c.pos)
return fmt.Sprintf("var %s %s // %s:%d", c.V, c.T, relative(pos.Filename), pos.Line)
}
return fmt.Sprintf("var %s %s", c.V, c.T)
}
type checkFieldType struct {
S, F, T string // S.F must have type T
opt bool
pos token.Pos
}
func (c *checkFieldType) String() string {
pos := fset.Position(c.pos)
return fmt.Sprintf("field %s.%s %s // %s:%d", c.S, c.F, c.T, relative(pos.Filename), pos.Line)
}
type checkConstVal struct {
C string // const C = V
V constant.Value
pos token.Pos
}
func (c *checkConstVal) String() string {
if showRuleOrigin {
pos := fset.Position(c.pos)
return fmt.Sprintf("const %s = %s // %s:%d", c.C, c.V, relative(pos.Filename), pos.Line)
}
return fmt.Sprintf("const %s = %s", c.C, c.V)
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Wrong number of arguments.\n\trtype (report [output-file]|check)\n")
os.Exit(1)
}
command := os.Args[1]
setup()
switch command {
case "report":
if len(os.Args) > 2 {
fh, err := os.Create(os.Args[2])
if err != nil {
log.Fatalf("error creating output file: %v", err)
}
defer fh.Close()
os.Stdout = fh
}
report()
case "check":
check()
default:
fmt.Fprintf(os.Stderr, "Wrong argument %s\n", command)
os.Exit(1)
}
}
// setup parses the proc package, extracting all +rtype comments and
// converting them into rules.
func setup() {
pkgs, err := packages.Load(&packages.Config{Mode: packages.LoadSyntax, Fset: fset}, "github.com/emad-elsaid/delve/pkg/proc")
if err != nil {
log.Fatalf("could not load proc package: %v", err)
}
for _, file := range pkgs[0].Syntax {
cmntmap := ast.NewCommentMap(fset, file, file.Comments)
rtypeCmnts := getRtypeCmnts(file, cmntmap)
for _, rtcmnt := range rtypeCmnts {
if rtcmnt == nil {
continue
}
process(pkgs[0], rtcmnt, cmntmap, rtypeCmnts)
}
}
}
// getRtypeCmnts returns all +rtype comments inside 'file'. It also
// decorates them with the toplevel declaration that contains them as well
// as the statement they are associated with (where applicable).
func getRtypeCmnts(file *ast.File, cmntmap ast.CommentMap) []*rtypeCmnt {
r := []*rtypeCmnt{}
for n, cmntgrps := range cmntmap {
for _, cmntgrp := range cmntgrps {
if len(cmntgrp.List) == 0 {
continue
}
for _, cmnt := range cmntgrp.List {
txt := cleanupCommentText(cmnt.Text)
if !strings.HasPrefix(txt, magicCommentPrefix) {
continue
}
r = append(r, &rtypeCmnt{slash: cmnt.Slash, txt: txt, node: n})
}
}
}
sort.Slice(r, func(i, j int) bool { return r[i].slash < r[j].slash })
// assign each comment to the toplevel declaration that contains it
for i, j := 0, 0; i < len(r) && j < len(file.Decls); {
decl := file.Decls[j]
if decl.Pos() <= r[i].slash && r[i].slash < decl.End() {
r[i].toplevel = decl
i++
} else {
j++
}
}
// for comments declared inside a function also find the statement that contains them.
for i := range r {
fndecl, ok := r[i].toplevel.(*ast.FuncDecl)
if !ok {
continue
}
var lastStmt ast.Stmt
ast.Inspect(fndecl, func(n ast.Node) bool {
if stmt, _ := n.(ast.Stmt); stmt != nil {
lastStmt = stmt
}
if n == r[i].node {
r[i].stmt = lastStmt
}
return true
})
}
return r
}
func cleanupCommentText(txt string) string {
if strings.HasPrefix(txt, "/*") || strings.HasPrefix(txt, "//") {
txt = txt[2:]
}
return strings.TrimSpace(strings.TrimSuffix(txt, "*/"))
}
// process processes a single +rtype comment, turning it into a rule.
// If the +rtype comment is associated with a *proc.Variable declaration
// then it also checks the containing function for all uses of that
// variable.
func process(pkg *packages.Package, rtcmnt *rtypeCmnt, cmntmap ast.CommentMap, rtcmnts []*rtypeCmnt) {
tinfo := pkg.TypesInfo
fields := strings.Split(rtcmnt.txt, " ")
switch fields[1] {
case "-var":
// -var V T
// requests that variable V is of type T
addCheckVarType(fields[2], fields[3], rtcmnt.slash)
case "-field":
// -field S.F T
// requests that field F of type S is of type T
v := strings.Split(fields[2], ".")
addCheckFieldType(v[0], v[1], fields[3], false, rtcmnt.slash)
default:
ok := false
if ident := isProcVariableDecl(rtcmnt.stmt, tinfo); ident != nil {
if len(fields) == 2 {
processProcVariableUses(rtcmnt.toplevel, tinfo, ident, cmntmap, rtcmnts, fields[1])
ok = true
} else if len(fields) == 3 && fields[1] == "-opt" {
processProcVariableUses(rtcmnt.toplevel, tinfo, ident, cmntmap, rtcmnts, fields[2])
ok = true
}
} else if ident := isConstDecl(rtcmnt.toplevel, rtcmnt.node); len(fields) == 2 && ident != nil {
addCheckConstVal(fields[1], constValue(tinfo.Defs[ident]), rtcmnt.slash)
ok = true
} else if F := isStringCaseClause(rtcmnt.stmt); F != "" && len(fields) == 4 && fields[1] == "-fieldof" {
addCheckFieldType(fields[2], F, fields[3], false, rtcmnt.slash)
ok = true
}
if !ok {
pos := fset.Position(rtcmnt.slash)
log.Fatalf("%s:%d: unrecognized +rtype comment\n", pos.Filename, pos.Line)
}
}
}
// isProcVariableDecl returns true if stmt is a declaration of a
// *proc.Variable variable.
func isProcVariableDecl(stmt ast.Stmt, tinfo *types.Info) *ast.Ident {
ass, _ := stmt.(*ast.AssignStmt)
if ass == nil {
return nil
}
if len(ass.Lhs) == 0 {
return nil
}
ident, _ := ass.Lhs[0].(*ast.Ident)
if ident == nil {
return nil
}
var typ types.Type
if def := tinfo.Defs[ident]; def != nil {
typ = def.Type()
}
if tv, ok := tinfo.Types[ident]; ok {
typ = tv.Type
}
if typ == nil {
return nil
}
if typ == nil || typ.String() != "*github.com/emad-elsaid/delve/pkg/proc.Variable" {
return nil
}
return ident
}
func isConstDecl(toplevel ast.Decl, node ast.Node) *ast.Ident {
gendecl, _ := toplevel.(*ast.GenDecl)
if gendecl == nil {
return nil
}
if gendecl.Tok != token.CONST {
return nil
}
valspec, _ := node.(*ast.ValueSpec)
if valspec == nil {
return nil
}
if len(valspec.Names) != 1 {
return nil
}
return valspec.Names[0]
}
func isStringCaseClause(stmt ast.Stmt) string {
c, _ := stmt.(*ast.CaseClause)
if c == nil {
return ""
}
if len(c.List) != 1 {
return ""
}
lit := c.List[0].(*ast.BasicLit)
if lit == nil {
return ""
}
if lit.Kind != token.STRING {
return ""
}
r, _ := strconv.Unquote(lit.Value)
return r
}
// processProcVariableUses scans the body of the function declaration 'decl'
// looking for uses of 'procVarIdent' which is assumed to be an identifier
// for a *proc.Variable variable.
func processProcVariableUses(decl ast.Node, tinfo *types.Info, procVarIdent *ast.Ident, cmntmap ast.CommentMap, rtcmnts []*rtypeCmnt, S string) {
if len(S) > 0 && S[0] == '*' {
S = S[1:]
}
isParseG := false
if fndecl, _ := decl.(*ast.FuncDecl); fndecl != nil {
if fndecl.Name.Name == "parseG" {
if procVarIdent.Name == "v" {
isParseG = true
}
}
}
var lastStmt ast.Stmt
ast.Inspect(decl, func(n ast.Node) bool {
if stmt, _ := n.(ast.Stmt); stmt != nil {
lastStmt = stmt
}
fncall, _ := n.(*ast.CallExpr)
if fncall == nil {
return true
}
var methodName string
if isParseG {
if xident, _ := fncall.Fun.(*ast.Ident); xident != nil && xident.Name == "loadInt64Maybe" {
methodName = "loadInt64Maybe"
}
}
if methodName == "" {
sel, _ := fncall.Fun.(*ast.SelectorExpr)
if sel == nil {
return true
}
methodName = sel.Sel.Name
xident, _ := sel.X.(*ast.Ident)
if xident == nil {
return true
}
if xident.Obj != procVarIdent.Obj {
return true
}
}
if len(fncall.Args) < 1 {
return true
}
arg0, _ := fncall.Args[0].(*ast.BasicLit)
if arg0 == nil {
return true
}
if arg0.Kind != token.STRING {
return true
}
switch methodName {
case "loadFieldNamed", "fieldVariable", "loadInt64Maybe", "structMember":
rtcmntIdx := -1
if cmntgrps := cmntmap[lastStmt]; len(cmntgrps) > 0 && len(cmntgrps[0].List) > 0 {
rtcmntIdx = findComment(cmntgrps[0].List[0].Slash, rtcmnts)
}
typ := "anytype"
opt := false
if rtcmntIdx >= 0 {
fields := strings.Split(rtcmnts[rtcmntIdx].txt, " ")
if len(fields) == 2 {
typ = fields[1]
} else if len(fields) == 3 && fields[1] == "-opt" {
opt = true
typ = fields[2]
}
if isProcVariableDecl(lastStmt, tinfo) == nil {
// remove it because we have already processed it
rtcmnts[rtcmntIdx] = nil
}
}
F, _ := strconv.Unquote(arg0.Value)
addCheckFieldType(S, F, typ, opt, fncall.Pos())
//printNode(fset, fncall)
default:
pos := fset.Position(n.Pos())
log.Fatalf("unknown node at %s:%d", pos.Filename, pos.Line)
}
return true
})
}
func findComment(slash token.Pos, rtcmnts []*rtypeCmnt) int {
for i := range rtcmnts {
if rtcmnts[i] != nil && rtcmnts[i].slash == slash {
return i
}
}
return -1
}
func addCheckVarType(V, T string, pos token.Pos) {
checkVarTypeRules = append(checkVarTypeRules, &checkVarType{V, T, pos})
}
func addCheckFieldType(S, F, T string, opt bool, pos token.Pos) {
checkFieldTypeRules[S] = append(checkFieldTypeRules[S], &checkFieldType{S, F, T, opt, pos})
}
func addCheckConstVal(C string, V constant.Value, pos token.Pos) {
checkConstValRules[C] = append(checkConstValRules[C], &checkConstVal{C, V, pos})
}
// report writes a report of all rules derived from the proc package to stdout.
func report() {
for _, rule := range checkVarTypeRules {
fmt.Printf("%s\n\n", rule.String())
}
var Ss []string
for S := range checkFieldTypeRules {
Ss = append(Ss, S)
}
sort.Strings(Ss)
for _, S := range Ss {
rules := checkFieldTypeRules[S]
fmt.Printf("type %s struct {\n", S)
for _, rule := range rules {
fmt.Printf("\t%s %s", rule.F, rule.T)
if rule.opt {
fmt.Printf(" (optional)")
}
pos := fset.Position(rule.pos)
if showRuleOrigin {
fmt.Printf("\t// %s:%d", relative(pos.Filename), pos.Line)
}
fmt.Printf("\n")
}
fmt.Printf("}\n\n")
}
var Cs []string
for C := range checkConstValRules {
Cs = append(Cs, C)
}
sort.Strings(Cs)
for _, C := range Cs {
rules := checkConstValRules[C]
for i, rule := range rules {
if i == 0 {
fmt.Printf("%s\n", rule.String())
} else {
fmt.Printf("or %s\n", rule.String())
}
}
fmt.Printf("\n")
}
}
// check parses the runtime package and checks that all the rules retrieved
// from the 'proc' package pass.
func check() {
pkgs2, err := packages.Load(&packages.Config{Mode: packages.LoadSyntax, Fset: fset}, "runtime")
if err != nil {
log.Fatalf("could not load runtime package: %v", err)
}
allok := true
for _, rule := range checkVarTypeRules {
//TODO: implement
pos := fset.Position(rule.pos)
def := pkgs2[0].Types.Scope().Lookup(rule.V)
if def == nil {
fmt.Fprintf(os.Stderr, "%s:%d: could not find variable %s\n", pos.Filename, pos.Line, rule.V)
allok = false
continue
}
if !matchType(def.Type(), rule.T) {
fmt.Fprintf(os.Stderr, "%s:%d: wrong type for variable %s, expected %s got %s\n", pos.Filename, pos.Line, rule.V, rule.T, typeStr(def.Type()))
allok = false
continue
}
}
var Ss []string
for S := range checkFieldTypeRules {
Ss = append(Ss, S)
}
sort.Strings(Ss)
for _, S := range Ss {
rules := checkFieldTypeRules[S]
pos := fset.Position(rules[0].pos)
def := pkgs2[0].Types.Scope().Lookup(S)
if def == nil {
fmt.Fprintf(os.Stderr, "%s:%d: could not find struct %s\n", pos.Filename, pos.Line, S)
allok = false
continue
}
typ := def.Type()
if typ == nil {
fmt.Fprintf(os.Stderr, "%s:%d: could not find struct %s\n", pos.Filename, pos.Line, S)
allok = false
continue
}
styp, _ := typ.Underlying().(*types.Struct)
if styp == nil {
fmt.Fprintf(os.Stderr, "%s:%d: could not find struct %s\n", pos.Filename, pos.Line, S)
allok = false
continue
}
for _, rule := range rules {
pos := fset.Position(rule.pos)
fieldType := fieldTypeByName(styp, rule.F)
if fieldType == nil {
if rule.opt {
continue
}
fmt.Fprintf(os.Stderr, "%s:%d: could not find field %s.%s\n", pos.Filename, pos.Line, rule.S, rule.F)
allok = false
continue
}
if !matchType(fieldType, rule.T) {
fmt.Fprintf(os.Stderr, "%s:%d: wrong type for field %s.%s, expected %s got %s\n", pos.Filename, pos.Line, rule.S, rule.F, rule.T, typeStr(fieldType))
allok = false
continue
}
}
}
var Cs []string
for C := range checkConstValRules {
Cs = append(Cs, C)
}
sort.Strings(Cs)
for _, C := range Cs {
rules := checkConstValRules[C]
pos := fset.Position(rules[0].pos)
def := pkgs2[0].Types.Scope().Lookup(C)
if def == nil {
fmt.Fprintf(os.Stderr, "%s:%d: could not find constant %s\n", pos.Filename, pos.Line, C)
allok = false
continue
}
val := constValue(def)
found := false
for _, rule := range rules {
if val == rule.V {
found = true
}
}
if !found {
fmt.Fprintf(os.Stderr, "%s:%d: wrong value for constant %s (%s)\n", pos.Filename, pos.Line, C, val.String())
allok = false
continue
}
}
if !allok {
os.Exit(1)
}
}
func fieldTypeByName(typ *types.Struct, name string) types.Type {
for i := 0; i < typ.NumFields(); i++ {
field := typ.Field(i)
if field.Name() == name {
return field.Type()
}
}
return nil
}
func matchType(typ types.Type, T string) bool {
if T == "anytype" {
return true
}
return typeStr(typ) == T
}
func typeStr(typ types.Type) string {
return types.TypeString(typ, func(pkg *types.Package) string {
if pkg.Path() == "runtime" {
return ""
}
return pkg.Path()
})
}
func constValue(obj types.Object) constant.Value {
return obj.(*types.Const).Val()
}
func printNode(fset *token.FileSet, n ast.Node) {
ast.Fprint(os.Stderr, fset, n, nil)
}
func exprToString(t ast.Expr) string {
var buf bytes.Buffer
printer.Fprint(&buf, token.NewFileSet(), t)
return buf.String()
}
func relative(s string) string {
wd, _ := os.Getwd()
r, err := filepath.Rel(wd, s)
if err != nil {
return s
}
return r
}