From 4e34f948fdcab8d2a67a2d9d5ac3ff1b75d944f9 Mon Sep 17 00:00:00 2001 From: Martin Odersky Date: Tue, 12 Jan 2021 17:54:51 +0100 Subject: [PATCH] Better error message if derived trait does not have companion Fixes #11072 --- compiler/src/dotty/tools/dotc/typer/Deriving.scala | 6 ++++-- tests/neg/i11072.check | 4 ++++ tests/neg/i11072.scala | 5 +++++ 3 files changed, 13 insertions(+), 2 deletions(-) create mode 100644 tests/neg/i11072.check create mode 100644 tests/neg/i11072.scala diff --git a/compiler/src/dotty/tools/dotc/typer/Deriving.scala b/compiler/src/dotty/tools/dotc/typer/Deriving.scala index 1218d2c10094..269924c21114 100644 --- a/compiler/src/dotty/tools/dotc/typer/Deriving.scala +++ b/compiler/src/dotty/tools/dotc/typer/Deriving.scala @@ -291,9 +291,11 @@ trait Deriving { companionRef(tp.underlying) } val resultType = instantiated(sym.info) - val module = untpd.ref(companionRef(resultType)).withSpan(sym.span) + val companion = companionRef(resultType) + val module = untpd.ref(companion).withSpan(sym.span) val rhs = untpd.Select(module, nme.derived) - typed(rhs, resultType) + if companion.termSymbol.exists then typed(rhs, resultType) + else errorTree(rhs, em"$resultType cannot be derived since ${resultType.typeSymbol} has no companion object") end typeclassInstance def syntheticDef(sym: Symbol): Tree = inContext(ctx.fresh.setOwner(sym).setNewScope) { diff --git a/tests/neg/i11072.check b/tests/neg/i11072.check new file mode 100644 index 000000000000..7f1e1d503c67 --- /dev/null +++ b/tests/neg/i11072.check @@ -0,0 +1,4 @@ +-- Error: tests/neg/i11072.scala:3:17 ---------------------------------------------------------------------------------- +3 |enum Foo derives Sealed { // error + | ^ + | Sealed[Foo] cannot be derived since trait Sealed has no companion object diff --git a/tests/neg/i11072.scala b/tests/neg/i11072.scala new file mode 100644 index 000000000000..5df4cfbfb3aa --- /dev/null +++ b/tests/neg/i11072.scala @@ -0,0 +1,5 @@ +trait Sealed[A] + +enum Foo derives Sealed { // error + case A, B, C +} \ No newline at end of file