This repository has been archived by the owner on Nov 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
LinterPluginTest.scala
2950 lines (2509 loc) · 101 KB
/
LinterPluginTest.scala
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 2012 Foursquare Labs, Inc.
*
* 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
*
* http://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.
*/
package org.psywerx.hairyfotr
import java.io.{ PrintWriter, StringWriter }
import org.junit.{ Ignore, Test }
import org.specs2.matcher.{ MustThrownMatchers, ThrownStandardMatchResults }
import scala.collection.mutable
import scala.io.Source
import scala.tools.nsc.interpreter.{ IMain, Results }
import scala.tools.nsc.reporters.Reporter
import scala.tools.nsc.{ Properties, Settings }
//TODO:
// * each test should have a positive and a negative case
// * have longer tests, that maybe trigger several checks
// * if it's worth it, error msgs could come from outside
// * handle/test plugin settings (when settings are done)
// * detect the non-compiling tests (they currently pass)
final object Compiler {
private[this] val settings = new Settings
private[this] val loader = manifest[LinterPlugin].runtimeClass.getClassLoader
settings.classpath.value = Source.fromURL(loader.getResource("app.class.path")).mkString
settings.bootclasspath.append(Source.fromURL(loader.getResource("boot.class.path")).mkString)
settings.deprecation.value = true // enable detailed deprecation warnings
//settings.unchecked.value = true // enable detailed unchecked warnings
settings.Xwarnfatal.value = true // warnings cause compile failures
//settings.stopAfter.value = List("linter-refchecked") // fails, but would speed up things
private[this] val stringWriter = new StringWriter()
// This is deprecated in 2.9.x, but we need to use it for compatibility with 2.8.x
private[this] val interpreter = new IMain(settings, new PrintWriter(stringWriter)) {
override protected def newCompiler(settings: Settings, reporter: Reporter) = {
settings.outputDirs setSingleOutput virtualDirectory
val compiler = super.newCompiler(settings, reporter)
val linterPlugin = new LinterPlugin(compiler)
import scala.language.reflectiveCalls
for (phase <- linterPlugin.components) {
compiler.asInstanceOf[{def phasesSet: mutable.HashSet[tools.nsc.SubComponent]}].phasesSet += phase
}
compiler
}
}
def compileAndLint(code: String, thunked: Boolean = true): String = {
stringWriter.getBuffer.delete(0, stringWriter.getBuffer.length)
val toInterpret = if (thunked) s"() => { \n$code\n }" else code
interpreter.interpret(toInterpret) match {
case Results.Success => ""
case Results.Error => stringWriter.toString
case Results.Incomplete => throw new Exception("Incomplete code snippet")
}
}
}
final class LinterPluginTest extends MustThrownMatchers with ThrownStandardMatchResults {
// A few hacks to avoid boilerplate and better pinpoint the failing test
def should(code: String, thunked: Boolean = true)(implicit expectedMsg: String, not: Boolean = false): Unit = {
val compileResult = Compiler.compileAndLint(code, thunked)
val unitResult = (expectedMsg, compileResult) must beLike {
case (expected, actual) if (not ^ actual.contains(expected)) => ok
case _ =>
val problem = s"""false ${if (not) "positive" else "negative"}"""
val trace =
Thread.currentThread.getStackTrace
.filter(_.getClassName == "org.psywerx.hairyfotr.LinterPluginTest")
.map(_.getMethodName)
.reverse.mkString(" -> ")
val fail = s"""|
|problem: $problem
|message: $expectedMsg
| trace: $trace
| code: $code
|""".stripMargin
println(fail)
ko(fail)
}
}
def noLint(code: String, thunked: Boolean = true): Unit = { val unitResult = Compiler.compileAndLint(code, thunked) must be ("") }
def noWarn(code: String, thunked: Boolean = true)(implicit expectedMsg: String): Unit = { should(code, thunked)(expectedMsg, not = true) }
/*@Before
def forceCompilerInit(): Unit = {
val unitResult = compiler.compileAndLint("1 + 1")
}*/
@Test
def readmeExamples(): Unit = {
val defs = """
val a,b,x,y = util.Random.nextInt
val bool = util.Random.nextBoolean
val str = util.Random.nextString(5)
val strOption = Option(str)
"""
should(defs+"""if (a == 10 || b == 10) 0 else if(a == 20 && b == 10) 1 else 2""")("""This condition has appeared earlier in the if-else chain and will never hold here.""")
should(defs+"""if (b > 4) (2,a) else (2,a)""")("""If statement branches have the same structure.""")
should(defs+"""if (a == b) true else false""")("""Remove the if expression and use the condition directly.""")
should(defs+"""(x,y) match { case (a,5) if a > 5 => 0 case (c,5) if c > 5 => 1 }""")("""Identical case condition detected above. This case will never match.""")
should(defs+"""a match { case 3 => "hello" case 4 => "hello" case 5 => "hello" case _ => "how low" }""")("""Bodies of 3 neighbouring cases are identical and could be merged.""")
should(defs+"""bool match { case true => 0 case false => 1 }""")("""Pattern matching on Boolean is probably better written as an if statement.""")
should(defs+"""for (i <- 10 to 20) { if(i > 20) "" }""")("""This condition will never hold.""")
should(defs+"""for (i <- 1 to 10) { 1/(i-1) }""")("""Possible division by zero.""")
should(defs+"""{ val a = List(1,2,3); for (i <- 1 to 10) { println(a(i)) } }""")("""You will likely use a too large index.""")
should(defs+"""for (i <- 10 to 20) { if (i.toString.length == 3) "" }""")("""This condition will never hold.""")
should(defs+"""val s = "hello"+util.Random.nextString(10)+"world"+util.Random.nextString(10)+"!"; if(s contains "world") ""; """)("""This contains always returns the same value: true""")
should(defs+"""val s = "hello"+util.Random.nextString(10)+"world"+util.Random.nextString(10)+"!"; if(s startsWith "hell") ""; """)("""This startsWith always returns the same value: true""")
should(defs+"""val s = "hello"+util.Random.nextString(10)+"world"+util.Random.nextString(10)+"!"; if(s endsWith "!") ""; """)("""This endsWith always returns the same value: true""")
should(defs+"""str.replaceAll("?", ".")""")("""Regex pattern syntax error: Dangling meta character '?'""")
should(defs+"""math.log(1d + a)""")("""Use math.log1p(x), instead of math.log(1 + x) for added accuracy when x is near 0.""")
should(defs+"""BigDecimal(0.555555555555555555555555555)""")("""Possible loss of precision.""")
should(defs+"""{val a = Some(List(1,2,3)); if (a.size > 3) ""}""")("""Did you mean to take the size of the collection inside the Option?""")
should(defs+"""if (strOption.isDefined) strOption.get else "" """)("""Use strOption.getOrElse(...) instead of if (strOption.isDefined) strOption.get else ...""")
should(defs+"""List(1,2,3,4).find(x => x % 2 == 0).isDefined""")("""Use col.exists(...) instead of col.find(...).isDefined""")
should(defs+"""List(1,2,3,4).flatMap(x => if (x % 2 == 0) List(x) else Nil)""")("""Use col.filter(x => condition) instead of col.flatMap(x => if (condition) ... else ...).""")
should(defs+"""def func(b: Int, c: String, d: String) = { println(b); b+c }""")("""Parameter d is not used in method func""")
//should(defs+"""List(1, 2, 3).contains("4")""")("""List[Int].contains(String) will probably return false because the collection and target element are of different types.""")
//should(defs+"""Nil == None""")("""Comparing with == on instances of different types (scala.collection.immutable.Nil.type, None.type) will probably return false.""")
should(defs+"""List(1, 2, 3).contains("4")""")("""will probably return false, since the collection and target element are of unrelated types.""")
should(defs+"""Nil == None""")("""Comparing with == on instances of unrelated types""")
}
@Test
def UseIfExpression(): Unit = {
implicit val msg = "Assign the result of the if expression"
should("""var a = 5; if(util.Random.nextBoolean) a = 4 else a = 2""")
should("""var a = "a"; if(util.Random.nextBoolean) a = "b" else a = "c" """)
noLint("""var a = 5; if(util.Random.nextBoolean) a = 4 else println("foo")""")
noLint("""var a = 5; if(util.Random.nextBoolean) println("foo") else a = 4""")
}
@Test
def UnnecessaryElseBranch(): Unit = {
implicit val msg = "Since the if branch always returns, the code from the else branch can be moved out to reduce nesting."
should("""
def test(): Any = {
if(util.Random.nextBoolean) {
println("foo"); return 5; println("foo2");
} else {
println("foo3"); println("foo4");
}
}""")
noLint("""
def test(): Any = {
if(util.Random.nextBoolean) {
println("foo"); println("foo2");
}
println("foo3"); println("foo4");
}""")
noLint("""
def test(): Any = {
if(util.Random.nextBoolean) {
println("foo"); println("foo2");
} else {
println("foo3"); return 3; println("foo4");
}
}""")
noLint("""
def test(): Any = {
if(util.Random.nextBoolean) {
println("foo");
if(util.Random.nextBoolean) return 5 else println("fds")
println("foo2");
} else {
println("foo3"); println("foo4");
}
}""")
}
@Test
def NumberInstanceOf(): Unit = {
implicit val msg = "asInstanceOf"
should("""4.asInstanceOf[Double]""")
should("""3.4.asInstanceOf[Byte]""")
should("""val a = 4; a.asInstanceOf[Double]""")
}
@Test
def incompleteTest_InvariantCondition(): Unit = {
implicit val msg = "This condition will"
should("""val (a,b) = (1,2); if(a != b) a else b""")
should("""val (a,b) = (1,2); if(a == b) a else b""")
should("""val (a,b) = (1,2); if(a == b) b else a""")
should("""val (a,b) = (1,2); if(a == b && util.Random.nextInt == 5) a else b""")
should("""val (a,b) = (1,2); if(a == b || util.Random.nextInt == 5) a else b""")
should("""val (a,b) = (1,2); if(util.Random.nextInt == 3) 4 else if(a == b) a else b""")
}
@Test
def UseHypot(): Unit = {
implicit val msg = "Use math.hypot"
should("""val x,y = util.Random.nextDouble; math.sqrt(x*x + y*y)""")
should("""val x,y = util.Random.nextDouble; math.sqrt(x*x + math.pow(y, 2))""")
should("""val x,y = util.Random.nextDouble; math.sqrt(x*x + math.pow(5, 2))""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x*x + y)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x + y*y)""")
should("""val x,y = 5f; math.sqrt(x*x + y*y)""")
should("""val x,y = util.Random.nextDouble; math.sqrt(25 + x*x)""")
should("""val x,y = util.Random.nextDouble; math.sqrt(x*x + 25)""")
should("""val x,y = util.Random.nextDouble; math.sqrt(2147395600 + x*x)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x*x + 24)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x*x + 26)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(26 + x*x)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x*x + 2147395601)""")
noLint("""val x,y = util.Random.nextDouble; math.sqrt(x*x + 2147395599)""")
}
@Test
def UseCbrt(): Unit = {
implicit val msg = "Use math.cbrt"
should("""val x = util.Random.nextDouble; math.pow(x, 1/3d)""")
should("""val x = util.Random.nextDouble; math.pow(x, 1/3f)""")
should("""val x = util.Random.nextDouble; math.pow(20*x+1, 1/3f)""")
noLint("""val x = util.Random.nextDouble; math.pow(20*x+1, 0.75)""")
noLint("""val x = util.Random.nextDouble; math.pow(20*x+1, 0.25)""")
}
@Test
def UseSqrt(): Unit = {
implicit val msg = "Use math.sqrt"
should("""val x = util.Random.nextDouble; math.pow(x, 1/2d)""")
should("""val x = util.Random.nextDouble; math.pow(x, 1/2f)""")
should("""val x = util.Random.nextDouble; math.pow(20*x+1, 0.5)""")
noLint("""val x = util.Random.nextDouble; math.pow(20*x+1, 0.75)""")
noLint("""val x = util.Random.nextDouble; math.pow(20*x+1, 0.25)""")
}
def SuspiciousPow(): Unit = {
implicit val msg = "This use of pow is suspicious"
// -> 1
should("""val x = util.Random.nextDouble; math.pow(x, 0d)""")
should("""val x = util.Random.nextDouble; math.pow(x, 0f)""")
should("""val x = util.Random.nextDouble; math.pow(x, 0)""")
// -> x
should("""val x = util.Random.nextDouble; math.pow(x, 1d)""")
should("""val x = util.Random.nextDouble; math.pow(x, 1f)""")
should("""val x = util.Random.nextDouble; math.pow(x, 1)""")
// -> NaN
should("""val x = util.Random.nextDouble; math.pow(x, Double.NaN)""")
should("""val x = util.Random.nextDouble; math.pow(x, Float.NaN)""")
// -> NaN, except 0 -> 0
should("""val x = util.Random.nextDouble; math.pow(x, Double.PositiveInfinity)""")
should("""val x = util.Random.nextDouble; math.pow(x, Float.PositiveInfinity)""")
// -> NaN, except 0 -> PositiveInfinity
should("""val x = util.Random.nextDouble; math.pow(x, Double.NegativeInfinity)""")
should("""val x = util.Random.nextDouble; math.pow(x, Float.NegativeInfinity)""")
}
@Test
def UseExp(): Unit = {
implicit val msg = "Use math.exp"
should("""{ val x = util.Random.nextDouble; math.pow(2.718281828459045, 1/x) }""")
should("""val x = util.Random.nextDouble; math.pow(math.E, x/2f)""")
should("""val x = util.Random.nextDouble; math.pow(math.E, 20*x+1)""")
noLint("""val x = util.Random.nextDouble; math.pow(2, 20*x+1)""")
noLint("""val x = util.Random.nextDouble; math.pow(3, 20*x+1)""")
}
@Test
def UseLog10(): Unit = {
implicit val msg = "Use math.log10"
should("""val x = util.Random.nextDouble; math.log(x)/math.log(10)""")
should("""val x = util.Random.nextDouble; math.log(x+2)/math.log(10)""")
noLint("""val x = util.Random.nextDouble; math.log(x)/math.log(11)""")
noLint("""val x = util.Random.nextDouble; math.log(x)/math.log(9)""")
}
@Test
def PossibleLossOfPrecision(): Unit = {
{
implicit val msg = "Literal cannot be represented exactly"
should("""val x = 0.5555555555555555555555555555""")
should("""val x = 0.5555555555555555555555555555+0.5""")
noLint("""val x = 0.5""")
noLint("""val x = 0.5+0.5""")
should("""val x = 0.555555555f""")
noLint("""val x = 0.555555555d""")
noLint("""val x = 0f""")
//TODO
/*
should("""val x = 0.1f""")
// Longest double
for (i <- 1 to 100) {
// These by definition generate actual floats, so there must be no lint
// If you were doing something else and this test fails... please report the number
noWarn(s"""val x = ${"%.1080f".format(util.Random.nextFloat)}""")
noWarn(s"""val x = ${"%.1080f".format(util.Random.nextDouble)}""")
noWarn(s"""val x = ${"%.1080f".format(util.Random.nextGaussian)}""")
}*/
}
}
@Test
def UnitImplicitOrdering(): Unit = {
implicit val msg = "Unit is returned here"
should("""List(1,2,3) maxBy { x => val res = x }""")
should("""List(1,2,3) minBy { x => println("hello"); val res = x }""")
should("""(1 to 3) maxBy { x => println("hello"); () }""")
should("""Array(1,2,3) maxBy { x => println("hello"); () }""")
noLint("""List(1,2,3) maxBy { x => println("hello"); x }""")
}
@Test
def UnsafeAbs(): Unit = {
implicit val msg = "unsafe use of abs"
should("""math.abs(util.Random.nextInt)""")
should("""val a = new util.Random; math.abs(a.nextInt)""")
should("""util.Random.nextInt.abs""")
should("""val a = new util.Random; a.nextInt.abs""")
should("""util.Random.nextLong.abs""")
noLint("""math.abs(-10)""")
noLint("""-10.abs""")
}
@Test
def TypeToType(): Unit = {
implicit val msg = "that is already of type"
should(""" "".toString """)
noLint(""" "5".toInt """)
should(""" val a = ""; a.toString """)
noLint(""" val a = 5; a.toString """)
should("""val a = 5; a.toInt""")
noLint("""val a = 5; a.toLong""")
noLint("""val a = 5; a.toShort""")
noLint("""val a = 5; a.toLong""")
noLint("""val a = 5; a.toDouble""")
should("""val a = 5L; a.toLong""")
noLint("""val a = 5L; a.toInt""")
should("""val a = 5.0; a.toDouble""")
noLint("""val a = 5.0; a.toFloat""")
should("""val a = 5.0f; a.toFloat""")
noLint("""val a = 5.0f; a.toDouble""")
should("""val a = List(1,2,3); a.toList""")
should("""val a = Seq(1,2,3); a.toSeq""")
should("""val a = Set(1,2,3); a.toSet""")
should("""val a = Vector(1,2,3); a.toVector""")
should("""val a = Array(1,2,3); a.toArray""")
should("""val a = collection.mutable.Seq(1,2,3); a.toSeq""")
noLint("""val a = List(1,2,3); a.toSeq""")
noLint("""val a = Seq(1,2,3); a.toList""")
noLint("""val a = Seq(1,2,3); a.toVector""")
noLint("""val a = Array(1,2,3); a.toSeq""")
noLint("""val a = collection.mutable.Set(1,2,3); a.toSet""")
noLint("""val a = collection.mutable.Map(1->2,3->4); a.toMap""")
should("""val a = "abc"; String.valueOf(a)""")
should("""class Wat { def toWat: Wat = new Wat; }; val w = new Wat; println(w.toWat)""")
//TODO: false positive
//noLint("""class Wat { def toWat(a: Int): Wat = new Wat; }; val w = new Wat; println(w.toWat(4))""")
noLint("""class Wat { def toWat: Int = 5; println(toWat) }""")
noLint("""class Wat { def toWat: Wat = new Wat; println(toWat) }""")
//TODO: false positive
/*noLint("""
object X { class Wat { def toWat: Y.Wat = new Y.Wat; } }
object Y { class Wat { def toWat: X.Wat = new X.Wat; } }
val xw = new X.Wat
val yw = new Y.Wat
println(xw.toWat)
println(yw.toWat)
""")*/
}
@Test
def InvalidStringFormat(): Unit = {
implicit val msg = "string format will throw"
should(""" { val a = 5; "%s %i".format("a", 1) } """) // wrong formatter %i
should(""" { val a = "%s %d".format("a") } """) // not enough params
should(""" { val a = "%s % d".format("a", 3) } """) // two spaces
noLint(""" { val a = 5; "%s %d".format("a", 1) } """)
should(""" String.format("%s %s %s", "a", "1") """)
should(""" printf("%s %s %s", "a", "1") """)
should(""" Console.printf("%s %s %s", "a", "1") """)
should(""" "dafdsfdsa".format(1) """)("percent sign")
should(""" "dafdsf%dsa".format(1,2) """)("percent sign")
}
@Test
def EmptyStringInterpolator(): Unit = {
implicit val msg = "string interpolation"
should(""" val a = s"wat" """)
should(""" println(s"wat") """)
should(""" val a = 5; println(s"wat" + a) """)
should(""" val a = "5"; val b = s"wat" + a """)
noLint(""" { val a = 5; s" $a " } """)
}
@Test
def UnlikelyToString(): Unit = {
implicit val msg = "into string is likely unintended"
should(""" Array("1").toString """)
should(""" val a = Array(1,2,3); println(a.toString) """)
should(""" def x(a: Array[Long]): String = a.toString """)
noLint(""" val a = Seq(1,2,3); println(a.toString) """)
should(""" val a = Array(1,2,3); println(String.valueOf(a)) """)
noLint(""" val a = 5; println(String.valueOf(a)) """)
}
@Test
def UnthrownException(): Unit = {
implicit val msg = "This exception was likely meant to be thrown here."
should(""" def a: Int = { println(""); new Exception(); 5 } """)
noLint(""" def a: Int = { println(""); throw new Exception(); 5 } """)
noLint(""" def a: Int = { println(""); return 4; 5 } """)
}
@Test
def SuspiciousMatches(): Unit = {
implicit var msg = "matches the entire string"
should(""" val a = util.Random.nextString(5) matches "^abc$" """)
should(""" val a = util.Random.nextString(5); val b = a matches (a+"$") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("fdsf$") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("^"+a) """)
noLint(""" val a = util.Random.nextString(5); a matches a """)
should(""" if(List("") forall { _ matches "^[A-Za-z0-9_]{1,20}$" }) println""")
msg = "be replaced by contains"
should(""" val a = util.Random.nextString(5); val b = a matches (".*ab.*") """)
should(""" val a = util.Random.nextString(5); val b = a matches (".*a\\.b.*") """)
should(""" val a = util.Random.nextString(5); val b = a matches (".*a[b]c.*") """)
noLint(""" val a = util.Random.nextString(5); val b = a matches (".*a[bc]d.*") """)
msg = "be replaced by startsWith"
should(""" val a = util.Random.nextString(5); val b = a matches ("ab.*") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("a[b].*") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("ab\\..*") """)
noLint(""" val a = util.Random.nextString(5); val b = a matches ("a.b.*") """)
msg = "be replaced by endsWith"
should(""" val a = util.Random.nextString(5); val b = a matches (".*ab") """)
should(""" val a = util.Random.nextString(5); val b = a matches (".*ab\\.") """)
noLint(""" val a = util.Random.nextString(5); val b = a matches (".*a.b") """)
should(""" val a = util.Random.nextString(5); val b = a matches (".*a[b]c") """)
msg = "be replaced by equals"
should(""" val a = util.Random.nextString(5); val b = a matches ("ab") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("a[b]c") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("af235ud09q43fc9hrcxkb") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("fdsf\\$") """)
should(""" val a = util.Random.nextString(5); val b = a matches ("fdsf\\\\$") """)
noLint(""" val a = util.Random.nextString(5); val b = a matches ("a[bc]d") """)
noLint(""" val a = util.Random.nextString(5); val b = a matches ("a.b") """)
}
@Test
def UseFindNotFilterHead(): Unit = {
implicit val msg = ".headOption can be replaced by "
should(""" val a = List(1,2,3); a.filter( _ >= 2).headOption """)
noLint(""" val a = List(1,2,3); a.filter( _ >= 2) """)
}
@Test
def RegexWarning(): Unit = {
implicit val msg = "RegexWarning"
should(""" "ffasd".replaceFirst("/$", "") """)
should(""" "ffasd".replaceAll("^/", "") """)
should(""" "ffasd".replaceFirst("\\.git$", "") """)
should(""" "ffasd".replaceFirst("^refs/heads/", "") """)
should(""" "ffasd".replaceAll("ff", "aa") """)
should(""" "ffasd".replaceAll("f[f]", "aa") """)
noLint(""" "ffasd".replaceAll("f[fa]", "aa") """)
noLint(""" "ffasd".replaceAll("ff", "a$0a") """)
should(""" "*+".r """)
should(""" "[".r """)
should("""
val a = "*+"
a.r
""")
should(""" "fsdfds".split("*+") """)
should(""" "fsdfds".replaceAll("*", "") """)
should("""
val a = "*"
java.util.regex.Pattern.compile(a)
""")
should(""" "|(|)".r """)
noLint(""" "3*[a]+".r """)
noLint(""" "[a-t]".r """)
noLint("""
val a = "4*a+"
a.r
""")
noLint(""" "3*[a]+%s".format("hello") """)
noLint("""
val a = "*"
java.util.regex.Pattern.compile("(pattern)"+a)
""")
}
@Test
def InvariantCondition(): Unit = {
implicit val msg = "This condition will"
should(""" val a = util.Random.nextInt; if(a > 5 && a < 4) "wat" else "" """)
should(""" case class A(b: Int); val c = A(util.Random.nextInt); if(c.b > 5 && c.b < 4) "wat" else "" """)
should(""" val a = util.Random.nextInt; if(a > 5 || a < 6) "wat" else "" """)
noLint(""" val a = util.Random.nextInt; if(a > 5 && a < 6) "k" else "" """)
noLint(""" val a = util.Random.nextInt; if(a < 5 && a < 4) "k, wat" else "" """)
noLint(""" val a = util.Random.nextInt; if(a > 5 && a > 6) "k" else "" """)
noLint(""" val a = util.Random.nextInt; if(a > 6 && a > 5) "k" else "" """)
noLint(""" val a = util.Random.nextInt; if(a < 5 || a > 6) "k" else "" """)
noLint(""" val a = util.Random.nextInt; if(a > 5 || a > 4) "k, wat" else "" """)
noLint(""" val a = util.Random.nextInt; if(a < 5 || a < 4) "k, wat" else "" """)
noLint(""" val a = util.Random.nextInt; if(a < 4 || a < 5) "k, wat" else "" """)
noLint(""" if(util.Random.nextInt > 5 && util.Random.nextInt < 4) "k" else "" """)
}
@Test
def IfDoWhile(): Unit = {
implicit val msg = "do-while"
should("""
val a = util.Random.nextInt;
if(a > 5) do {
println("hello");
println("world")
} while(a > 5)
""")
noLint("""
val a = util.Random.nextInt;
if(a > 6) do {
println("hello");
println("world")
} while(a > 5)
""")
// This one's actually about the same, but meh
noLint("""
val a = util.Random.nextInt;
if(a > 5) while(a > 5) {
println("hello");
println("world")
}
""")
}
@Test
def TransformNotMap(): Unit = {
implicit val msg = ".transform"
should("""
var a = collection.mutable.ListBuffer(1,2,3);
a = a.map{_ + 1}
""")
should("""
var a = Array("1","2","3");
a = a.map{_ + 1}
""")
noLint("""
var a = collection.mutable.ListBuffer(1,2,3);
a = a.map{_ + 1}.filter{_ > 1}
""")
//although this one could be flagged too... anything of the form a = a.(...).map
noLint("""
var a = collection.mutable.ListBuffer(1,2,3);
a = a.filter{_ > 1}.map{_ + 1}
""")
noLint("""
var a = collection.mutable.Set(1,2,3);
a = a.map{_ + 1}
""")
noLint("""
var a = Seq(1,2,3);
a = a.map{_ + 1}
""")
noLint("""
var a = List(1,2,3);
a = a.map{_ + 1}
""")
noLint("""
var a = Vector(1,2,3);
a = a.map{_ + 1}
""")
}
@Test
def UseCountNotFilterLength(): Unit = {
implicit val msg = /*"Use col*/".count(...) instead of "/*col.filter(...).*/
should("""
var a = Seq(1,2,3);
val b = a.filter{ _ > 1 }.length
""")
should("""
var a = Seq(1,2,3);
val b = a.filter{ _ > 1 }.size
""")
should("""
var a = Set(1,2,3);
val b = a.filter{ _ > 1 }.size
""")
should("""
var a = Array(1,2,3);
val b = a.filter{ _ > 1 }.length
""")
should("""
var a = "abc";
val b = a.filter{ _ > 'a' }.size
""")
should("""
var atte = Array(1,2,3);
val b = atte.filter{ _ > 1 }.size
""")("Use col.count(...) instead of col.filter(...).")
should("""
var aaaa = Array(1,2,3);
val b = aaaa.filter{ _ > 1 }.size
""")("Use col.count(...) instead of col.filter(...).")
should("""
var a = Array(1,2,3);
val b = a.filter{ _ > 1 }.size
""")("Use col.count(...) instead of col.filter(...).")
}
@Test
def UseExistsNotCountCompare(): Unit = {
implicit val msg = ".exists(...) instead of "
should("""
var a = Seq(1,2,3);
val b = a.count{ _ > 1 } > 0
""")
should("""
var a = Seq(1,2,3);
val b = a.count{ _ > 1 } >= 1
""")
should("""
var a = Seq(1,2,3);
val b = a.count{ _ > 1 } != 0
""")
should("""
var a = Set(1,2,3);
val b = a.count{ _ > 1 } != 0
""")
should("""
var a = collection.mutable.ListBuffer(1,2,3);
val b = a.count{ _ > 1 } != 0
""")
should("""
var a = Array(1,2,3);
val b = a.count{ _ > 1 } != 0
""")
should("""
var a = Option(1);
val b = a.count{ _ > 1 } != 0
""")
noLint("""
var a = Seq(1,2,3);
val b = a.count{ _ > 1 } == 0
""")
noLint("""
var a = Seq(1,2,3);
val b = a.count{ _ > 1 } >= 0
""")
}
@Test
def UseContainsNotExistsEquals(): Unit = {
implicit val msg = " instead of "
should("val b = 5; Set(1,2,3).exists(_ == b) ")
should("val b = 5; List(1,2,3).exists(a => a == b) ")
should("val b = 5; Set(1,2,3).exists(a => b == a) ")
should("""val b = "5"; Set("1","2","3").exists(a => b eq a) """)
should("Set(1,2,3).exists(a => a == 2) ")
should("Vector(1,2,3).exists(a => a == 2) ")
should("Array(1,2,3).exists(a => a == 2) ")
should("collection.mutable.ListBuffer(1,2,3).exists(a => a == 2) ")
// Exists not present on 2.11 Option
if (Properties.versionString.contains("2.10")) {
noLint("val b = 5; Option(2).exists(_ == b)")
noLint("Option(2).exists(_ == 2)")
} else {
should("val b = 5; Option(2).exists(_ == b)")
should("Option(2).exists(_ == 2)")
}
}
@Test
def UseQuantifierFuncNotFold(): Unit = {
implicit val msg = " can be replaced by "
should(""" val a = List(true, true, false); a.fold(true)((acc, n) => acc && !n) """)
should(""" val a = List(true, true, false); a.fold(true)((acc, n) => !n && acc) """)
should(""" val a = List(true, true, false); a./:(true)((acc, n) => acc && !n) """)
should(""" val a = Array.fill(10)(scala.util.Random.nextInt(20)); a.foldLeft(false)((acc, n) => acc || n > 5) """)
should(""" val a = Array.fill(10)(scala.util.Random.nextInt(20)); a.foldLeft(false)((acc, n) => n > 5 || acc) """)
should(""" val a = List(true, true, false); a.reduce((acc, n) => acc && !n) """)
should(""" val a = List(true, true, false); a.reduce((acc, n) => !n || acc) """)
should(""" val a = List(true, true, false); a.reduceLeft((acc, n) => !n || acc) """)
should(""" val a = Set(true, true, false); a.reduceLeft((acc, n) => !n || acc) """)
//Issue #42
noLint(""" class col { def foldLeft(a: Any)(b: Any) = a.toString+b.toString }; val a = new col; a.foldLeft(false)((acc: Boolean, n: Int) => n > 5 || acc) """)
}
@Test
def UseFuncNotFold(): Unit = {
{
should(""" val a = List(1, 2, 3); a.fold(0)((a, b) => a + b) """)(".sum instead of ")
should(""" val a = List(1, 2, 3); a./:(0)((a, b) => a + b) """)(".sum instead of ")
should(""" val a = List(1.0, 2.0, 3.0); a.foldLeft(2.0)((a, b) => b + a) """)(".sum + 2.0 instead of ")
should(""" val a = Array(1.0, 2.0, 3.0); a.foldLeft(2.0)((a, b) => b + a) """)(".sum + 2.0 instead of ")
should(""" val a = Set(1.0, 2.0, 3.0); a.foldLeft(2.0)((a, b) => b + a) """)(".sum + 2.0 instead of ")
noLint(""" val a = List(1.0, 2.0, 3.0); a.foldLeft(2.0)((a, b) => b + (a * 4)) """)
}
{
should(""" val a = List(1, 2, 3); a.fold(1)((a, b) => a * b) """)(".product instead of ")
should(""" val a = List(1, 2, 3); a./:(1)((a, b) => a * b) """)(".product instead of ")
should(""" val a = Array(1, 2, 3); a./:(1)((a, b) => a * b) """)(".product instead of ")
should(""" val a = Set(1, 2, 3); a./:(1)((a, b) => a * b) """)(".product instead of ")
should(""" val a = List(1.0, 2.0, 3.0); a.foldLeft(2d)((a, b) => b * a) """)(".product * 2.0 instead of ")
}
}
@Test
def UseFuncNotReduce(): Unit = {
{
implicit val msg = ".sum instead of "
should(""" val a = List(1, 2, 3); a.reduce((a, b) => a + b) """)
should(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b + a) """)
should(""" val a = Array(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b + a) """)
should(""" val a = Set(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b + a) """)
noLint(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b + (a * 2)) """)
}
{
implicit val msg = ".product instead of "
should(""" val a = List(1, 2, 3); a.reduce((a, b) => a * b) """)
should(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b * a) """)
should(""" val a = Array(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b * a) """)
should(""" val a = Set(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b * a) """)
noLint(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft((a, b) => b * (a * 2)) """)
}
{
implicit val msg = ".min instead of "
should(""" val a = List(1, 2, 3); a.reduce((a, b) => a min b) """)
should(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft(_ min _) """)
should(""" val a = Array(1.0, 2.0, 3.0); a.reduceLeft(_ min _) """)
should(""" val a = Set(1.0, 2.0, 3.0); a.reduceLeft(_ min _) """)
noLint(""" val a = List(1, 2, 3); a.reduce((a, b) => a min (b + 2)) """)
}
{
implicit val msg = ".max instead of "
should(""" val a = List(1, 2, 3); a.reduce((a, b) => a max b) """)
should(""" val a = List(1.0, 2.0, 3.0); a.reduceLeft(_ max _) """)
should(""" val a = Array(1.0, 2.0, 3.0); a.reduceLeft(_ max _) """)
should(""" val a = Set(1.0, 2.0, 3.0); a.reduceLeft(_ max _) """)
noLint(""" val a = List(1, 2, 3); a.reduce((a, b) => a max (b / 2)) """)
}
}
@Test
def CloseSourceFile(): Unit = {
implicit val msg = "You should close the file stream after use."
should("""scala.io.Source.fromFile("README.md").mkString""")
//should("""scala.io.Source.fromFile("README.md")""")
noLint("""val a = scala.io.Source.fromFile("README.md"); a.mkString(""); a.close()""")
noLint("""def fromFile(s: String) = s; fromFile("aaa").mkString("")""")
}
@Test
def JavaConverters(): Unit = {
implicit val msg = "Consider using the explicit collection.JavaConverters"
should("import scala.collection.JavaConversions._;")
}
@Test
def ContainsTypeMismatch(): Unit = {
implicit val msg = "will probably return false"
should("""val x = List(4); x.contains("foo")""")
// Contains not present on 2.10 Option
if (Properties.versionString.contains("2.11")) {
//Issue #45
should("""val x = Some(1); x.contains("foo")""")
should("""val x = Some("foo"); x.contains(1)""")
noLint("""val x = Some("foo"); x.contains("ab")""")
//Issue #46
should("""val foo = Some(4); val bar = Some("bar"); foo.exists(str => bar.contains(str))""")
should("""val foo = Some("foo"); val bar = Some(4); foo.exists(str => bar.contains(str))""")
noLint("""val foo = Some("foo"); val bar = Some("bar"); foo.exists(str => bar.contains(str))""")
should("""val foo = Some(4); val bar = Some("bar"); foo.exists(bar.contains(_))""")
should("""val foo = Some("foo"); val bar = Some(4); foo.exists(bar.contains(_))""")
noLint("""val foo = Some("foo"); val bar = Some("bar"); foo.exists(bar.contains(_))""")
//TODO: false negatives
//should("""val foo = Some(4); val bar = Some("bar"); foo.exists(bar.contains)""")
//should("""val foo = Some("foo"); val bar = Some(4); foo.exists(bar.contains)""")
noLint("""val foo = Some("foo"); val bar = Some("bar"); foo.exists(bar.contains)""")
}
noLint("""val x = List(scala.util.Random.nextInt); x.contains(5)""")
// Number weak type eq
noLint("""val x = List(4L, 5L); x.contains(5)""")
//Issue #46
should("""val foo = List(4); val bar = List("bar"); foo.exists(str => bar.contains(str))""")
noLint("""val foo = List("foo"); val bar = List("bar"); foo.exists(str => bar.contains(str))""")
should("""val foo = List(4); val bar = List("bar"); foo.exists(bar.contains(_))""")
noLint("""val foo = List("foo"); val bar = List("bar"); foo.exists(bar.contains(_))""")
//TODO: false negative
//should("""val foo = List(4); val bar = List("bar"); foo.exists(bar.contains)""")
noLint("""val foo = List("foo"); val bar = List("bar"); foo.exists(bar.contains)""")
// Set and Map have type-safe contains methods so we don't want to warn on those.
noLint("""val x = Set(scala.util.Random.nextInt); x.contains(3)""")
noLint("""val x = Map(4 -> 5); x.contains(3)""")
}
@Test
def UseConditionDirectly(): Unit = {
implicit val msg = "Remove the if expression and use the "
should("""
val a,b = util.Random.nextInt
if(a == b && b > 5)
true
else
false""")
should("""
val a,b = util.Random.nextInt
if(a != b && b > 5)
false
else
true""")
noLint("""
val a,b = util.Random.nextInt
if(a != b && b > 5)
1+1
else
true""")
}
@Test
def DuplicateIfBranches(): Unit = {
implicit val msg = "If statement branches have the same structure"
should("""
val a,b = 10
if(b > 4)
(1+1,a)
else
(2,a)""")
should("""
val a,b = 4
if(b > 4)
(1+1,a)
else if(b > 7)
(2,a)""")
noLint("""
val a,b = scala.util.Random.nextInt
if(b > 4)
(3,a)
else if(b > 7)
(2,a)""")
}
@Test
def IdenticalCaseBodies(): Unit = {
implicit val msg = "neighbouring cases are identical"
should("""
val a = 7
a match {
case 3 => println("hello")
case 4 => println("hello")
case 5 => println("hello")
case _ => println("how low")
}""")
should("""
val a = 7
import scala.annotation.switch
(a: @switch) match {
case 3 => println("hello")
case 4 => println("hello")
case 5 => println("hello")
case _ => println("how low")
}""")
noLint("""
val a = 7
a match {
case 3 => println("hello1")
case 4 => println("hello2")
case 5 => println("hello3")
case _ => println("how low")
}""")
noLint("""
val a = 7
a match {
case 3 => println("hello")
case 4 if util.Random.nextBoolean => println("hello")
case 5 if util.Random.nextBoolean => println("hello")
case 6 if util.Random.nextBoolean => println("hello")
case 7 => println("hello")
case _ => println("how low")
}""")
// Test fails in later versions because this future is deprecated
if (Properties.versionString.contains("2.10")) {
noLint("""
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.util.{Failure,Success}
future { 1+1 } andThen { case Success(a) => println("win") case Failure(s) => println("fail") }
""")
}
}
@Test
def PatternMatchConstant(): Unit = {
implicit val msg = "Pattern matching on a constant value"
should("""
5 match {
case 3 => "hello"
case _ => "hi"
}""")
//TODO: should("""val a = 5; a match { case 3 => "hello"; case _ => "hi" } """)
noLint("""
val a = 5
a match {
case 3 => "hello";