Skip to content

Overriding final method using MacroAnnotations #18825

Closed
@hamzaremmal

Description

@hamzaremmal

Compiler version

3.3.1

Minimized code

Macro_1.scala

import scala.annotation.experimental
import scala.annotation.MacroAnnotation
import scala.quoted.*

@experimental
class toString extends MacroAnnotation :
    def transform(using Quotes)(tree: quotes.reflect.Definition): List[quotes.reflect.Definition] =
        import quotes.reflect.*
        tree match
            case ClassDef(name, ctr, parents, self, body) =>
                val cls = tree.symbol
                val toStringSym = Symbol.requiredMethod("java.lang.Object.toString")
                val toStringOverrideSym = Symbol.newMethod(cls, "toString", toStringSym.info, Flags.Override, Symbol.noSymbol)
                val toStringDef = DefDef(toStringOverrideSym, _ => Some(Literal(StringConstant("Hello from macro"))))
                val newClassDef = ClassDef.copy(tree)(name, ctr, parents, self, toStringDef :: body)
                List(newClassDef)
            case _ =>
                report.error("@toString can only be annotated on class definitions")
                tree :: Nil

Test_2.scala

import annotation.experimental

class Foo :
    final override def toString(): String = "Hello"

@experimental
@toString
class AFoo extends Foo //:
    //override def toString(): String = "Hello from macro"

@experimental
@main def run =
    println(new AFoo().toString)

Output

It compiles and it crashes when running the code

Expectation

It should not compile

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions