-
Notifications
You must be signed in to change notification settings - Fork 419
/
rewrite.go
1431 lines (1297 loc) · 38.6 KB
/
rewrite.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 2016 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.
*/
// Rewriting of high-level (not purely syntactic) BUILD constructs.
package build
import (
"path"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/bazelbuild/buildtools/labels"
"github.com/bazelbuild/buildtools/tables"
)
// DisableRewrites disables certain rewrites (for debugging).
var DisableRewrites []string
// disabled reports whether the named rewrite is disabled.
func disabled(name string) bool {
for _, x := range DisableRewrites {
if name == x {
return true
}
}
return false
}
// AllowSort allows sorting of these lists even with sorting otherwise disabled (for debugging).
var AllowSort []string
// allowedSort reports whether sorting is allowed in the named context.
func allowedSort(name string) bool {
for _, x := range AllowSort {
if name == x {
return true
}
}
return false
}
// Rewriter controls the rewrites to be applied.
//
// If non-nil, the rewrites with the specified names will be run. If
// nil, a default set of rewrites will be used that is determined by
// the type (BUILD vs default starlark) of the file being rewritten.
type Rewriter struct {
RewriteSet []string
IsLabelArg map[string]bool
LabelDenyList map[string]bool
IsSortableListArg map[string]bool
SortableDenylist map[string]bool
SortableAllowlist map[string]bool
NamePriority map[string]int
StripLabelLeadingSlashes bool
ShortenAbsoluteLabelsToRelative bool
}
// Rewrite applies rewrites to a file
func Rewrite(f *File) {
var rewriter = &Rewriter{
IsLabelArg: tables.IsLabelArg,
LabelDenyList: tables.LabelDenylist,
IsSortableListArg: tables.IsSortableListArg,
SortableDenylist: tables.SortableDenylist,
SortableAllowlist: tables.SortableAllowlist,
NamePriority: tables.NamePriority,
StripLabelLeadingSlashes: tables.StripLabelLeadingSlashes,
ShortenAbsoluteLabelsToRelative: tables.ShortenAbsoluteLabelsToRelative,
}
rewriter.Rewrite(f)
}
// Rewrite applies the rewrites to a file
func (w *Rewriter) Rewrite(f *File) {
for _, r := range rewrites {
// f.Type&r.scope is a bitwise comparison. Because starlark files result in a scope that will
// not be changed by rewrites, we have included another check looking on the right side.
// If we have an empty rewrite set, we do not want any rewrites to happen.
if (!disabled(r.name) && (f.Type&r.scope != 0) && w.RewriteSet == nil) || (w.RewriteSet != nil && rewriteSetContains(w, r.name)) {
r.fn(f, w)
}
}
}
func rewriteSetContains(w *Rewriter, name string) bool {
for _, value := range w.RewriteSet {
if value == name {
return true
}
}
return false
}
// Each rewrite function can be either applied for BUILD files, other files (such as .bzl),
// or all files.
const (
scopeDefault = TypeDefault | TypeBzl // .bzl and generic Starlark files
scopeBuild = TypeBuild | TypeWorkspace | TypeModule // BUILD, WORKSPACE, and MODULE files
scopeBoth = scopeDefault | scopeBuild
)
// rewrites is the list of all Buildifier rewrites, in the order in which they are applied.
// The order here matters: for example, label canonicalization must happen
// before sorting lists of strings.
var rewrites = []struct {
name string
fn func(*File, *Rewriter)
scope FileType
}{
{"removeParens", removeParens, scopeBuild},
{"callsort", sortCallArgs, scopeBuild},
{"label", fixLabels, scopeBuild},
{"listsort", sortStringLists, scopeBoth},
{"multiplus", fixMultilinePlus, scopeBuild},
{"loadTop", moveLoadOnTop, scopeBoth},
{"sameOriginLoad", compressSameOriginLoads, scopeBoth},
{"sortLoadStatements", sortLoadStatements, scopeBoth},
{"loadsort", sortAllLoadArgs, scopeBoth},
{"useRepoPositionalsSort", sortUseRepoPositionals, TypeModule},
{"formatdocstrings", formatDocstrings, scopeBoth},
{"reorderarguments", reorderArguments, scopeBoth},
{"editoctal", editOctals, scopeBoth},
}
// leaveAlone reports whether any of the nodes on the stack are marked
// with a comment containing "buildifier: leave-alone".
func leaveAlone(stk []Expr, final Expr) bool {
for _, x := range stk {
if leaveAlone1(x) {
return true
}
}
if final != nil && leaveAlone1(final) {
return true
}
return false
}
// hasComment reports whether x is marked with a comment that
// after being converted to lower case, contains the specified text.
func hasComment(x Expr, text string) bool {
if x == nil {
return false
}
for _, com := range x.Comment().Before {
if strings.Contains(strings.ToLower(com.Token), text) {
return true
}
}
for _, com := range x.Comment().After {
if strings.Contains(strings.ToLower(com.Token), text) {
return true
}
}
for _, com := range x.Comment().Suffix {
if strings.Contains(strings.ToLower(com.Token), text) {
return true
}
}
return false
}
// isCommentAnywhere checks whether there's a comment containing the given text
// anywhere in the file.
func isCommentAnywhere(f *File, text string) bool {
commentExists := false
WalkInterruptable(f, func(node Expr, stack []Expr) (err error) {
if hasComment(node, text) {
commentExists = true
return &StopTraversalError{}
}
return nil
})
return commentExists
}
// leaveAlone1 reports whether x is marked with a comment containing
// "buildifier: leave-alone", case-insensitive.
func leaveAlone1(x Expr) bool {
return hasComment(x, "buildifier: leave-alone")
}
// doNotSort reports whether x is marked with a comment containing
// "do not sort", case-insensitive.
func doNotSort(x Expr) bool {
return hasComment(x, "do not sort")
}
// keepSorted reports whether x is marked with a comment containing
// "keep sorted", case-insensitive.
func keepSorted(x Expr) bool {
return hasComment(x, "keep sorted")
}
// fixLabels rewrites labels into a canonical form.
//
// First, it joins labels written as string addition, turning
// "//x" + ":y" (usually split across multiple lines) into "//x:y".
//
// Second, it removes redundant target qualifiers, turning labels like
// "//third_party/m4:m4" into "//third_party/m4" as well as ones like
// "@foo//:foo" into "@foo".
func fixLabels(f *File, w *Rewriter) {
joinLabel := func(p *Expr) {
add, ok := (*p).(*BinaryExpr)
if !ok || add.Op != "+" {
return
}
str1, ok := add.X.(*StringExpr)
if !ok || !strings.HasPrefix(str1.Value, "//") || strings.Contains(str1.Value, " ") {
return
}
str2, ok := add.Y.(*StringExpr)
if !ok || strings.Contains(str2.Value, " ") {
return
}
str1.Value += str2.Value
// Deleting nodes add and str2.
// Merge comments from add, str1, and str2 and save in str1.
com1 := add.Comment()
com2 := str1.Comment()
com3 := str2.Comment()
com1.Before = append(com1.Before, com2.Before...)
com1.Before = append(com1.Before, com3.Before...)
com1.Suffix = append(com1.Suffix, com2.Suffix...)
com1.Suffix = append(com1.Suffix, com3.Suffix...)
*str1.Comment() = *com1
*p = str1
}
labelPrefix := "//"
if w.StripLabelLeadingSlashes {
labelPrefix = ""
}
// labelRE matches label strings, e.g. @r//x/y/z:abc
// where $1 is @r//x/y/z, $2 is @r//, $3 is r, $4 is z, $5 is abc.
labelRE := regexp.MustCompile(`^(((?:@(\w+))?//|` + labelPrefix + `)(?:.+/)?([^:]*))(?::([^:]+))?$`)
shortenLabel := func(v Expr) {
str, ok := v.(*StringExpr)
if !ok {
return
}
if w.StripLabelLeadingSlashes && strings.HasPrefix(str.Value, "//") {
if filepath.Dir(f.Path) == "." || !strings.HasPrefix(str.Value, "//:") {
str.Value = str.Value[2:]
}
}
if w.ShortenAbsoluteLabelsToRelative {
thisPackage := labelPrefix + filepath.Dir(f.Path)
// filepath.Dir on Windows uses backslashes as separators, while labels always have slashes.
if filepath.Separator != '/' {
thisPackage = strings.Replace(thisPackage, string(filepath.Separator), "/", -1)
}
if str.Value == thisPackage {
str.Value = ":" + path.Base(str.Value)
} else if strings.HasPrefix(str.Value, thisPackage+":") {
str.Value = str.Value[len(thisPackage):]
}
}
m := labelRE.FindStringSubmatch(str.Value)
if m == nil {
return
}
if m[4] != "" && m[4] == m[5] { // e.g. //foo:foo
str.Value = m[1]
} else if m[3] != "" && m[4] == "" && m[3] == m[5] { // e.g. @foo//:foo
str.Value = "@" + m[3]
}
}
// Join and shorten labels within a container of labels (which can be a single
// label, e.g. a single string expression or a concatenation of them).
// Gracefully finish if the argument is of a different type.
fixLabelsWithinAContainer := func(e *Expr) {
if list, ok := (*e).(*ListExpr); ok {
for i := range list.List {
if leaveAlone1(list.List[i]) {
continue
}
joinLabel(&list.List[i])
shortenLabel(list.List[i])
}
}
if set, ok := (*e).(*SetExpr); ok {
for i := range set.List {
if leaveAlone1(set.List[i]) {
continue
}
joinLabel(&set.List[i])
shortenLabel(set.List[i])
}
} else {
joinLabel(e)
shortenLabel(*e)
}
}
Walk(f, func(v Expr, stk []Expr) {
switch v := v.(type) {
case *CallExpr:
if leaveAlone(stk, v) {
return
}
for i := range v.List {
if leaveAlone1(v.List[i]) {
continue
}
as, ok := v.List[i].(*AssignExpr)
if !ok {
continue
}
key, ok := as.LHS.(*Ident)
if !ok || !w.IsLabelArg[key.Name] || w.LabelDenyList[callName(v)+"."+key.Name] {
continue
}
if leaveAlone1(as.RHS) {
continue
}
findAndModifyStrings(&as.RHS, fixLabelsWithinAContainer)
}
}
})
}
// callName returns the name of the rule being called by call.
// If the call is not to a literal rule name or a dot expression, callName
// returns "".
func callName(call *CallExpr) string {
return (&Rule{call, ""}).Kind()
}
// sortCallArgs sorts lists of named arguments to a call.
func sortCallArgs(f *File, w *Rewriter) {
Walk(f, func(v Expr, stk []Expr) {
call, ok := v.(*CallExpr)
if !ok {
return
}
if leaveAlone(stk, call) {
return
}
rule := callName(call)
if rule == "" {
rule = "<complex rule kind>"
}
// Find the tail of the argument list with named arguments.
start := len(call.List)
for start > 0 && argName(call.List[start-1]) != "" {
start--
}
// Record information about each arg into a sortable list.
var args namedArgs
for i, x := range call.List[start:] {
name := argName(x)
args = append(args, namedArg{ruleNamePriority(w, rule, name), name, i, x})
}
// Sort the list and put the args back in the new order.
if sort.IsSorted(args) {
return
}
sort.Sort(args)
for i, x := range args {
call.List[start+i] = x.expr
}
})
}
// ruleNamePriority maps a rule argument name to its sorting priority.
// It could use the auto-generated per-rule tables but for now it just
// falls back to the original list.
func ruleNamePriority(w *Rewriter, rule, arg string) int {
ruleArg := rule + "." + arg
if val, ok := w.NamePriority[ruleArg]; ok {
return val
}
return w.NamePriority[arg]
/*
list := ruleArgOrder[rule]
if len(list) == 0 {
return tables.NamePriority[arg]
}
for i, x := range list {
if x == arg {
return i
}
}
return len(list)
*/
}
// If x is of the form key=value, argName returns the string key.
// Otherwise argName returns "".
func argName(x Expr) string {
if as, ok := x.(*AssignExpr); ok {
if id, ok := as.LHS.(*Ident); ok {
return id.Name
}
}
return ""
}
// A namedArg records information needed for sorting
// a named call argument into its proper position.
type namedArg struct {
priority int // kind of name; first sort key
name string // name; second sort key
index int // original index; final sort key
expr Expr // name=value argument
}
// namedArgs is a slice of namedArg that implements sort.Interface
type namedArgs []namedArg
func (x namedArgs) Len() int { return len(x) }
func (x namedArgs) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x namedArgs) Less(i, j int) bool {
p := x[i]
q := x[j]
if p.priority != q.priority {
return p.priority < q.priority
}
if p.name != q.name {
return p.name < q.name
}
return p.index < q.index
}
// sortStringLists sorts lists of string literals used as specific rule arguments.
func sortStringLists(f *File, w *Rewriter) {
sortStringList := func(x *Expr) {
SortStringList(*x)
}
Walk(f, func(e Expr, stk []Expr) {
switch v := e.(type) {
case *CallExpr:
if f.Type == TypeDefault || f.Type == TypeBzl {
// Rule parameters, not applicable to .bzl or default file types
return
}
if leaveAlone(stk, v) {
return
}
rule := callName(v)
for _, arg := range v.List {
if leaveAlone1(arg) {
continue
}
as, ok := arg.(*AssignExpr)
if !ok || leaveAlone1(as) {
continue
}
key, ok := as.LHS.(*Ident)
if !ok {
continue
}
context := rule + "." + key.Name
if w.SortableDenylist[context] {
continue
}
if w.IsSortableListArg[key.Name] ||
w.SortableAllowlist[context] ||
(!disabled("unsafesort") && allowedSort(context)) {
if doNotSort(as) {
deduplicateStringList(as.RHS)
} else {
findAndModifyStrings(&as.RHS, sortStringList)
}
}
}
case *AssignExpr:
if disabled("unsafesort") {
return
}
// "keep sorted" comment on x = list forces sorting of list.
if keepSorted(v) {
findAndModifyStrings(&v.RHS, sortStringList)
}
case *KeyValueExpr:
if disabled("unsafesort") {
return
}
// "keep sorted" before key: list also forces sorting of list.
if keepSorted(v) {
findAndModifyStrings(&v.Value, sortStringList)
}
case *ListExpr:
if disabled("unsafesort") {
return
}
// "keep sorted" comment above first list element also forces sorting of list.
if len(v.List) > 0 && (keepSorted(v) || keepSorted(v.List[0])) {
findAndModifyStrings(&e, sortStringList)
}
}
})
}
// deduplicateStringList removes duplicates from a list with string expressions
// without reordering its elements.
// Any suffix-comments are lost, any before- and after-comments are preserved.
func deduplicateStringList(x Expr) {
list, ok := x.(*ListExpr)
if !ok {
return
}
list.List = deduplicateStringExprs(list.List)
}
// deduplicateStringExprs removes duplicate string expressions from a slice
// without reordering its elements.
// Any suffix-comments are lost, any before- and after-comments are preserved.
func deduplicateStringExprs(list []Expr) []Expr {
var comments []Comment
alreadySeen := make(map[string]bool)
var deduplicated []Expr
for _, value := range list {
str, ok := value.(*StringExpr)
if !ok {
deduplicated = append(deduplicated, value)
continue
}
strVal := str.Value
if _, ok := alreadySeen[strVal]; ok {
// This is a duplicate of a string above.
// Collect comments so that they're not lost.
comments = append(comments, str.Comment().Before...)
comments = append(comments, str.Comment().After...)
continue
}
alreadySeen[strVal] = true
if len(comments) > 0 {
comments = append(comments, value.Comment().Before...)
value.Comment().Before = comments
comments = nil
}
deduplicated = append(deduplicated, value)
}
return deduplicated
}
// SortStringList sorts x, a list of strings.
// The list is broken by non-strings and by blank lines and comments into chunks.
// Each chunk is sorted in place.
func SortStringList(x Expr) {
list, ok := x.(*ListExpr)
if !ok || len(list.List) < 2 {
return
}
if doNotSort(list.List[0]) {
list.List = deduplicateStringExprs(list.List)
return
}
forceSort := keepSorted(list) || keepSorted(list.List[0])
// TODO(bazel-team): Decide how to recognize lists that cannot
// be sorted. Avoiding all lists with comments avoids sorting
// lists that say explicitly, in some form or another, why they
// cannot be sorted. For example, many cc_test rules require
// certain order in their deps attributes.
if !forceSort {
if line, _ := hasComments(list); line {
deduplicateStringList(list)
return
}
}
list.List = sortStringExprs(list.List)
}
// findAndModifyStrings finds and modifies string lists with a callback
// function recursively within the given expression. It doesn't touch all
// string lists it can find, but only top-level lists, lists that are parts of
// concatenated expressions and lists within select statements.
// It calls the callback on the root node and on all relevant inner lists.
// The callback function should gracefully return if called with not appropriate
// arguments.
func findAndModifyStrings(x *Expr, callback func(*Expr)) {
callback(x)
switch x := (*x).(type) {
case *BinaryExpr:
if x.Op != "+" {
return
}
findAndModifyStrings(&x.X, callback)
findAndModifyStrings(&x.Y, callback)
case *CallExpr:
if ident, ok := x.X.(*Ident); !ok || ident.Name != "select" {
return
}
if len(x.List) == 0 {
return
}
dict, ok := x.List[0].(*DictExpr)
if !ok {
return
}
for _, kv := range dict.List {
findAndModifyStrings(&kv.Value, callback)
}
}
}
func sortStringExprs(list []Expr) []Expr {
if len(list) < 2 {
return list
}
// Sort chunks of the list with no intervening blank lines or comments.
for i := 0; i < len(list); {
if _, ok := list[i].(*StringExpr); !ok {
i++
continue
}
j := i + 1
for ; j < len(list); j++ {
if str, ok := list[j].(*StringExpr); !ok || len(str.Before) > 0 {
break
}
}
var chunk []stringSortKey
for index, x := range list[i:j] {
chunk = append(chunk, makeSortKey(index, x.(*StringExpr)))
}
if !sort.IsSorted(byStringExpr(chunk)) || !isUniq(chunk) {
before := chunk[0].x.Comment().Before
chunk[0].x.Comment().Before = nil
sort.Sort(byStringExpr(chunk))
chunk = uniq(chunk)
chunk[0].x.Comment().Before = before
for offset, key := range chunk {
list[i+offset] = key.x
}
list = append(list[:(i+len(chunk))], list[j:]...)
}
i = j
}
return list
}
// uniq removes duplicates from a list, which must already be sorted.
// It edits the list in place.
func uniq(sortedList []stringSortKey) []stringSortKey {
out := sortedList[:0]
for _, sk := range sortedList {
if len(out) == 0 || sk.value != out[len(out)-1].value {
out = append(out, sk)
}
}
return out
}
// isUniq reports whether the sorted list only contains unique elements.
func isUniq(list []stringSortKey) bool {
for i := range list {
if i+1 < len(list) && list[i].value == list[i+1].value {
return false
}
}
return true
}
// If stk describes a call argument like rule(arg=...), callArgName
// returns the name of that argument, formatted as "rule.arg".
func callArgName(stk []Expr) string {
n := len(stk)
if n < 2 {
return ""
}
arg := argName(stk[n-1])
if arg == "" {
return ""
}
call, ok := stk[n-2].(*CallExpr)
if !ok {
return ""
}
rule, ok := call.X.(*Ident)
if !ok {
return ""
}
return rule.Name + "." + arg
}
// A stringSortKey records information about a single string literal to be
// sorted. The strings are first grouped into four phases: most strings,
// strings beginning with ":", strings beginning with "//", and strings
// beginning with "@". The next significant part of the comparison is the list
// of elements in the value, where elements are split at `.' and `:'. Finally
// we compare by value and break ties by original index.
type stringSortKey struct {
phase int
split []string
value string
original int
x Expr
}
func makeSortKey(index int, x *StringExpr) stringSortKey {
key := stringSortKey{
value: x.Value,
original: index,
x: x,
}
switch {
case strings.HasPrefix(x.Value, ":"):
key.phase = 1
case strings.HasPrefix(x.Value, "//") || (tables.StripLabelLeadingSlashes && !strings.HasPrefix(x.Value, "@")):
key.phase = 2
case strings.HasPrefix(x.Value, "@"):
key.phase = 3
}
key.split = strings.Split(strings.Replace(x.Value, ":", ".", -1), ".")
return key
}
// byStringExpr implements sort.Interface for a list of stringSortKey.
type byStringExpr []stringSortKey
func (x byStringExpr) Len() int { return len(x) }
func (x byStringExpr) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
func (x byStringExpr) Less(i, j int) bool {
xi := x[i]
xj := x[j]
if xi.phase != xj.phase {
return xi.phase < xj.phase
}
for k := 0; k < len(xi.split) && k < len(xj.split); k++ {
if xi.split[k] != xj.split[k] {
return xi.split[k] < xj.split[k]
}
}
if len(xi.split) != len(xj.split) {
return len(xi.split) < len(xj.split)
}
if xi.value != xj.value {
return xi.value < xj.value
}
return xi.original < xj.original
}
// fixMultilinePlus turns
//
// ... +
// [ ... ]
//
// ... +
// call(...)
//
// into
//
// ... + [
// ...
// ]
//
// ... + call(
// ...
// )
//
// which typically works better with our aggressively compact formatting.
func fixMultilinePlus(f *File, _ *Rewriter) {
// List manipulation helpers.
// As a special case, we treat f([...]) as a list, mainly
// for glob.
// isList reports whether x is a list.
var isList func(x Expr) bool
isList = func(x Expr) bool {
switch x := x.(type) {
case *ListExpr:
return true
case *CallExpr:
if len(x.List) == 1 {
return isList(x.List[0])
}
}
return false
}
// isMultiLine reports whether x is a multiline list.
var isMultiLine func(Expr) bool
isMultiLine = func(x Expr) bool {
switch x := x.(type) {
case *ListExpr:
return x.ForceMultiLine || len(x.List) > 1
case *CallExpr:
if x.ForceMultiLine || len(x.List) > 1 && !x.ForceCompact {
return true
}
if len(x.List) == 1 {
return isMultiLine(x.List[0])
}
}
return false
}
// forceMultiLine tries to force the list x to use a multiline form.
// It reports whether it was successful.
var forceMultiLine func(Expr) bool
forceMultiLine = func(x Expr) bool {
switch x := x.(type) {
case *ListExpr:
// Already multi line?
if x.ForceMultiLine {
return true
}
// If this is a list containing a list, force the
// inner list to be multiline instead.
if len(x.List) == 1 && forceMultiLine(x.List[0]) {
return true
}
x.ForceMultiLine = true
return true
case *CallExpr:
if len(x.List) == 1 {
return forceMultiLine(x.List[0])
}
}
return false
}
skip := map[Expr]bool{}
Walk(f, func(v Expr, stk []Expr) {
if skip[v] {
return
}
bin, ok := v.(*BinaryExpr)
if !ok || bin.Op != "+" {
return
}
// Found a +.
// w + x + y + z parses as ((w + x) + y) + z,
// so chase down the left side to make a list of
// all the things being added together, separated
// by the BinaryExprs that join them.
// Mark them as "skip" so that when Walk recurses
// into the subexpressions, we won't reprocess them.
var all []Expr
for {
all = append(all, bin.Y, bin)
bin1, ok := bin.X.(*BinaryExpr)
if !ok || bin1.Op != "+" {
break
}
bin = bin1
skip[bin] = true
}
all = append(all, bin.X)
// Because the outermost expression was the
// rightmost one, the list is backward. Reverse it.
for i, j := 0, len(all)-1; i < j; i, j = i+1, j-1 {
all[i], all[j] = all[j], all[i]
}
// The 'all' slice is alternating addends and BinaryExpr +'s:
// w, +, x, +, y, +, z
// If there are no lists involved, don't rewrite anything.
haveList := false
for i := 0; i < len(all); i += 2 {
if isList(all[i]) {
haveList = true
break
}
}
if !haveList {
return
}
// Okay, there are lists.
// Consider each + next to a line break.
for i := 1; i < len(all); i += 2 {
bin := all[i].(*BinaryExpr)
if !bin.LineBreak {
continue
}
// We're going to break the line after the +.
// If it is followed by a list, force that to be
// multiline instead.
if forceMultiLine(all[i+1]) {
bin.LineBreak = false
continue
}
// If the previous list was multiline already,
// don't bother with the line break after
// the +.
if isMultiLine(all[i-1]) {
bin.LineBreak = false
continue
}
}
})
}
// isFunctionCall checks whether expr is a call of a function with a given name
func isFunctionCall(expr Expr, name string) bool {
call, ok := expr.(*CallExpr)
if !ok {
return false
}
if ident, ok := call.X.(*Ident); ok && ident.Name == name {
return true
}
return false
}
// moveLoadOnTop moves all load statements to the top of the file
func moveLoadOnTop(f *File, _ *Rewriter) {
if f.Type == TypeWorkspace {
// Moving load statements in Workspace files can break the semantics
return
}
if isCommentAnywhere(f, "disable=load-on-top") {
// For backward compatibility. This rewrite used to be a suppressible warning,
// in some cases it's hard to maintain the position of load statements (e.g.
// when the file is automatically generated or has automatic transformations
// applied to it). The rewrite checks for the comment anywhere in the file
// because it's hard to determine which statement is out of order.
return
}
// Find the misplaced load statements
misplacedLoads := make(map[int]*LoadStmt)
firstStmtIndex := -1 // index of the first seen non-load statement
for i := 0; i < len(f.Stmt); i++ {
stmt := f.Stmt[i]
_, isString := stmt.(*StringExpr) // typically a docstring
_, isComment := stmt.(*CommentBlock)
isWorkspace := isFunctionCall(stmt, "workspace")
if isString || isComment || isWorkspace || stmt == nil {
continue
}
load, ok := stmt.(*LoadStmt)
if !ok {
if firstStmtIndex == -1 {
firstStmtIndex = i
}
continue
}
if firstStmtIndex == -1 {
continue
}
misplacedLoads[i] = load
}
// Calculate a fix
if firstStmtIndex == -1 {
firstStmtIndex = 0
}
offset := len(misplacedLoads)
if offset == 0 {
return