From 751cc2ffd0f2bac65ccc79565deb20f64b08cbd5 Mon Sep 17 00:00:00 2001 From: Matt Bovel Date: Wed, 1 May 2024 12:02:40 +0200 Subject: [PATCH] Add warning for synchronized calls in value classes Co-Authored-By: Yoonjae Jeon <18438185+nox213@users.noreply.github.com> --- compiler/src/dotty/tools/dotc/typer/RefChecks.scala | 4 +++- tests/warn/i17493.check | 11 +++++++++++ tests/warn/i17493.scala | 4 ++++ 3 files changed, 18 insertions(+), 1 deletion(-) create mode 100644 tests/warn/i17493.check create mode 100644 tests/warn/i17493.scala diff --git a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala index cdfd137e5661..09ed2d91a788 100644 --- a/compiler/src/dotty/tools/dotc/typer/RefChecks.scala +++ b/compiler/src/dotty/tools/dotc/typer/RefChecks.scala @@ -1239,7 +1239,9 @@ object RefChecks { def checkAnyRefMethodCall(tree: Tree)(using Context) = if tree.symbol.exists && defn.topClasses.contains(tree.symbol.owner) - && (!ctx.owner.enclosingClass.exists || ctx.owner.enclosingClass.isPackageObject) then + && (!ctx.owner.enclosingClass.exists + || ctx.owner.enclosingClass.isPackageObject + || ctx.owner.enclosingClass.isValueClass) then report.warning(UnqualifiedCallToAnyRefMethod(tree, tree.symbol), tree) } diff --git a/tests/warn/i17493.check b/tests/warn/i17493.check new file mode 100644 index 000000000000..af5a0b8ad115 --- /dev/null +++ b/tests/warn/i17493.check @@ -0,0 +1,11 @@ +-- [E181] Potential Issue Warning: tests/warn/i17493.scala:3:11 -------------------------------------------------------- +3 | def g = synchronized { println("hello, world") } // warn + | ^^^^^^^^^^^^ + | Suspicious top-level unqualified call to synchronized + |--------------------------------------------------------------------------------------------------------------------- + | Explanation (enabled by `-explain`) + |- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + | Top-level unqualified calls to AnyRef or Any methods such as synchronized are + | resolved to calls on Predef or on imported methods. This might not be what + | you intended. + --------------------------------------------------------------------------------------------------------------------- diff --git a/tests/warn/i17493.scala b/tests/warn/i17493.scala new file mode 100644 index 000000000000..74f2039b81b5 --- /dev/null +++ b/tests/warn/i17493.scala @@ -0,0 +1,4 @@ +//> using options -explain + class A(val s: String) extends AnyVal { + def g = synchronized { println("hello, world") } // warn + }