Skip to content

DisableSyntax: Add special case for asInstanceOf[Matchable] in Scala 3 #2245

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,37 @@ final class DisableSyntax(config: DisableSyntaxConfig)
Diagnostic("noXml", "xml literals should be avoided", token.pos)
case token: Token.Ident
if token.value == "asInstanceOf" && config.noAsInstanceOf =>
Diagnostic(
"asInstanceOf",
"asInstanceOf casts are disabled, use pattern matching instead",
token.pos
)
val isMatchableCast = {
val tokenIndex = doc.tree.tokens.indexOf(token)
if (tokenIndex >= 0) {
val subsequentTokens = doc.tree.tokens.drop(tokenIndex + 1)
val nonSpaceTokens = subsequentTokens.filterNot(_.is[Token.Space])

nonSpaceTokens.take(3).toList match {
case (_: Token.LeftBracket) ::
(ident: Token.Ident) ::
(_: Token.RightBracket) :: Nil
if ident.value == "Matchable" =>
true
case _ => false
}
} else false
}

if (isMatchableCast) {
Diagnostic(
"asInstanceOfMatchable",
"asInstanceOf[Matchable] is used here to enable pattern matching on Any. " +
"Consider using the .asMatchable extension method instead for better readability.",
token.pos
)
} else {
Diagnostic(
"asInstanceOf",
"asInstanceOf casts are disabled, use pattern matching instead",
token.pos
)
}
case token: Token.Ident
if token.value == "isInstanceOf" && config.noIsInstanceOf =>
Diagnostic(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
rules = DisableSyntax
DisableSyntax.noAsInstanceOf = true
*/
package test.disableSyntax

object MatchableAsInstanceOf {
class Example {
override def equals(obj: Any): Boolean =
obj.asInstanceOf[Matchable] match { /* assert: DisableSyntax.asInstanceOfMatchable
^^^^^^^^^^^^
asInstanceOf[Matchable] is used here to enable pattern matching on Any. Consider using the .asMatchable extension method instead for better readability.
*/
case that: Example => true
case _ => false
}
}

def regularCast(x: Any): String =
x.asInstanceOf[String] /* assert: DisableSyntax.asInstanceOf
^^^^^^^^^^^^
asInstanceOf casts are disabled, use pattern matching instead
*/

// whitespace between tokens
class WhitespaceExample {
override def equals(obj: Any): Boolean =
obj.asInstanceOf [ Matchable ] match { /* assert: DisableSyntax.asInstanceOfMatchable
^^^^^^^^^^^^
asInstanceOf[Matchable] is used here to enable pattern matching on Any. Consider using the .asMatchable extension method instead for better readability.
*/
case _ => true
}
}
}