Skip to content

Commit 2844b2d

Browse files
authored
Merge pull request scalacenter#2245 from subhramit/matchable-as-instanceof
`DisableSyntax`: Add special case for `asInstanceOf[Matchable]` in Scala 3
2 parents 1a85cf8 + ced7c36 commit 2844b2d

File tree

2 files changed

+56
-5
lines changed

2 files changed

+56
-5
lines changed

scalafix-rules/src/main/scala/scalafix/internal/rule/DisableSyntax.scala

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -113,11 +113,27 @@ final class DisableSyntax(config: DisableSyntaxConfig)
113113
Diagnostic("noXml", "xml literals should be avoided", token.pos)
114114
case token: Token.Ident
115115
if token.value == "asInstanceOf" && config.noAsInstanceOf =>
116-
Diagnostic(
117-
"asInstanceOf",
118-
"asInstanceOf casts are disabled, use pattern matching instead",
119-
token.pos
120-
)
116+
val isMatchableCast =
117+
doc.tokenList
118+
.trailing(token)
119+
.takeWhile(!_.is[Token.RightBracket])
120+
.collectFirst { case Token.Ident("Matchable") => }
121+
.isDefined
122+
123+
if (isMatchableCast) {
124+
Diagnostic(
125+
"asInstanceOfMatchable",
126+
"asInstanceOf[Matchable] is used here to enable pattern matching on Any. " +
127+
"Consider using the .asMatchable extension method instead for better readability.",
128+
token.pos
129+
)
130+
} else {
131+
Diagnostic(
132+
"asInstanceOf",
133+
"asInstanceOf casts are disabled, use pattern matching instead",
134+
token.pos
135+
)
136+
}
121137
case token: Token.Ident
122138
if token.value == "isInstanceOf" && config.noIsInstanceOf =>
123139
Diagnostic(
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
rules = DisableSyntax
3+
DisableSyntax.noAsInstanceOf = true
4+
*/
5+
package test.disableSyntax
6+
7+
object MatchableDisableSyntax {
8+
class Example {
9+
override def equals(obj: Any): Boolean =
10+
obj.asInstanceOf[Matchable] match { /* assert: DisableSyntax.asInstanceOfMatchable
11+
^^^^^^^^^^^^
12+
asInstanceOf[Matchable] is used here to enable pattern matching on Any. Consider using the .asMatchable extension method instead for better readability.
13+
*/
14+
case that: Example => true
15+
case _ => false
16+
}
17+
}
18+
19+
def regularCast(x: Any): String =
20+
x.asInstanceOf[String] /* assert: DisableSyntax.asInstanceOf
21+
^^^^^^^^^^^^
22+
asInstanceOf casts are disabled, use pattern matching instead
23+
*/
24+
25+
// whitespace between tokens
26+
class WhitespaceExample {
27+
override def equals(obj: Any): Boolean =
28+
obj.asInstanceOf [ Matchable ] match { /* assert: DisableSyntax.asInstanceOfMatchable
29+
^^^^^^^^^^^^
30+
asInstanceOf[Matchable] is used here to enable pattern matching on Any. Consider using the .asMatchable extension method instead for better readability.
31+
*/
32+
case _ => true
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)