forked from bazelbuild/buildtools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwarn_bazel_api.go
1240 lines (1098 loc) · 37.4 KB
/
warn_bazel_api.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
/*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Warnings for incompatible changes in the Bazel API
package warn
import (
"fmt"
"sort"
"strings"
"github.com/bazelbuild/buildtools/build"
"github.com/bazelbuild/buildtools/bzlenv"
"github.com/bazelbuild/buildtools/edit"
"github.com/bazelbuild/buildtools/edit/bzlmod"
"github.com/bazelbuild/buildtools/labels"
"github.com/bazelbuild/buildtools/tables"
)
// Bazel API-specific warnings
// negateExpression returns an expression which is a negation of the input.
// If it's a boolean literal (true or false), just return the opposite literal.
// If it's a unary expression with a unary `not` operator, just remove it.
// Otherwise, insert a `not` operator.
// It's assumed that input is no longer needed as it may be mutated or reused by the function.
func negateExpression(expr build.Expr) build.Expr {
paren, ok := expr.(*build.ParenExpr)
if ok {
newParen := *paren
newParen.X = negateExpression(paren.X)
return &newParen
}
unary, ok := expr.(*build.UnaryExpr)
if ok && unary.Op == "not" {
return unary.X
}
boolean, ok := expr.(*build.Ident)
if ok {
newBoolean := *boolean
if boolean.Name == "True" {
newBoolean.Name = "False"
} else {
newBoolean.Name = "True"
}
return &newBoolean
}
return &build.UnaryExpr{
Op: "not",
X: expr,
}
}
// getParam search for a param with a given name in a given list of function arguments
// and returns it with its index
func getParam(attrs []build.Expr, paramName string) (int, *build.Ident, *build.AssignExpr) {
for i, attr := range attrs {
as, ok := attr.(*build.AssignExpr)
if !ok {
continue
}
name, ok := (as.LHS).(*build.Ident)
if !ok || name.Name != paramName {
continue
}
return i, name, as
}
return -1, nil, nil
}
// isFunctionCall checks whether expr is a call of a function with a given name
func isFunctionCall(expr build.Expr, name string) (*build.CallExpr, bool) {
call, ok := expr.(*build.CallExpr)
if !ok {
return nil, false
}
if ident, ok := call.X.(*build.Ident); ok && ident.Name == name {
return call, true
}
return nil, false
}
// globalVariableUsageCheck checks whether there's a usage of a given global variable in the file.
// It's ok to shadow the name with a local variable and use it.
func globalVariableUsageCheck(f *build.File, global, alternative string) []*LinterFinding {
var findings []*LinterFinding
if f.Type != build.TypeBzl {
return findings
}
var walk func(e *build.Expr, env *bzlenv.Environment)
walk = func(e *build.Expr, env *bzlenv.Environment) {
defer bzlenv.WalkOnceWithEnvironment(*e, env, walk)
ident, ok := (*e).(*build.Ident)
if !ok {
return
}
if ident.Name != global {
return
}
if binding := env.Get(ident.Name); binding != nil {
return
}
// Fix
newIdent := *ident
newIdent.Name = alternative
findings = append(findings, makeLinterFinding(ident,
fmt.Sprintf(`Global variable %q is deprecated in favor of %q. Please rename it.`, global, alternative),
LinterReplacement{e, &newIdent}))
}
var expr build.Expr = f
walk(&expr, bzlenv.NewEnvironment())
return findings
}
// insertLoad returns a *LinterReplacement object representing a replacement required for inserting
// an additional load statement. Returns nil if nothing needs to be changed.
func insertLoad(f *build.File, module string, symbols []string) *LinterReplacement {
// Try to find an existing load statement
for i, stmt := range f.Stmt {
load, ok := stmt.(*build.LoadStmt)
if !ok || load.Module.Value != module {
continue
}
// Modify an existing load statement
newLoad := *load
if !edit.AppendToLoad(&newLoad, symbols, symbols) {
return nil
}
return &LinterReplacement{&(f.Stmt[i]), &newLoad}
}
// Need to insert a new load statement. Can't modify the tree here, so just insert a placeholder
// nil statement and return a replacement for it.
i := 0
for i = range f.Stmt {
stmt := f.Stmt[i]
if _, isComment := stmt.(*build.CommentBlock); isComment {
continue
}
if _, isDocString := stmt.(*build.StringExpr); !isDocString {
// Insert a nil statement here
break
}
}
stmts := append([]build.Expr{}, f.Stmt[:i]...)
stmts = append(stmts, nil)
stmts = append(stmts, f.Stmt[i:]...)
f.Stmt = stmts
return &LinterReplacement{&(f.Stmt[i]), edit.NewLoad(module, symbols, symbols)}
}
// Caches the result of bzlmod.ExtractModuleToApparentNameMapping.
var moduleToApparentRepoName func(string) string
// useApparentRepoNameIfExternal replaces the module name in a load statement with the apparent repository
// name used by the root Bazel module (if any).
func useApparentRepoNameIfExternal(load string, fileReader *FileReader) string {
if !strings.HasPrefix(load, "@") || fileReader == nil {
// Not a load from an external repository or we can't load external files.
return load
}
if moduleToApparentRepoName == nil {
moduleToApparentRepoName = bzlmod.ExtractModuleToApparentNameMapping(func(relPath string) *build.File {
return fileReader.GetFile("", relPath)
})
}
l := labels.Parse(load)
apparentName := moduleToApparentRepoName(l.Repository)
if apparentName == "" {
// The module that hosts the load is not a bazel_dep of the root module. We assume that's
// because it is a WORKSPACE repo, which uses the legacy name.
apparentName = tables.ModuleToLegacyRepoName[l.Repository]
if apparentName == "" {
apparentName = l.Repository
}
}
l.Repository = apparentName
return l.Format()
}
func notLoadedFunctionUsageCheckInternal(expr *build.Expr, env *bzlenv.Environment, globals []string, loadFrom string, fileReader *FileReader) ([]string, []*LinterFinding) {
var loads []string
var findings []*LinterFinding
call, ok := (*expr).(*build.CallExpr)
if !ok {
return loads, findings
}
var name string
var replacements []LinterReplacement
switch node := call.X.(type) {
case *build.DotExpr:
// Maybe native.`global`?
ident, ok := node.X.(*build.Ident)
if !ok || ident.Name != "native" {
return loads, findings
}
name = node.Name
// Replace `native.foo()` with `foo()`
newCall := *call
newCall.X = &build.Ident{Name: node.Name}
replacements = append(replacements, LinterReplacement{expr, &newCall})
case *build.Ident:
// Maybe `global`()?
if binding := env.Get(node.Name); binding != nil {
return loads, findings
}
name = node.Name
default:
return loads, findings
}
for _, global := range globals {
if name == global {
loads = append(loads, name)
findings = append(findings,
makeLinterFinding(call.X, fmt.Sprintf(`Function %q is not global anymore and needs to be loaded from %q.`, global, useApparentRepoNameIfExternal(loadFrom, fileReader)), replacements...))
break
}
}
return loads, findings
}
func notLoadedSymbolUsageCheckInternal(expr *build.Expr, env *bzlenv.Environment, globals []string, loadFrom string, fileReader *FileReader) ([]string, []*LinterFinding) {
var loads []string
var findings []*LinterFinding
ident, ok := (*expr).(*build.Ident)
if !ok {
return loads, findings
}
if binding := env.Get(ident.Name); binding != nil {
return loads, findings
}
for _, global := range globals {
if ident.Name == global {
loads = append(loads, ident.Name)
findings = append(findings,
makeLinterFinding(ident, fmt.Sprintf(`Symbol %q is not global anymore and needs to be loaded from %q.`, global, useApparentRepoNameIfExternal(loadFrom, fileReader))))
break
}
}
return loads, findings
}
// notLoadedUsageCheck checks whether there's a usage of a given not imported function or symbol in the file
// and adds a load statement if necessary.
func notLoadedUsageCheck(f *build.File, fileReader *FileReader, functions, symbols []string, loadFrom string) []*LinterFinding {
toLoad := make(map[string]bool)
var findings []*LinterFinding
var walk func(expr *build.Expr, env *bzlenv.Environment)
walk = func(expr *build.Expr, env *bzlenv.Environment) {
defer bzlenv.WalkOnceWithEnvironment(*expr, env, walk)
functionLoads, functionFindings := notLoadedFunctionUsageCheckInternal(expr, env, functions, loadFrom, fileReader)
findings = append(findings, functionFindings...)
for _, load := range functionLoads {
toLoad[load] = true
}
symbolLoads, symbolFindings := notLoadedSymbolUsageCheckInternal(expr, env, symbols, loadFrom, fileReader)
findings = append(findings, symbolFindings...)
for _, load := range symbolLoads {
toLoad[load] = true
}
}
var expr build.Expr = f
walk(&expr, bzlenv.NewEnvironment())
if len(toLoad) == 0 {
return nil
}
loadFrom = useApparentRepoNameIfExternal(loadFrom, fileReader)
loads := []string{}
for l := range toLoad {
loads = append(loads, l)
}
sort.Strings(loads)
replacement := insertLoad(f, loadFrom, loads)
if replacement != nil {
// Add the same replacement to all relevant findings.
for _, f := range findings {
f.Replacement = append(f.Replacement, *replacement)
}
}
return findings
}
// NotLoadedFunctionUsageCheck checks whether there's a usage of a given not imported function in the file
// and adds a load statement if necessary.
func NotLoadedFunctionUsageCheck(f *build.File, fileReader *FileReader, globals []string, loadFrom string) []*LinterFinding {
return notLoadedUsageCheck(f, fileReader, globals, []string{}, loadFrom)
}
// NotLoadedSymbolUsageCheck checks whether there's a usage of a given not imported function in the file
// and adds a load statement if necessary.
func NotLoadedSymbolUsageCheck(f *build.File, fileReader *FileReader, globals []string, loadFrom string) []*LinterFinding {
return notLoadedUsageCheck(f, fileReader, []string{}, globals, loadFrom)
}
// makePositional makes the function argument positional (removes the keyword if it exists)
func makePositional(argument build.Expr) build.Expr {
if binary, ok := argument.(*build.AssignExpr); ok {
return binary.RHS
}
return argument
}
// makeKeyword makes the function argument keyword (adds or edits the keyword name)
func makeKeyword(argument build.Expr, name string) build.Expr {
assign, ok := argument.(*build.AssignExpr)
if !ok {
return &build.AssignExpr{
LHS: &build.Ident{Name: name},
Op: "=",
RHS: argument,
}
}
ident, ok := assign.LHS.(*build.Ident)
if ok && ident.Name == name {
// Nothing to change
return argument
}
// Technically it's possible that the LHS is not an ident, but that is a syntax error anyway.
newAssign := *assign
newAssign.LHS = &build.Ident{Name: name}
return &newAssign
}
func attrConfigurationWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: attr.xxxx(..., cfg = "data", ...) and attr.xxxx(..., cfg = "host", ...)
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "attr" {
return
}
i, _, param := getParam(call.List, "cfg")
if param == nil {
return
}
value, ok := (param.RHS).(*build.StringExpr)
if !ok {
return
}
newCall := *call
switch value.Value {
case "data":
newCall.List = append(newCall.List[:i], newCall.List[i+1:]...)
findings = append(findings,
makeLinterFinding(param, `cfg = "data" for attr definitions has no effect and should be removed.`,
LinterReplacement{expr, &newCall}))
case "host":
{
newCall.List = append([]build.Expr{}, newCall.List...)
newParam := newCall.List[i].Copy().(*build.AssignExpr)
newRHS := newParam.RHS.Copy().(*build.StringExpr)
newRHS.Value = "exec"
newParam.RHS = newRHS
newCall.List[i] = newParam
findings = append(findings,
makeLinterFinding(param, `cfg = "host" for attr definitions should be replaced by cfg = "exec".`,
LinterReplacement{expr, &newCall}))
}
default:
// value not matched.
return
}
})
return findings
}
func depsetItemsWarning(f *build.File) []*LinterFinding {
var findings []*LinterFinding
types := DetectTypes(f)
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
base, ok := call.X.(*build.Ident)
if !ok || base.Name != "depset" {
return
}
if len(call.List) == 0 {
return
}
_, _, param := getParam(call.List, "items")
if param != nil {
findings = append(findings,
makeLinterFinding(param, `Parameter "items" is deprecated, use "direct" and/or "transitive" instead.`))
return
}
if _, ok := call.List[0].(*build.AssignExpr); ok {
return
}
// We have an unnamed first parameter. Check the type.
if types[call.List[0]] == Depset {
findings = append(findings,
makeLinterFinding(call.List[0], `Giving a depset as first unnamed parameter to depset() is deprecated, use the "transitive" parameter instead.`))
}
})
return findings
}
func attrNonEmptyWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: attr.xxxx(..., non_empty = ..., ...)
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "attr" {
return
}
_, name, param := getParam(call.List, "non_empty")
if param == nil {
return
}
// Fix
newName := *name
newName.Name = "allow_empty"
negatedRHS := negateExpression(param.RHS)
findings = append(findings,
makeLinterFinding(param, "non_empty attributes for attr definitions are deprecated in favor of allow_empty.",
LinterReplacement{¶m.LHS, &newName},
LinterReplacement{¶m.RHS, negatedRHS},
))
})
return findings
}
func attrSingleFileWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: attr.xxxx(..., single_file = ..., ...)
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "attr" {
return
}
singleFileIndex, singleFileKw, singleFileParam := getParam(call.List, "single_file")
if singleFileParam == nil {
return
}
// Fix
newCall := *call
newCall.List = append([]build.Expr{}, call.List...)
newSingleFileKw := *singleFileKw
newSingleFileKw.Name = "allow_single_file"
singleFileValue := singleFileParam.RHS
if boolean, ok := singleFileValue.(*build.Ident); ok && boolean.Name == "False" {
// if the value is `False`, just remove the whole parameter
newCall.List = append(newCall.List[:singleFileIndex], newCall.List[singleFileIndex+1:]...)
} else {
// search for `allow_files` parameter in the same attr definition and remove it
allowFileIndex, _, allowFilesParam := getParam(call.List, "allow_files")
if allowFilesParam != nil {
singleFileValue = allowFilesParam.RHS
newCall.List = append(newCall.List[:allowFileIndex], newCall.List[allowFileIndex+1:]...)
if singleFileIndex > allowFileIndex {
singleFileIndex--
}
}
}
findings = append(findings,
makeLinterFinding(singleFileParam, "single_file is deprecated in favor of allow_single_file.",
LinterReplacement{expr, &newCall},
LinterReplacement{&singleFileParam.LHS, &newSingleFileKw},
LinterReplacement{&singleFileParam.RHS, singleFileValue},
))
})
return findings
}
func ctxActionsWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: ctx.xxxx(...)
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "ctx" {
return
}
switch dot.Name {
case "new_file", "experimental_new_directory", "file_action", "action", "empty_action", "template_action":
// fix
default:
return
}
// Fix
newCall := *call
newCall.List = append([]build.Expr{}, call.List...)
newDot := *dot
newCall.X = &newDot
switch dot.Name {
case "new_file":
if len(call.List) > 2 {
// Can't fix automatically because the new API doesn't support the 3 arguments signature
findings = append(findings,
makeLinterFinding(dot, fmt.Sprintf(`"ctx.new_file" is deprecated in favor of "ctx.actions.declare_file".`)))
return
}
newDot.Name = "actions.declare_file"
if len(call.List) == 2 {
// swap arguments:
// ctx.new_file(sibling, name) -> ctx.actions.declare_file(name, sibling=sibling)
newCall.List[0], newCall.List[1] = makePositional(call.List[1]), makeKeyword(call.List[0], "sibling")
}
case "experimental_new_directory":
newDot.Name = "actions.declare_directory"
case "file_action":
newDot.Name = "actions.write"
i, ident, param := getParam(newCall.List, "executable")
if ident != nil {
newIdent := *ident
newIdent.Name = "is_executable"
newParam := *param
newParam.LHS = &newIdent
newCall.List[i] = &newParam
}
case "action":
newDot.Name = "actions.run"
if _, _, command := getParam(call.List, "command"); command != nil {
newDot.Name = "actions.run_shell"
}
case "empty_action":
newDot.Name = "actions.do_nothing"
case "template_action":
newDot.Name = "actions.expand_template"
if i, ident, param := getParam(call.List, "executable"); ident != nil {
newIdent := *ident
newIdent.Name = "is_executable"
newParam := *param
newParam.LHS = &newIdent
newCall.List[i] = &newParam
}
}
findings = append(findings, makeLinterFinding(dot,
fmt.Sprintf(`"ctx.%s" is deprecated in favor of "ctx.%s".`, dot.Name, newDot.Name),
LinterReplacement{expr, &newCall}))
})
return findings
}
func fileTypeWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
var walk func(e *build.Expr, env *bzlenv.Environment)
walk = func(e *build.Expr, env *bzlenv.Environment) {
defer bzlenv.WalkOnceWithEnvironment(*e, env, walk)
call, ok := isFunctionCall(*e, "FileType")
if !ok {
return
}
if binding := env.Get("FileType"); binding == nil {
findings = append(findings,
makeLinterFinding(call, "The FileType function is deprecated."))
}
}
var expr build.Expr = f
walk(&expr, bzlenv.NewEnvironment())
return findings
}
func packageNameWarning(f *build.File) []*LinterFinding {
return globalVariableUsageCheck(f, "PACKAGE_NAME", "native.package_name()")
}
func repositoryNameWarning(f *build.File) []*LinterFinding {
return globalVariableUsageCheck(f, "REPOSITORY_NAME", "native.repository_name()")
}
func outputGroupWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: ctx.attr.xxx.output_group
outputGroup, ok := (*expr).(*build.DotExpr)
if !ok || outputGroup.Name != "output_group" {
return
}
dep, ok := (outputGroup.X).(*build.DotExpr)
if !ok {
return
}
attr, ok := (dep.X).(*build.DotExpr)
if !ok || attr.Name != "attr" {
return
}
ctx, ok := (attr.X).(*build.Ident)
if !ok || ctx.Name != "ctx" {
return
}
// Replace `xxx.output_group` with `xxx[OutputGroupInfo]`
findings = append(findings,
makeLinterFinding(outputGroup,
`"ctx.attr.dep.output_group" is deprecated in favor of "ctx.attr.dep[OutputGroupInfo]".`,
LinterReplacement{expr, &build.IndexExpr{
X: dep,
Y: &build.Ident{Name: "OutputGroupInfo"},
},
}))
})
return findings
}
func nativeGitRepositoryWarning(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{"git_repository", "new_git_repository"}, "@bazel_tools//tools/build_defs/repo:git.bzl")
}
func nativeHTTPArchiveWarning(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{"http_archive"}, "@bazel_tools//tools/build_defs/repo:http.bzl")
}
func nativeAndroidRulesWarning(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, tables.AndroidNativeRules, tables.AndroidLoadPath)
}
// NativeCcRulesWarning produces a warning for missing loads of cc rules
func NativeCcRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.CcLoadPathPrefix+":"+rule+".bzl")
}
}
// NativeCcToolchainRulesWarning produces a warning for missing loads of cc toolchain rules
func NativeCcToolchainRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.CcLoadPathPrefix+"/toolchains:"+rule+".bzl")
}
}
// NativeCcSymbolsWarning produces a warning for missing loads of cc top-level symbols
func NativeCcSymbolsWarning(symbol string, bzlfile string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedSymbolUsageCheck(f, fileReader, []string{symbol}, tables.CcLoadPathPrefix+"/common:"+bzlfile+".bzl")
}
}
// NativeJavaRulesWarning produces a warning for missing loads of java rules
func NativeJavaRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.JavaLoadPathPrefix+":"+rule+".bzl")
}
}
// NativeJavaToolchainRulesWarning produces a warning for missing loads of java toolchain rules
func NativeJavaToolchainRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.JavaLoadPathPrefix+"/toolchains:"+rule+".bzl")
}
}
// NativeJavaSymbolsWarning produces a warning for missing loads of java top-level symbols
func NativeJavaSymbolsWarning(symbol string, bzlfile string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedSymbolUsageCheck(f, fileReader, []string{symbol}, tables.JavaLoadPathPrefix+"/common:"+bzlfile+".bzl")
}
}
func nativePyRulesWarning(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, tables.PyNativeRules, tables.PyLoadPath)
}
// NativeProtoRulesWarning produces a warning for missing loads of proto rules
func NativeProtoRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.ProtoLoadPathPrefix+":"+rule+".bzl")
}
}
func nativeProtoLangToolchainWarning(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{"proto_lang_toolchain"}, tables.ProtoLoadPathPrefix+"/toolchains:proto_lang_toolchain.bzl")
}
func nativeProtoSymbolsWarning(symbol string, bzlfile string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedSymbolUsageCheck(f, fileReader, []string{symbol}, tables.ProtoLoadPathPrefix+"/common:"+bzlfile)
}
}
// NativeShellRulesWarning produces a warning for missing loads of shell rules
func NativeShellRulesWarning(rule string) func(f *build.File, fileReader *FileReader) []*LinterFinding {
return func(f *build.File, fileReader *FileReader) []*LinterFinding {
if f.Type != build.TypeBzl && f.Type != build.TypeBuild {
return nil
}
return NotLoadedFunctionUsageCheck(f, fileReader, []string{rule}, tables.ShellLoadPathPrefix+":"+rule+".bzl")
}
}
func contextArgsAPIWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
types := DetectTypes(f)
build.WalkPointers(f, func(expr *build.Expr, stack []build.Expr) {
// Search for `<ctx.actions.args>.add()` nodes
call, ok := (*expr).(*build.CallExpr)
if !ok {
return
}
dot, ok := call.X.(*build.DotExpr)
if !ok || dot.Name != "add" || types[dot.X] != CtxActionsArgs {
return
}
// If neither before_each nor join_with nor map_fn is specified, the node is ok.
// Otherwise if join_with is specified, use `.add_joined` instead.
// Otherwise use `.add_all` instead.
_, beforeEachKw, beforeEach := getParam(call.List, "before_each")
_, _, joinWith := getParam(call.List, "join_with")
_, mapFnKw, mapFn := getParam(call.List, "map_fn")
if beforeEach == nil && joinWith == nil && mapFn == nil {
// No deprecated API detected
return
}
// Fix
var replacements []LinterReplacement
newDot := *dot
newDot.Name = "add_all"
replacements = append(replacements, LinterReplacement{&call.X, &newDot})
if joinWith != nil {
newDot.Name = "add_joined"
if beforeEach != nil {
// `add_joined` doesn't have a `before_each` parameter, replace it with `format_each`:
// `before_each = foo` -> `format_each = foo + "%s"`
newBeforeEachKw := *beforeEachKw
newBeforeEachKw.Name = "format_each"
replacements = append(replacements, LinterReplacement{&beforeEach.LHS, &newBeforeEachKw})
replacements = append(replacements, LinterReplacement{&beforeEach.RHS, &build.BinaryExpr{
X: beforeEach.RHS,
Op: "+",
Y: &build.StringExpr{Value: "%s"},
}})
}
}
if mapFnKw != nil {
// Replace `map_fn = ...` with `map_each = ...`
newMapFnKw := *mapFnKw
newMapFnKw.Name = "map_each"
replacements = append(replacements, LinterReplacement{&mapFn.LHS, &newMapFnKw})
}
findings = append(findings,
makeLinterFinding(call,
`"ctx.actions.args().add()" for multiple arguments is deprecated in favor of "add_all()" or "add_joined()".`,
replacements...))
})
return findings
}
func attrOutputDefaultWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.Walk(f, func(expr build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: attr.output(..., default = ...)
call, ok := expr.(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok || dot.Name != "output" {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "attr" {
return
}
_, _, param := getParam(call.List, "default")
if param == nil {
return
}
findings = append(findings,
makeLinterFinding(param, `The "default" parameter for attr.output() is deprecated.`))
})
return findings
}
func attrLicenseWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
build.Walk(f, func(expr build.Expr, stack []build.Expr) {
// Find nodes that match the following pattern: attr.license(...)
call, ok := expr.(*build.CallExpr)
if !ok {
return
}
dot, ok := (call.X).(*build.DotExpr)
if !ok || dot.Name != "license" {
return
}
base, ok := dot.X.(*build.Ident)
if !ok || base.Name != "attr" {
return
}
findings = append(findings,
makeLinterFinding(expr, `"attr.license()" is deprecated and shouldn't be used.`))
})
return findings
}
// ruleImplReturnWarning checks whether a rule implementation function returns an old-style struct
func ruleImplReturnWarning(f *build.File) []*LinterFinding {
if f.Type != build.TypeBzl {
return nil
}
var findings []*LinterFinding
// iterate over rules and collect rule implementation function names
implNames := make(map[string]bool)
build.Walk(f, func(expr build.Expr, stack []build.Expr) {
call, ok := isFunctionCall(expr, "rule")
if !ok {
return
}
// Try to get the implementaton parameter either by name or as the first argument
var impl build.Expr
_, _, param := getParam(call.List, "implementation")
if param != nil {
impl = param.RHS
} else if len(call.List) > 0 {
impl = call.List[0]
}
if name, ok := impl.(*build.Ident); ok {
implNames[name.Name] = true
}
})
// iterate over functions
for _, stmt := range f.Stmt {
def, ok := stmt.(*build.DefStmt)
if !ok || !implNames[def.Name] {
// either not a function or not used in the file as a rule implementation function
continue
}
// traverse the function and find all of its return statements
build.Walk(def, func(expr build.Expr, stack []build.Expr) {
ret, ok := expr.(*build.ReturnStmt)
if !ok {
return