diff --git a/compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala b/compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala index a2a5aaeafaff..37a675f6e35b 100644 --- a/compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala +++ b/compiler/src/dotty/tools/dotc/reporting/ErrorMessageID.scala @@ -166,7 +166,8 @@ enum ErrorMessageID extends java.lang.Enum[ErrorMessageID] { TypeSpliceInValPatternID, ModifierNotAllowedForDefinitionID, CannotExtendJavaEnumID, - InvalidReferenceInImplicitNotFoundAnnotationID + InvalidReferenceInImplicitNotFoundAnnotationID, + TraitMayNotDefineNativeMethodID def errorNumber = ordinal - 2 } diff --git a/compiler/src/dotty/tools/dotc/reporting/messages.scala b/compiler/src/dotty/tools/dotc/reporting/messages.scala index d0dd13e93397..f4c46317ab98 100644 --- a/compiler/src/dotty/tools/dotc/reporting/messages.scala +++ b/compiler/src/dotty/tools/dotc/reporting/messages.scala @@ -1480,6 +1480,13 @@ import ast.tpd def explain = "" } + class TraitMayNotDefineNativeMethod(sym: Symbol)( + implicit ctx: Context) + extends SyntaxMsg(TraitMayNotDefineNativeMethodID) { + def msg = em"""A trait cannot define a ${hl("@native")} method.""" + def explain = "" + } + class OnlyClassesCanHaveDeclaredButUndefinedMembers(sym: Symbol)( implicit ctx: Context) extends SyntaxMsg(OnlyClassesCanHaveDeclaredButUndefinedMembersID) { diff --git a/compiler/src/dotty/tools/dotc/typer/Checking.scala b/compiler/src/dotty/tools/dotc/typer/Checking.scala index a9573ff9e48b..ad0d7406369c 100644 --- a/compiler/src/dotty/tools/dotc/typer/Checking.scala +++ b/compiler/src/dotty/tools/dotc/typer/Checking.scala @@ -467,6 +467,8 @@ object Checking { if (sym.hasAnnotation(defn.NativeAnnot)) { if (!sym.is(Deferred)) fail(NativeMembersMayNotHaveImplementation(sym)) + else if(sym.owner.is(Trait)) + fail(TraitMayNotDefineNativeMethod(sym)) } else if (sym.is(Deferred, butNot = Param) && !sym.isType && !sym.isSelfSym) { if (!sym.owner.isClass || sym.owner.is(Module) || sym.owner.isAnonymousClass) diff --git a/tests/neg/i9432.check b/tests/neg/i9432.check new file mode 100644 index 000000000000..0419a9d9a27b --- /dev/null +++ b/tests/neg/i9432.check @@ -0,0 +1,4 @@ +-- [E159] Syntax Error: tests/neg/i9432.scala:2:14 --------------------------------------------------------------------- +2 | @native def foo(x: Int): Unit // error + | ^ + | A trait cannot define a @native method. diff --git a/tests/neg/i9432.scala b/tests/neg/i9432.scala new file mode 100644 index 000000000000..5dbbb3f769f2 --- /dev/null +++ b/tests/neg/i9432.scala @@ -0,0 +1,3 @@ +trait CLibrary { + @native def foo(x: Int): Unit // error +}