diff --git a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala index 7bf83d548c97..9ed19c93d1ba 100644 --- a/compiler/src/dotty/tools/dotc/ast/MainProxies.scala +++ b/compiler/src/dotty/tools/dotc/ast/MainProxies.scala @@ -98,17 +98,17 @@ object MainProxies { val body = Try(call, handler :: Nil, EmptyTree) val mainArg = ValDef(nme.args, TypeTree(defn.ArrayType.appliedTo(defn.StringType)), EmptyTree) .withFlags(Param) - /** Replace typed `Ident`s that have been typed with a TypeSplice with the reference to the symbol. - * The annotations will be retype-checked in another scope that may not have the same imports. + + /** This context is used to create the `TypeSplices` wrapping annotations + * below. These should have `mainFun` as their owner (and not the + * enclosing package class that we would get otherwise) so that + * subsequent owner changes (for example in `Typer.typedTypedSplice`) are + * correct. See #22364 and associated tests. */ - def insertTypeSplices = new TreeMap { - override def transform(tree: Tree)(using Context): Tree = tree match - case tree: tpd.Ident @unchecked => TypedSplice(tree) - case tree => super.transform(tree) - } + val annotsCtx = ctx.fresh.setOwner(mainFun) val annots = mainFun.annotations .filterNot(_.matches(defn.MainAnnot)) - .map(annot => insertTypeSplices.transform(annot.tree)) + .map(annot => TypedSplice(annot.tree)(using annotsCtx)) val mainMeth = DefDef(nme.main, (mainArg :: Nil) :: Nil, TypeTree(defn.UnitType), body) .withFlags(JavaStatic | Synthetic) .withAnnotations(annots) diff --git a/tests/pos/annot-main-22364.scala b/tests/pos/annot-main-22364.scala new file mode 100644 index 000000000000..205589b525bc --- /dev/null +++ b/tests/pos/annot-main-22364.scala @@ -0,0 +1,5 @@ +def id[T](x: T): T = x + +class ann(x: Int) extends annotation.Annotation + +@ann(id(22)) @main def blop = () diff --git a/tests/pos/annot-main-22364b.scala b/tests/pos/annot-main-22364b.scala new file mode 100644 index 000000000000..c4e3067d7325 --- /dev/null +++ b/tests/pos/annot-main-22364b.scala @@ -0,0 +1,6 @@ +import util.chaining.* + +class ann(x: Int = 1, y: Int) extends annotation.Annotation + +@ann(y = 22.tap(println)) @main def blop = () + diff --git a/tests/pos/annot-main-22364c.scala b/tests/pos/annot-main-22364c.scala new file mode 100644 index 000000000000..53a6abe1a56b --- /dev/null +++ b/tests/pos/annot-main-22364c.scala @@ -0,0 +1,10 @@ +package p + +object P1: + class ann(x: Int) extends annotation.Annotation + +object P2: + def id[T](x: T): T = x + +object P3: + @P1.ann(P2.id(22)) @main def blop = ()