-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyzer.go
855 lines (793 loc) · 22.6 KB
/
analyzer.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
package jape
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
"strconv"
"strings"
"sync"
"golang.org/x/tools/go/analysis"
"golang.org/x/tools/go/analysis/passes/ctrlflow"
"golang.org/x/tools/go/analysis/passes/inspect"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/cfg"
)
const Doc = `enforce jape client/server parity
The japecheck analysis reports mismatches between the API endpoints
defined by a server and the methods defined by a client.
`
var Analyzer = &analysis.Analyzer{
Name: "japecheck",
Doc: Doc,
Run: run,
RunDespiteErrors: true,
Requires: []*analysis.Analyzer{
inspect.Analyzer,
ctrlflow.Analyzer,
},
}
var checkTypes bool
var clientPrefix string
var serverPrefix string
func init() {
Analyzer.Flags.BoolVar(&checkTypes, "types", true, "check that request/response types match in client and server")
Analyzer.Flags.StringVar(&clientPrefix, "cprefix", "", "client endpoint URL prefix to trim")
Analyzer.Flags.StringVar(&serverPrefix, "sprefix", "", "server endpoint URL prefix to trim")
}
func isPtr(t types.Type) bool {
_, ok := t.(*types.Pointer)
return ok
}
func evalConstString(expr ast.Expr, info *types.Info) string {
switch v := expr.(type) {
case *ast.BasicLit:
lit, err := strconv.Unquote(v.Value)
if err != nil {
return v.Value
}
return lit
case *ast.BinaryExpr:
if v.Op != token.ADD {
panic(fmt.Sprintf("unhandled op type (%v)", v.Op))
}
return evalConstString(v.X, info) + evalConstString(v.Y, info)
case *ast.CallExpr:
if types.ExprString(v.Fun) == "fmt.Sprintf" {
return evalConstString(v.Args[0], info)
}
return "%s"
case *ast.Ident:
if typ, ok := info.Types[v]; ok && typ.Value != nil {
return constant.StringVal(typ.Value)
}
return "%s"
case *ast.SelectorExpr:
if typ, ok := info.Types[v]; ok && typ.Value != nil {
return constant.StringVal(typ.Value)
}
return "%s"
default:
panic(fmt.Sprintf("unhandled expr type (%T)", expr))
}
}
type serverParam struct {
name string
typ types.Type
}
type serverRoute struct {
method string
path string
pathParams []serverParam
queryParams map[string]types.Type
request types.Type
response types.Type
seen bool
}
func (r serverRoute) String() string { return r.method + " " + r.path }
func (r serverRoute) normalizedRoute() string {
split := strings.Split(r.path, "/")
for i := range split {
if strings.HasPrefix(split[i], ":") || strings.HasPrefix(split[i], "*") {
split[i] = "%s"
}
}
return r.method + " " + strings.Join(split, "/")
}
func gotoDef(id *ast.Ident, pass *analysis.Pass) (*ast.FuncDecl, ast.Node) {
obj := pass.TypesInfo.ObjectOf(id)
for _, file := range pass.Files {
path, _ := astutil.PathEnclosingInterval(file, obj.Pos(), obj.Pos())
if len(path) == 1 {
continue // not the right file
}
for _, n := range path {
if f, ok := n.(*ast.FuncDecl); ok && f.Name.Name == id.Name {
return f, f.Body
}
}
}
return nil, nil
}
func parseServerRoute(kv *ast.KeyValueExpr, pass *analysis.Pass) (*serverRoute, bool) {
typeof := func(e ast.Expr) types.Type { return pass.TypesInfo.TypeOf(e) }
methodPath := strings.Fields(evalConstString(kv.Key, pass.TypesInfo))
if len(methodPath) != 2 {
pass.Report(analysis.Diagnostic{
Pos: kv.Pos(),
Message: fmt.Sprintf("Server defines invalid route: %q", methodPath),
})
return nil, false
}
r := &serverRoute{
method: methodPath[0],
path: strings.TrimPrefix(methodPath[1], serverPrefix),
queryParams: make(map[string]types.Type),
}
// parse path params
for _, param := range strings.Split(r.path, "/") {
if strings.HasPrefix(param, ":") || strings.HasPrefix(param, "*") {
r.pathParams = append(r.pathParams, serverParam{name: param[1:]})
}
}
// lookup funcBody
var funcBody ast.Node
switch v := kv.Value.(type) {
case *ast.FuncLit:
funcBody = v.Body
case *ast.Ident:
_, funcBody = gotoDef(v, pass)
case *ast.SelectorExpr:
_, funcBody = gotoDef(v.Sel, pass)
}
if funcBody == nil {
pass.Report(analysis.Diagnostic{
Pos: kv.Pos(),
Message: "Could not locate handler definition",
})
return nil, false
}
ast.Inspect(funcBody, func(n ast.Node) bool {
if call, ok := n.(*ast.CallExpr); !ok {
return true
} else if sel, ok := call.Fun.(*ast.SelectorExpr); !ok {
return true
} else if typ := typeof(sel.X); typ == nil || typ.String() != "go.sia.tech/jape.Context" {
return true
} else {
switch sel.Sel.Name {
case "Custom":
r.request = typeof(call.Args[0])
r.response = typeof(call.Args[1])
if r.request != types.Typ[types.UntypedNil] && !isPtr(r.request) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: "Request type must be a pointer",
})
return false
}
switch r.method {
case "GET":
if r.request != types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("%v routes should not read a request object", r.method),
})
return false
}
if checkTypes && r.response == types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("%v routes should write a response object", r.method),
})
return false
}
case "POST":
case "PATCH":
if r.request == types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("%v routes should read a request object", r.method),
})
return false
}
case "PUT":
if r.request == types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("%v routes should read a request object", r.method),
})
return false
}
if r.response != types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[1].Pos(),
Message: fmt.Sprintf("%v routes should not write a response object", r.method),
})
return false
}
case "DELETE":
if r.request != types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("%v routes should not read a request object", r.method),
})
return false
}
if r.response != nil {
pass.Report(analysis.Diagnostic{
Pos: call.Args[1].Pos(),
Message: fmt.Sprintf("%v routes should not write a response object", r.method),
})
return false
}
}
case "Decode":
if r.method == "GET" || r.method == "DELETE" {
pass.Report(analysis.Diagnostic{
Pos: call.Pos(),
Message: fmt.Sprintf("%v routes should not read a request object", r.method),
})
return false
}
typ := typeof(call.Args[0])
if !isPtr(typ) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: "Decode called on non-pointer value",
})
return false
}
if checkTypes && r.request != nil && !types.Identical(typ, r.request) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("Decode called on %v, but was previously called on %v", typ, r.request),
})
return false
}
r.request = typ
case "Encode":
if r.method == "PUT" || r.method == "DELETE" {
pass.Report(analysis.Diagnostic{
Pos: call.Pos(),
Message: fmt.Sprintf("%v routes should not write a response object", r.method),
})
return false
}
typ := typeof(call.Args[0])
if checkTypes && r.response != nil && !types.Identical(typ, r.response) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("Encode called on %v, but was previously called on %v", typ, r.response),
})
return false
}
r.response = typ
case "DecodeForm":
name := evalConstString(call.Args[0], pass.TypesInfo)
typ := typeof(call.Args[1])
if prev, ok := r.queryParams[name]; ok && checkTypes && !types.Identical(prev, typ) {
pass.Report(analysis.Diagnostic{
Pos: call.Pos(),
Message: fmt.Sprintf("Form value %q decoded as %v, but was previously decoded as %v", name, typ, prev),
})
return false
}
r.queryParams[name] = typ
case "DecodeParam":
name := evalConstString(call.Args[0], pass.TypesInfo)
typ := typeof(call.Args[1])
var sp *serverParam
for i := range r.pathParams {
if r.pathParams[i].name == name {
sp = &r.pathParams[i]
}
}
if sp == nil {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("DecodeParam called on param (%q) not present in route definition", name),
})
return false
} else if checkTypes && sp.typ != nil && !types.Identical(sp.typ, typ) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[1].Pos(),
Message: fmt.Sprintf("Param %q decoded as %v, but was previously decoded as %v", name, typ, sp.typ),
})
return false
} else if !isPtr(typ) {
pass.Report(analysis.Diagnostic{
Pos: call.Args[1].Pos(),
Message: "DecodeParam called on non-pointer value",
})
return false
}
sp.typ = typ
case "PathParam":
name := evalConstString(call.Args[0], pass.TypesInfo)
typ := types.NewPointer(types.Typ[types.String])
var sp *serverParam
for i := range r.pathParams {
if r.pathParams[i].name == name {
sp = &r.pathParams[i]
}
}
if sp == nil {
pass.Report(analysis.Diagnostic{
Pos: call.Args[0].Pos(),
Message: fmt.Sprintf("PathParam called on param (%q) not present in route definition", name),
})
return false
} else if checkTypes && sp.typ != nil && !types.Identical(sp.typ, typ) {
pass.Report(analysis.Diagnostic{
Pos: call.Pos(),
Message: fmt.Sprintf("Param %q decoded as %v, but was previously decoded as %v", name, typ, sp.typ),
})
return false
}
sp.typ = typ
}
return true
}
})
if r.request == nil {
r.request = types.Typ[types.UntypedNil]
}
if r.response == nil {
r.response = types.Typ[types.UntypedNil]
}
if checkTypes && r.method == "GET" && r.response == types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: funcBody.Pos(),
Message: fmt.Sprintf("%v routes should write a response object", r.method),
})
return nil, false
} else if r.method == "PUT" && r.request == types.Typ[types.UntypedNil] {
pass.Report(analysis.Diagnostic{
Pos: funcBody.Pos(),
Message: fmt.Sprintf("%v routes should read a request object", r.method),
})
return nil, false
}
return r, true
}
func checkSingleResponse(kv *ast.KeyValueExpr, pass *analysis.Pass) {
typeof := func(e ast.Expr) types.Type { return pass.TypesInfo.TypeOf(e) }
isWrite := func(n ast.Node) bool {
if call, ok := n.(*ast.CallExpr); !ok {
return false
} else if sel, ok := call.Fun.(*ast.SelectorExpr); !ok {
return false
} else if typ := typeof(sel.X); typ == nil || typ.String() != "go.sia.tech/jape.Context" {
return false
} else {
m := sel.Sel.Name
return m == "Error" ||
m == "Check" ||
m == "Decode" ||
m == "DecodeParam" ||
m == "DecodeForm" ||
m == "Encode"
}
}
containsWrite := func(n ast.Node) bool {
var found bool
ast.Inspect(n, func(n ast.Node) bool {
if isWrite(n) {
found = true
return false
}
return true
})
return found
}
visited := make(map[*cfg.Block]bool)
var checkBlock func(b *cfg.Block, prevWrite ast.Node)
checkBlock = func(b *cfg.Block, prevWrite ast.Node) {
if visited[b] {
return
}
visited[b] = true
for _, n := range b.Nodes {
if containsWrite(n) {
if prevWrite != nil {
pass.Report(analysis.Diagnostic{
Pos: n.Pos(),
Message: fmt.Sprintf("Handler writes multiple responses (previous write at %v)", pass.Fset.Position(prevWrite.Pos())),
})
return
} else {
prevWrite = n
}
}
}
if len(b.Succs) == 2 && len(b.Nodes) != 0 {
cond := b.Nodes[len(b.Nodes)-1].(ast.Expr)
if !containsWrite(cond) {
checkBlock(b.Succs[0], prevWrite)
checkBlock(b.Succs[1], prevWrite)
return
}
var cmp token.Token
var op token.Token
var numConds int
var checkCond func(ast.Expr) bool
checkCond = func(cond ast.Expr) bool {
if be, ok := cond.(*ast.BinaryExpr); ok {
switch be.Op {
case token.EQL, token.NEQ:
if cmp == 0 {
cmp = be.Op
} else if be.Op != cmp {
return false
}
numConds++
return isWrite(be.X) && typeof(be.Y) == types.Typ[types.UntypedNil]
case token.LAND, token.LOR:
if op == 0 {
op = be.Op
} else if be.Op != op {
return false
}
return checkCond(be.X) && checkCond(be.Y)
}
}
return false
}
if !checkCond(cond) {
pass.Report(analysis.Diagnostic{
Pos: cond.Pos(),
Message: "Weird condition expression; please stick to either (x != nil || y != nil || ...) or (x == nil && y == nil && ...)",
})
return
}
if numConds > 1 && ((cmp == token.EQL && op != token.LAND) || (cmp == token.NEQ && op != token.LOR)) {
pass.Report(analysis.Diagnostic{
Pos: cond.Pos(),
Message: "Condition may write multiple responses",
})
return
}
if cmp == token.NEQ {
checkBlock(b.Succs[0], prevWrite)
checkBlock(b.Succs[1], nil)
} else {
checkBlock(b.Succs[0], nil)
checkBlock(b.Succs[1], prevWrite)
}
} else {
for _, s := range b.Succs {
checkBlock(s, prevWrite)
}
}
}
cfgs := pass.ResultOf[ctrlflow.Analyzer].(*ctrlflow.CFGs)
var g *cfg.CFG
switch v := kv.Value.(type) {
case *ast.FuncLit:
g = cfgs.FuncLit(v)
case *ast.Ident:
if fd, _ := gotoDef(v, pass); fd != nil {
g = cfgs.FuncDecl(fd)
}
case *ast.SelectorExpr:
if fd, _ := gotoDef(v.Sel, pass); fd != nil {
g = cfgs.FuncDecl(fd)
}
}
if g == nil {
pass.Report(analysis.Diagnostic{
Pos: kv.Pos(),
Message: "Could not locate handler function declaration or literal",
})
return
}
for _, b := range g.Blocks {
checkBlock(b, nil)
}
}
type clientRoute struct {
method string
path string
pos token.Pos
callPos token.Pos
pathParams []ast.Expr
queryParams map[string]ast.Expr
request ast.Expr
response ast.Expr
}
func (r clientRoute) String() string { return r.method + " " + r.path }
func (r clientRoute) normalizedRoute() string {
path := r.path
if split := strings.Split(r.path, "?"); len(split) > 1 {
path = split[0]
}
split := strings.Split(path, "/")
for i := range split {
if strings.HasPrefix(split[i], "%") && len(split[i]) > 1 {
split[i] = "%s"
}
}
return r.method + " " + strings.Join(split, "/")
}
func parseClientRoute(call *ast.CallExpr, pass *analysis.Pass) *clientRoute {
sprintfParse := func(r *clientRoute, expr ast.Expr) {
r.callPos = call.Pos()
r.queryParams = make(map[string]ast.Expr)
if call, ok := expr.(*ast.CallExpr); ok {
if sel, ok := call.Fun.(*ast.SelectorExpr); ok && types.ExprString(sel) == "fmt.Sprintf" {
nPath := strings.Count(r.path, "/%")
nForm := strings.Count(r.path, "=%")
if len(call.Args[1:]) != nPath+nForm {
pass.Report(analysis.Diagnostic{
Pos: call.Pos(),
Message: fmt.Sprintf("route contains (%v path + %v form) = %v parameters, but %v arguments are supplied", nPath, nForm, nPath+nForm, len(call.Args[1:])),
})
return
}
var queryParams []string
if i := strings.Index(r.path, "?"); i != -1 {
for _, part := range strings.Split(r.path[i+1:], "&") {
if i := strings.Index(part, "=%"); i == -1 {
continue // hard-coded form value
} else {
queryParams = append(queryParams, part[:i])
}
}
}
for i, arg := range call.Args[1:] {
if i < nPath {
r.pathParams = append(r.pathParams, arg)
} else {
r.queryParams[queryParams[i-nPath]] = arg
}
}
}
}
}
if call.Fun.(*ast.SelectorExpr).Sel.Name == "Custom" {
r := &clientRoute{
method: evalConstString(call.Args[0], pass.TypesInfo),
path: strings.TrimPrefix(evalConstString(call.Args[1], pass.TypesInfo), clientPrefix),
request: call.Args[2],
response: call.Args[3],
}
sprintfParse(r, call.Args[1])
return r
}
r := &clientRoute{
method: call.Fun.(*ast.SelectorExpr).Sel.Name,
path: strings.TrimPrefix(evalConstString(call.Args[0], pass.TypesInfo), clientPrefix),
}
switch r.method {
case "GET":
r.response = call.Args[1]
case "POST":
r.request = call.Args[1]
r.response = call.Args[2]
case "PUT":
r.request = call.Args[1]
case "PATCH":
r.request = call.Args[1]
r.response = call.Args[2]
}
sprintfParse(r, call.Args[0])
return r
}
func definesClient(file *ast.File, pass *analysis.Pass) bool {
found := false
ast.Inspect(file, func(n ast.Node) bool {
if found {
return false
}
call, ok := n.(*ast.CallExpr)
if !ok {
return true
} else if sel, ok := call.Fun.(*ast.SelectorExpr); !ok {
return true
} else if typ, ok := pass.TypesInfo.Types[sel.X]; ok && typ.Type.String() == "go.sia.tech/jape.Client" {
found = true
return false
}
return true
})
return found
}
func definesServer(file *ast.File, pass *analysis.Pass) bool {
found := false
ast.Inspect(file, func(n ast.Node) bool {
if found {
return false
} else if e, ok := n.(ast.Expr); !ok {
return true
} else if typ, ok := pass.TypesInfo.Types[e]; ok && typ.Type.String() == "map[string]go.sia.tech/jape.Handler" {
found = true
return false
}
return true
})
return found
}
var mu sync.Mutex
var routes = make(map[string]*serverRoute)
var clientRoutes []*clientRoute
var finished bool
var clientPass, serverPass *analysis.Pass
func run(pass *analysis.Pass) (interface{}, error) {
var clientFiles, serverFiles []*ast.File
// find client and server definitions
for _, file := range pass.Files {
if definesClient(file, pass) {
mu.Lock()
clientPass = pass
clientFiles = append(clientFiles, file)
mu.Unlock()
}
if definesServer(file, pass) {
mu.Lock()
serverPass = pass
serverFiles = append(serverFiles, file)
mu.Unlock()
}
}
typeof := func(pass *analysis.Pass, n ast.Node) types.Type {
e, ok := n.(ast.Expr)
if !ok {
return nil
}
return pass.TypesInfo.TypeOf(e)
}
// parse server routes
done := false
mu.Lock()
for _, serverFile := range serverFiles {
ast.Inspect(serverFile, func(n ast.Node) bool {
if done {
return false
} else if typ := typeof(serverPass, n); typ == nil || typ.String() != "map[string]go.sia.tech/jape.Handler" {
return true
} else if _, ok := n.(*ast.CompositeLit); !ok {
return true
}
for _, elt := range n.(*ast.CompositeLit).Elts {
r, ok := parseServerRoute(elt.(*ast.KeyValueExpr), pass)
if !ok {
continue
}
routes[r.normalizedRoute()] = r
// check that the handler only writes to the response body once
checkSingleResponse(elt.(*ast.KeyValueExpr), pass)
}
done = true
return false
})
}
mu.Unlock()
// compare to client routes
mu.Lock()
for _, clientFile := range clientFiles {
ast.Inspect(clientFile, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
} else if sel, ok := call.Fun.(*ast.SelectorExpr); !ok {
return true
} else if typ := typeof(clientPass, sel.X); typ == nil || (typ.String() != "go.sia.tech/jape.Client" && typ.String() != "*go.sia.tech/jape.Client") {
return true
} else if m := sel.Sel.Name; m != "GET" && m != "POST" && m != "PUT" && m != "PATCH" && m != "DELETE" && m != "Custom" {
return true
}
cr := parseClientRoute(call, pass)
if cr == nil {
return true
}
cr.pos = n.Pos()
clientRoutes = append(clientRoutes, cr)
return true
})
}
mu.Unlock()
mu.Lock()
if !finished && len(routes) > 0 && len(clientRoutes) > 0 {
finished = true
// compare against server
for _, cr := range clientRoutes {
sr, ok := routes[cr.normalizedRoute()]
if !ok {
pass.Report(analysis.Diagnostic{
Pos: cr.pos,
Message: fmt.Sprintf("Client references route not defined by server: %v", cr),
})
continue
} else if sr.seen {
// TODO: maybe allow this?
pass.Report(analysis.Diagnostic{
Pos: cr.pos,
Message: fmt.Sprintf("Client references %v multiple times", cr),
})
continue
}
sr.seen = true
ptrTo := func(t types.Type) types.Type {
if t == types.Typ[types.UntypedNil] {
return t
}
return types.NewPointer(t)
}
elem := func(t types.Type) types.Type {
if t, ok := t.(*types.Pointer); ok {
return t.Elem()
}
return t
}
if cr.request != nil {
got := typeof(clientPass, cr.request)
want := elem(sr.request)
if checkTypes && !types.Identical(got, want) {
pass.Report(analysis.Diagnostic{
Pos: cr.request.Pos(),
Message: fmt.Sprintf("Client has wrong request type for %v (got %v, should be %v)", sr, got, want),
})
}
}
if cr.response != nil {
got := typeof(clientPass, cr.response)
want := ptrTo(sr.response)
if checkTypes && !types.Identical(got, want) {
pass.Report(analysis.Diagnostic{
Pos: cr.response.Pos(),
Message: fmt.Sprintf("Client has wrong response type for %v (got %v, should be %v)", sr, got, want),
})
}
}
for i := range sr.pathParams {
if i >= len(cr.pathParams) {
// TODO: this should be unreachable (routes[] lookup should fail)
pass.Report(analysis.Diagnostic{
Pos: cr.callPos,
Message: fmt.Sprintf("Client has too few path parameters for %v", sr),
})
continue
}
cp := cr.pathParams[i]
sp := sr.pathParams[i]
got := typeof(clientPass, cp)
want := elem(sp.typ)
if checkTypes && !types.Identical(got, want) {
pass.Report(analysis.Diagnostic{
Pos: cp.Pos(),
Message: fmt.Sprintf("Client has wrong type for path parameter %q (got %v, should be %v)", sp.name, got, want),
})
}
}
for name, arg := range cr.queryParams {
sq, ok := sr.queryParams[name]
if !ok {
pass.Report(analysis.Diagnostic{
Pos: arg.Pos(),
Message: fmt.Sprintf("Client references undefined query parameter %q", name),
})
continue
}
got := typeof(clientPass, arg)
want := elem(sq)
if checkTypes && !types.Identical(got, want) {
pass.Report(analysis.Diagnostic{
Pos: arg.Pos(),
Message: fmt.Sprintf("Client has wrong type for query parameter %q (got %v, should be %v)", name, got, want),
})
}
}
}
for _, sr := range routes {
if !sr.seen {
pass.Report(analysis.Diagnostic{
Message: fmt.Sprintf("Client missing method for %v", sr),
})
}
}
}
mu.Unlock()
return nil, nil
}