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

Merged
merged 13 commits into from
Jun 1, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,27 @@ 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 =
doc.tokenList
.trailing(token)
.takeWhile(!_.is[Token.RightBracket])
.collectFirst { case Token.Ident("Matchable") => }
.isDefined

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 MatchableDisableSyntax {
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
}
}
}