-
Notifications
You must be signed in to change notification settings - Fork 41
/
wsl.go
1416 lines (1229 loc) · 43 KB
/
wsl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package wsl
import (
"fmt"
"go/ast"
"go/token"
"reflect"
"sort"
"strings"
)
// Error reason strings.
const (
reasonAnonSwitchCuddled = "anonymous switch statements should never be cuddled"
reasonAppendCuddledWithoutUse = "append only allowed to cuddle with appended value"
reasonAssignsCuddleAssign = "assignments should only be cuddled with other assignments"
reasonBlockEndsWithWS = "block should not end with a whitespace (or comment)"
reasonBlockStartsWithWS = "block should not start with a whitespace"
reasonCaseBlockTooCuddly = "case block should end with newline at this size"
reasonDeferCuddledWithOtherVar = "defer statements should only be cuddled with expressions on same variable"
reasonExprCuddlingNonAssignedVar = "only cuddled expressions if assigning variable or using from line above"
reasonExpressionCuddledWithBlock = "expressions should not be cuddled with blocks"
reasonExpressionCuddledWithDeclOrRet = "expressions should not be cuddled with declarations or returns"
reasonForCuddledAssignWithoutUse = "for statements should only be cuddled with assignments used in the iteration"
reasonForWithoutCondition = "for statement without condition should never be cuddled"
reasonGoFuncWithoutAssign = "go statements can only invoke functions assigned on line above"
reasonMultiLineBranchCuddle = "branch statements should not be cuddled if block has more than two lines"
reasonMustCuddleErrCheck = "if statements that check an error must be cuddled with the statement that assigned the error"
reasonNeverCuddleDeclare = "declarations should never be cuddled"
reasonOnlyCuddle2LineReturn = "return statements should not be cuddled if block has more than two lines"
reasonOnlyCuddleIfWithAssign = "if statements should only be cuddled with assignments"
reasonOnlyCuddleWithUsedAssign = "if statements should only be cuddled with assignments used in the if statement itself"
reasonOnlyOneCuddleBeforeDefer = "only one cuddle assignment allowed before defer statement"
reasonOnlyOneCuddleBeforeFor = "only one cuddle assignment allowed before for statement"
reasonOnlyOneCuddleBeforeGo = "only one cuddle assignment allowed before go statement"
reasonOnlyOneCuddleBeforeIf = "only one cuddle assignment allowed before if statement"
reasonOnlyOneCuddleBeforeRange = "only one cuddle assignment allowed before range statement"
reasonOnlyOneCuddleBeforeSwitch = "only one cuddle assignment allowed before switch statement"
reasonOnlyOneCuddleBeforeTypeSwitch = "only one cuddle assignment allowed before type switch statement"
reasonRangeCuddledWithoutUse = "ranges should only be cuddled with assignments used in the iteration"
reasonShortDeclNotExclusive = "short declaration should cuddle only with other short declarations"
reasonSwitchCuddledWithoutUse = "switch statements should only be cuddled with variables switched"
reasonTypeSwitchCuddledWithoutUse = "type switch statements should only be cuddled with variables switched"
)
// Warning strings.
const (
warnTypeNotImplement = "type not implemented"
warnStmtNotImplemented = "stmt type not implemented"
warnBodyStmtTypeNotImplemented = "body statement type not implemented "
warnWSNodeTypeNotImplemented = "whitespace node type not implemented "
warnUnknownLHS = "UNKNOWN LHS"
warnUnknownRHS = "UNKNOWN RHS"
)
// Configuration represents configurable settings for the linter.
type Configuration struct {
// StrictAppend will do strict checking when assigning from append (x =
// append(x, y)). If this is set to true the append call must append either
// a variable assigned, called or used on the line above. Example on not
// allowed when this is true:
//
// x := []string{}
// y := "not going in X"
// x = append(x, "not y") // This is not allowed with StrictAppend
// z := "going in X"
//
// x = append(x, z) // This is allowed with StrictAppend
//
// m := transform(z)
// x = append(x, z) // So is this because Z is used above.
StrictAppend bool
// AllowAssignAndCallCuddle allows assignments to be cuddled with variables
// used in calls on line above and calls to be cuddled with assignments of
// variables used in call on line above.
// Example supported with this set to true:
//
// x.Call()
// x = Assign()
// x.AnotherCall()
// x = AnotherAssign()
AllowAssignAndCallCuddle bool
// AllowAssignAndAnythingCuddle allows assignments to be cuddled with anything.
// Example supported with this set to true:
// if x == 1 {
// x = 0
// }
// z := x + 2
// fmt.Println("x")
// y := "x"
AllowAssignAndAnythingCuddle bool
// AllowMultiLineAssignCuddle allows cuddling to assignments even if they
// span over multiple lines. This defaults to true which allows the
// following example:
//
// err := function(
// "multiple", "lines",
// )
// if err != nil {
// // ...
// }
AllowMultiLineAssignCuddle bool
// If the number of lines in a case block is equal to or lager than this
// number, the case *must* end white a newline.
ForceCaseTrailingWhitespaceLimit int
// AllowTrailingComment will allow blocks to end with comments.
AllowTrailingComment bool
// AllowSeparatedLeadingComment will allow multiple comments in the
// beginning of a block separated with newline. Example:
// func () {
// // Comment one
//
// // Comment two
// fmt.Println("x")
// }
AllowSeparatedLeadingComment bool
// AllowCuddleDeclaration will allow multiple var/declaration statements to
// be cuddled. This defaults to false but setting it to true will enable the
// following example:
// var foo bool
// var err error
AllowCuddleDeclaration bool
// AllowCuddleWithCalls is a list of call idents that everything can be
// cuddled with. Defaults to calls looking like locks to support a flow like
// this:
//
// mu.Lock()
// allow := thisAssignment
AllowCuddleWithCalls []string
// AllowCuddleWithRHS is a list of right hand side variables that is allowed
// to be cuddled with anything. Defaults to assignments or calls looking
// like unlocks to support a flow like this:
//
// allow := thisAssignment()
// mu.Unlock()
AllowCuddleWithRHS []string
// ForceCuddleErrCheckAndAssign will cause an error when an If statement that
// checks an error variable doesn't cuddle with the assignment of that variable.
// This defaults to false but setting it to true will cause the following
// to generate an error:
//
// err := ProduceError()
//
// if err != nil {
// return err
// }
ForceCuddleErrCheckAndAssign bool
// When ForceCuddleErrCheckAndAssign is enabled this is a list of names
// used for error variables to check for in the conditional.
// Defaults to just "err"
ErrorVariableNames []string
// ForceExclusiveShortDeclarations will cause an error if a short declaration
// (:=) cuddles with anything other than another short declaration. For example
//
// a := 2
// b := 3
//
// is allowed, but
//
// a := 2
// b = 3
//
// is not allowed. This logic overrides ForceCuddleErrCheckAndAssign among others.
ForceExclusiveShortDeclarations bool
// IncludeGenerated will include generated files in the analysis and report
// errors even for generated files. Can be useful when developing
// generators.
IncludeGenerated bool
}
// fix is a range to fixup.
type fix struct {
fixRangeStart token.Pos
fixRangeEnd token.Pos
}
// result represents the result of one error.
type result struct {
fixRanges []fix
reason string
}
// processor is the type that keeps track of the file and fileset and holds the
// results from parsing the AST.
type processor struct {
config *Configuration
file *ast.File
fileSet *token.FileSet
result map[token.Pos]result
warnings []string
}
// newProcessorWithConfig will create a Processor with the passed configuration.
func newProcessorWithConfig(file *ast.File, fileSet *token.FileSet, cfg *Configuration) *processor {
return &processor{
config: cfg,
file: file,
fileSet: fileSet,
result: make(map[token.Pos]result),
}
}
// parseAST will parse the AST attached to the Processor instance.
func (p *processor) parseAST() {
for _, d := range p.file.Decls {
switch v := d.(type) {
case *ast.FuncDecl:
p.parseBlockBody(v.Name, v.Body)
case *ast.GenDecl:
// `go fmt` will handle proper spacing for GenDecl such as imports,
// constants etc.
default:
p.addWarning(warnTypeNotImplement, d.Pos(), v)
}
}
}
// parseBlockBody will parse any kind of block statements such as switch cases
// and if statements. A list of Result is returned.
func (p *processor) parseBlockBody(ident *ast.Ident, block *ast.BlockStmt) {
// Nothing to do if there's no value.
if reflect.ValueOf(block).IsNil() {
return
}
// Start by finding leading and trailing whitespaces.
p.findLeadingAndTrailingWhitespaces(ident, block, nil)
// Parse the block body contents.
p.parseBlockStatements(block.List)
}
// parseBlockStatements will parse all the statements found in the body of a
// node. A list of Result is returned.
func (p *processor) parseBlockStatements(statements []ast.Stmt) {
for i, stmt := range statements {
// Start by checking if this statement is another block (other than if,
// for and range). This could be assignment to a function, defer or go
// call with an inline function or similar. If this is found we start by
// parsing this body block before moving on.
for _, stmtBlocks := range p.findBlockStmt(stmt) {
p.parseBlockBody(nil, stmtBlocks)
}
firstBodyStatement := p.firstBodyStatement(i, statements)
// First statement, nothing to do.
if i == 0 {
continue
}
previousStatement := statements[i-1]
previousStatementIsMultiline := p.nodeStart(previousStatement) != p.nodeEnd(previousStatement)
cuddledWithLastStmt := p.nodeEnd(previousStatement) == p.nodeStart(stmt)-1
// If we're not cuddled and we don't need to enforce err-check cuddling
// then we can bail out here
if !cuddledWithLastStmt && !p.config.ForceCuddleErrCheckAndAssign {
continue
}
// We don't force error cuddling for multilines. (#86)
if p.config.ForceCuddleErrCheckAndAssign && previousStatementIsMultiline && !cuddledWithLastStmt {
continue
}
// Extract assigned variables on the line above
// which is the only thing we allow cuddling with. If the assignment is
// made over multiple lines we should not allow cuddling.
var assignedOnLineAbove []string
// We want to keep track of what was called on the line above to support
// special handling of things such as mutexes.
var calledOnLineAbove []string
// Check if the previous statement spans over multiple lines.
cuddledWithMultiLineAssignment := cuddledWithLastStmt && p.nodeStart(previousStatement) != p.nodeStart(stmt)-1
// Ensure previous line is not a multi line assignment and if not get
// rightAndLeftHandSide assigned variables.
if !cuddledWithMultiLineAssignment {
assignedOnLineAbove = p.findLHS(previousStatement)
calledOnLineAbove = p.findRHS(previousStatement)
}
// If previous assignment is multi line and we allow it, fetch
// assignments (but only assignments).
if cuddledWithMultiLineAssignment && p.config.AllowMultiLineAssignCuddle {
if _, ok := previousStatement.(*ast.AssignStmt); ok {
assignedOnLineAbove = p.findLHS(previousStatement)
}
}
// We could potentially have a block which require us to check the first
// argument before ruling out an allowed cuddle.
var calledOrAssignedFirstInBlock []string
if firstBodyStatement != nil {
calledOrAssignedFirstInBlock = append(p.findLHS(firstBodyStatement), p.findRHS(firstBodyStatement)...)
}
var (
leftHandSide = p.findLHS(stmt)
rightHandSide = p.findRHS(stmt)
rightAndLeftHandSide = append(leftHandSide, rightHandSide...)
calledOrAssignedOnLineAbove = append(calledOnLineAbove, assignedOnLineAbove...)
)
// If we called some kind of lock on the line above we allow cuddling
// anything.
if atLeastOneInListsMatch(calledOnLineAbove, p.config.AllowCuddleWithCalls) {
continue
}
// If we call some kind of unlock on this line we allow cuddling with
// anything.
if atLeastOneInListsMatch(rightHandSide, p.config.AllowCuddleWithRHS) {
continue
}
nStatementsBefore := func(n int) bool {
if i < n {
return false
}
for j := 1; j < n; j++ {
s1 := statements[i-j]
s2 := statements[i-(j+1)]
if p.nodeStart(s1)-1 != p.nodeEnd(s2) {
return false
}
}
return true
}
nStatementsAfter := func(n int) bool {
if len(statements)-1 < i+n {
return false
}
for j := range n {
s1 := statements[i+j]
s2 := statements[i+j+1]
if p.nodeEnd(s1)+1 != p.nodeStart(s2) {
return false
}
}
return true
}
isLastStatementInBlockOfOnlyTwoLines := func() bool {
// If we're the last statement, check if there's no more than two
// lines from the starting statement and the end of this statement.
// This is to support short return functions such as:
// func (t *Typ) X() {
// t.X = true
// return t
// }
if len(statements) == 2 && i == 1 {
if p.nodeEnd(stmt)-p.nodeStart(previousStatement) <= 2 {
return true
}
}
return false
}
// If it's a short declaration we should not cuddle with anything else
// if ForceExclusiveShortDeclarations is set on; either this or the
// previous statement could be the short decl, so we'll find out which
// it was and use *that* statement's position
if p.config.ForceExclusiveShortDeclarations && cuddledWithLastStmt {
if p.isShortDecl(stmt) && !p.isShortDecl(previousStatement) {
var reportNode ast.Node = previousStatement
cm := ast.NewCommentMap(p.fileSet, stmt, p.file.Comments)
if cg, ok := cm[stmt]; ok && len(cg) > 0 {
for _, c := range cg {
if c.Pos() > previousStatement.End() && c.End() < stmt.Pos() {
reportNode = c
}
}
}
p.addErrorRange(
stmt.Pos(),
reportNode.End(),
reportNode.End(),
reasonShortDeclNotExclusive,
)
} else if p.isShortDecl(previousStatement) && !p.isShortDecl(stmt) {
p.addErrorRange(
previousStatement.Pos(),
stmt.Pos(),
stmt.Pos(),
reasonShortDeclNotExclusive,
)
}
}
// If it's not an if statement and we're not cuddled move on. The only
// reason we need to keep going for if statements is to check if we
// should be cuddled with an error check.
if _, ok := stmt.(*ast.IfStmt); !ok {
if !cuddledWithLastStmt {
continue
}
}
reportNewlineTwoLinesAbove := func(n1, n2 ast.Node, reason string) {
if atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) ||
atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
// If both the assignment on the line above _and_ the assignment
// two lines above is part of line or first in block, add the
// newline as if non were.
_, isAssignmentTwoLinesAbove := statements[i-2].(*ast.AssignStmt)
assignedTwoLinesAbove := p.findLHS(statements[i-2])
if isAssignmentTwoLinesAbove &&
(atLeastOneInListsMatch(rightAndLeftHandSide, assignedTwoLinesAbove) ||
atLeastOneInListsMatch(assignedTwoLinesAbove, calledOrAssignedFirstInBlock)) {
p.addWhitespaceBeforeError(n1, reason)
} else {
// If the variable on the line above is allowed to be
// cuddled, break two lines above so we keep the proper
// cuddling.
p.addErrorRange(n1.Pos(), n2.Pos(), n2.Pos(), reason)
}
} else {
// If not, break here so we separate the cuddled variable.
p.addWhitespaceBeforeError(n1, reason)
}
}
switch t := stmt.(type) {
case *ast.IfStmt:
checkingErrInitializedInline := func() bool {
if t.Init == nil {
return false
}
// Variables were initialized inline in the if statement
// Let's make sure it's the err just to be safe
return atLeastOneInListsMatch(p.findLHS(t.Init), p.config.ErrorVariableNames)
}
if !cuddledWithLastStmt {
checkingErr := atLeastOneInListsMatch(rightAndLeftHandSide, p.config.ErrorVariableNames)
if checkingErr {
// We only want to enforce cuddling error checks if the
// error was assigned on the line above. See
// https://github.com/bombsimon/wsl/issues/78.
// This is needed since `assignedOnLineAbove` is not
// actually just assignments but everything from LHS in the
// previous statement. This means that if previous line was
// `if err ...`, `err` will now be in the list
// `assignedOnLineAbove`.
if _, ok := previousStatement.(*ast.AssignStmt); !ok {
continue
}
if checkingErrInitializedInline() {
continue
}
if atLeastOneInListsMatch(assignedOnLineAbove, p.config.ErrorVariableNames) {
p.addErrorRange(
stmt.Pos(),
previousStatement.End(),
stmt.Pos(),
reasonMustCuddleErrCheck,
)
}
}
continue
}
if len(assignedOnLineAbove) == 0 {
p.addWhitespaceBeforeError(t, reasonOnlyCuddleIfWithAssign)
continue
}
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeIf)
continue
}
if atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
continue
}
if atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
continue
}
p.addWhitespaceBeforeError(t, reasonOnlyCuddleWithUsedAssign)
case *ast.ReturnStmt:
if isLastStatementInBlockOfOnlyTwoLines() {
continue
}
p.addWhitespaceBeforeError(t, reasonOnlyCuddle2LineReturn)
case *ast.BranchStmt:
if isLastStatementInBlockOfOnlyTwoLines() {
continue
}
p.addWhitespaceBeforeError(t, reasonMultiLineBranchCuddle)
case *ast.AssignStmt:
// append is usually an assignment but should not be allowed to be
// cuddled with anything not appended.
if len(rightHandSide) > 0 && rightHandSide[len(rightHandSide)-1] == "append" {
if p.config.StrictAppend {
if !atLeastOneInListsMatch(calledOrAssignedOnLineAbove, rightHandSide) {
p.addWhitespaceBeforeError(t, reasonAppendCuddledWithoutUse)
}
}
continue
}
switch previousStatement.(type) {
case *ast.AssignStmt, *ast.IncDecStmt:
continue
}
if p.config.AllowAssignAndAnythingCuddle {
continue
}
if _, ok := previousStatement.(*ast.DeclStmt); ok && p.config.AllowCuddleDeclaration {
continue
}
// If the assignment is from a type or variable called on the line
// above we can allow it by setting AllowAssignAndCallCuddle to
// true.
// Example (x is used):
// x.function()
// a.Field = x.anotherFunction()
if p.config.AllowAssignAndCallCuddle {
if atLeastOneInListsMatch(calledOrAssignedOnLineAbove, rightAndLeftHandSide) {
continue
}
}
p.addWhitespaceBeforeError(t, reasonAssignsCuddleAssign)
case *ast.IncDecStmt:
switch previousStatement.(type) {
case *ast.AssignStmt, *ast.IncDecStmt:
continue
}
p.addWhitespaceBeforeError(t, reasonAssignsCuddleAssign)
case *ast.DeclStmt:
if !p.config.AllowCuddleDeclaration {
p.addWhitespaceBeforeError(t, reasonNeverCuddleDeclare)
}
case *ast.ExprStmt:
switch previousStatement.(type) {
case *ast.DeclStmt, *ast.ReturnStmt:
if p.config.AllowAssignAndCallCuddle && p.config.AllowCuddleDeclaration {
continue
}
p.addWhitespaceBeforeError(t, reasonExpressionCuddledWithDeclOrRet)
case *ast.IfStmt, *ast.RangeStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.ForStmt:
p.addWhitespaceBeforeError(t, reasonExpressionCuddledWithBlock)
}
// If the expression is called on a type or variable used or
// assigned on the line we can allow it by setting
// AllowAssignAndCallCuddle to true.
// Example of allowed cuddled (x is used):
// a.Field = x.func()
// x.function()
if p.config.AllowAssignAndCallCuddle {
if atLeastOneInListsMatch(calledOrAssignedOnLineAbove, rightAndLeftHandSide) {
continue
}
}
// If we assigned variables on the line above but didn't use them in
// this expression there should probably be a newline between them.
if len(assignedOnLineAbove) > 0 && !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
p.addWhitespaceBeforeError(t, reasonExprCuddlingNonAssignedVar)
}
case *ast.RangeStmt:
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeRange)
continue
}
if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
p.addWhitespaceBeforeError(t, reasonRangeCuddledWithoutUse)
}
}
case *ast.DeferStmt:
if _, ok := previousStatement.(*ast.DeferStmt); ok {
// We may cuddle multiple defers to group logic.
continue
}
if nStatementsBefore(2) {
// We allow cuddling defer if the defer references something
// used two lines above.
// There are several reasons to why we do this.
// Originally there was a special use case only for "Close"
//
// https://github.com/bombsimon/wsl/issues/31 which links to
// resp, err := client.Do(req)
// if err != nil {
// return err
// }
// defer resp.Body.Close()
//
// After a discussion in a followup issue it makes sense to not
// only hard code `Close` but for anything that's referenced two
// statements above.
//
// https://github.com/bombsimon/wsl/issues/85
// db, err := OpenDB()
// require.NoError(t, err)
// defer db.Close()
//
// All of this is only allowed if there's exactly three cuddled
// statements, otherwise the regular rules apply.
if !nStatementsBefore(3) && !nStatementsAfter(1) {
variablesTwoLinesAbove := append(p.findLHS(statements[i-2]), p.findRHS(statements[i-2])...)
if atLeastOneInListsMatch(rightHandSide, variablesTwoLinesAbove) {
continue
}
}
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeDefer)
continue
}
// Be extra nice with RHS, it's common to use this for locks:
// m.Lock()
// defer m.Unlock()
previousRHS := p.findRHS(previousStatement)
if atLeastOneInListsMatch(rightHandSide, previousRHS) {
continue
}
// Allow use to cuddled defer func literals with usages on line
// above. Example:
// b := getB()
// defer func() {
// makesSenseToUse(b)
// }()
if c, ok := t.Call.Fun.(*ast.FuncLit); ok {
funcLitFirstStmt := append(p.findLHS(c.Body), p.findRHS(c.Body)...)
if atLeastOneInListsMatch(assignedOnLineAbove, funcLitFirstStmt) {
continue
}
}
if atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
continue
}
if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
p.addWhitespaceBeforeError(t, reasonDeferCuddledWithOtherVar)
}
case *ast.ForStmt:
if len(rightAndLeftHandSide) == 0 {
p.addWhitespaceBeforeError(t, reasonForWithoutCondition)
continue
}
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeFor)
continue
}
// The same rule applies for ranges as for if statements, see
// comments regarding variable usages on the line before or as the
// first line in the block for details.
if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
p.addWhitespaceBeforeError(t, reasonForCuddledAssignWithoutUse)
}
}
case *ast.GoStmt:
if _, ok := previousStatement.(*ast.GoStmt); ok {
continue
}
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeGo)
continue
}
if c, ok := t.Call.Fun.(*ast.SelectorExpr); ok {
goCallArgs := append(p.findLHS(c.X), p.findRHS(c.X)...)
if atLeastOneInListsMatch(calledOnLineAbove, goCallArgs) {
continue
}
}
if c, ok := t.Call.Fun.(*ast.FuncLit); ok {
goCallArgs := append(p.findLHS(c.Body), p.findRHS(c.Body)...)
if atLeastOneInListsMatch(assignedOnLineAbove, goCallArgs) {
continue
}
}
if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
p.addWhitespaceBeforeError(t, reasonGoFuncWithoutAssign)
}
case *ast.SwitchStmt:
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeSwitch)
continue
}
if !atLeastOneInListsMatch(rightAndLeftHandSide, assignedOnLineAbove) {
if len(rightAndLeftHandSide) == 0 {
p.addWhitespaceBeforeError(t, reasonAnonSwitchCuddled)
} else {
p.addWhitespaceBeforeError(t, reasonSwitchCuddledWithoutUse)
}
}
case *ast.TypeSwitchStmt:
if nStatementsBefore(2) {
reportNewlineTwoLinesAbove(t, statements[i-1], reasonOnlyOneCuddleBeforeTypeSwitch)
continue
}
// Allowed to type assert on variable assigned on line above.
if !atLeastOneInListsMatch(rightHandSide, assignedOnLineAbove) {
// Allow type assertion on variables used in the first case
// immediately.
if !atLeastOneInListsMatch(assignedOnLineAbove, calledOrAssignedFirstInBlock) {
p.addWhitespaceBeforeError(t, reasonTypeSwitchCuddledWithoutUse)
}
}
case *ast.CaseClause, *ast.CommClause:
// Case clauses will be checked by not allowing leading of trailing
// whitespaces within the block. There's nothing in the case itself
// that may be cuddled.
default:
p.addWarning(warnStmtNotImplemented, t.Pos(), t)
}
}
}
// firstBodyStatement returns the first statement inside a body block. This is
// because variables may be cuddled with conditions or statements if it's used
// directly as the first argument inside a body.
// The body will then be parsed as a *ast.BlockStmt (regular block) or as a list
// of []ast.Stmt (case block).
func (p *processor) firstBodyStatement(i int, allStmt []ast.Stmt) ast.Node {
stmt := allStmt[i]
// Start by checking if the statement has a body (probably if-statement,
// a range, switch case or similar. Whenever a body is found we start by
// parsing it before moving on in the AST.
statementBody := reflect.Indirect(reflect.ValueOf(stmt)).FieldByName("Body")
// Some cases allow cuddling depending on the first statement in a body
// of a block or case. If possible extract the first statement.
var firstBodyStatement ast.Node
if !statementBody.IsValid() {
return firstBodyStatement
}
switch statementBodyContent := statementBody.Interface().(type) {
case *ast.BlockStmt:
if len(statementBodyContent.List) > 0 {
firstBodyStatement = statementBodyContent.List[0]
// If the first body statement is a *ast.CaseClause we're
// actually interested in the **next** body to know what's
// inside the first case.
if x, ok := firstBodyStatement.(*ast.CaseClause); ok {
if len(x.Body) > 0 {
firstBodyStatement = x.Body[0]
}
}
}
// If statement bodies will be parsed already when finding block bodies.
// The reason is because if/else-if/else chains is nested in the AST
// where the else bit is a part of the if statement. Since if statements
// is the only statement that can be chained like this we exclude it
// from parsing it again here.
if _, ok := stmt.(*ast.IfStmt); !ok {
p.parseBlockBody(nil, statementBodyContent)
}
case []ast.Stmt:
// The Body field for an *ast.CaseClause or *ast.CommClause is of type
// []ast.Stmt. We must check leading and trailing whitespaces and then
// pass the statements to parseBlockStatements to parse it's content.
var nextStatement ast.Node
// Check if there's more statements (potential cases) after the
// current one.
if len(allStmt)-1 > i {
nextStatement = allStmt[i+1]
}
p.findLeadingAndTrailingWhitespaces(nil, stmt, nextStatement)
p.parseBlockStatements(statementBodyContent)
default:
p.addWarning(
warnBodyStmtTypeNotImplemented,
stmt.Pos(), statementBodyContent,
)
}
return firstBodyStatement
}
func (p *processor) findLHS(node ast.Node) []string {
var lhs []string
if node == nil {
return lhs
}
switch t := node.(type) {
case *ast.BasicLit, *ast.FuncLit, *ast.SelectStmt,
*ast.LabeledStmt, *ast.ForStmt, *ast.SwitchStmt,
*ast.ReturnStmt, *ast.GoStmt, *ast.CaseClause,
*ast.CommClause, *ast.CallExpr, *ast.UnaryExpr,
*ast.BranchStmt, *ast.TypeSpec, *ast.ChanType,
*ast.DeferStmt, *ast.TypeAssertExpr, *ast.RangeStmt:
// Nothing to add to LHS
case *ast.IncDecStmt:
return p.findLHS(t.X)
case *ast.Ident:
return []string{t.Name}
case *ast.AssignStmt:
for _, v := range t.Lhs {
lhs = append(lhs, p.findLHS(v)...)
}
case *ast.GenDecl:
for _, v := range t.Specs {
lhs = append(lhs, p.findLHS(v)...)
}
case *ast.ValueSpec:
for _, v := range t.Names {
lhs = append(lhs, p.findLHS(v)...)
}
case *ast.BlockStmt:
for _, v := range t.List {
lhs = append(lhs, p.findLHS(v)...)
}
case *ast.BinaryExpr:
return append(
p.findLHS(t.X),
p.findLHS(t.Y)...,
)
case *ast.DeclStmt:
return p.findLHS(t.Decl)
case *ast.IfStmt:
return p.findLHS(t.Cond)
case *ast.TypeSwitchStmt:
return p.findLHS(t.Assign)
case *ast.SendStmt:
return p.findLHS(t.Chan)
default:
if x, ok := maybeX(t); ok {
return p.findLHS(x)
}
p.addWarning(warnUnknownLHS, t.Pos(), t)
}
return lhs
}
func (p *processor) findRHS(node ast.Node) []string {
var rhs []string
if node == nil {
return rhs
}
switch t := node.(type) {
case *ast.BasicLit, *ast.SelectStmt, *ast.ChanType,
*ast.LabeledStmt, *ast.DeclStmt, *ast.BranchStmt,
*ast.TypeSpec, *ast.ArrayType, *ast.CaseClause,
*ast.CommClause, *ast.MapType, *ast.FuncLit:
// Nothing to add to RHS
case *ast.Ident:
return []string{t.Name}
case *ast.SelectorExpr:
// TODO: Should this be RHS?
// t.X is needed for defer as of now and t.Sel needed for special
// functions such as Lock()
rhs = p.findRHS(t.X)
rhs = append(rhs, p.findRHS(t.Sel)...)
case *ast.AssignStmt:
for _, v := range t.Rhs {
rhs = append(rhs, p.findRHS(v)...)
}
case *ast.CallExpr:
for _, v := range t.Args {
rhs = append(rhs, p.findRHS(v)...)
}
rhs = append(rhs, p.findRHS(t.Fun)...)
case *ast.CompositeLit:
for _, v := range t.Elts {
rhs = append(rhs, p.findRHS(v)...)
}
case *ast.IfStmt:
rhs = append(rhs, p.findRHS(t.Cond)...)
rhs = append(rhs, p.findRHS(t.Init)...)
case *ast.BinaryExpr:
return append(
p.findRHS(t.X),
p.findRHS(t.Y)...,
)
case *ast.TypeSwitchStmt:
return p.findRHS(t.Assign)
case *ast.ReturnStmt:
for _, v := range t.Results {
rhs = append(rhs, p.findRHS(v)...)
}
case *ast.BlockStmt:
for _, v := range t.List {
rhs = append(rhs, p.findRHS(v)...)
}
case *ast.SwitchStmt:
return p.findRHS(t.Tag)
case *ast.GoStmt:
return p.findRHS(t.Call)
case *ast.ForStmt:
return p.findRHS(t.Cond)
case *ast.DeferStmt:
return p.findRHS(t.Call)
case *ast.SendStmt:
return p.findLHS(t.Value)
case *ast.IndexExpr:
rhs = append(rhs, p.findRHS(t.Index)...)
rhs = append(rhs, p.findRHS(t.X)...)
case *ast.SliceExpr:
rhs = append(rhs, p.findRHS(t.X)...)
rhs = append(rhs, p.findRHS(t.Low)...)
rhs = append(rhs, p.findRHS(t.High)...)
case *ast.KeyValueExpr:
rhs = p.findRHS(t.Key)
rhs = append(rhs, p.findRHS(t.Value)...)
default:
if x, ok := maybeX(t); ok {
return p.findRHS(x)
}
p.addWarning(warnUnknownRHS, t.Pos(), t)
}
return rhs
}
func (p *processor) isShortDecl(node ast.Node) bool {
if t, ok := node.(*ast.AssignStmt); ok {
return t.Tok == token.DEFINE
}
return false
}
func (p *processor) findBlockStmt(node ast.Node) []*ast.BlockStmt {
var blocks []*ast.BlockStmt
switch t := node.(type) {
case *ast.BlockStmt:
return []*ast.BlockStmt{t}
case *ast.AssignStmt:
for _, x := range t.Rhs {