Skip to content

Commit a61c12e

Browse files
authored
Fix copy of annotation on @main methods (#22582)
Fixes #22364. See #13858 (comment).
2 parents 37206cc + 15c4e51 commit a61c12e

File tree

4 files changed

+29
-8
lines changed

4 files changed

+29
-8
lines changed

compiler/src/dotty/tools/dotc/ast/MainProxies.scala

+8-8
Original file line numberDiff line numberDiff line change
@@ -98,17 +98,17 @@ object MainProxies {
9898
val body = Try(call, handler :: Nil, EmptyTree)
9999
val mainArg = ValDef(nme.args, TypeTree(defn.ArrayType.appliedTo(defn.StringType)), EmptyTree)
100100
.withFlags(Param)
101-
/** Replace typed `Ident`s that have been typed with a TypeSplice with the reference to the symbol.
102-
* The annotations will be retype-checked in another scope that may not have the same imports.
101+
102+
/** This context is used to create the `TypeSplices` wrapping annotations
103+
* below. These should have `mainFun` as their owner (and not the
104+
* enclosing package class that we would get otherwise) so that
105+
* subsequent owner changes (for example in `Typer.typedTypedSplice`) are
106+
* correct. See #22364 and associated tests.
103107
*/
104-
def insertTypeSplices = new TreeMap {
105-
override def transform(tree: Tree)(using Context): Tree = tree match
106-
case tree: tpd.Ident @unchecked => TypedSplice(tree)
107-
case tree => super.transform(tree)
108-
}
108+
val annotsCtx = ctx.fresh.setOwner(mainFun)
109109
val annots = mainFun.annotations
110110
.filterNot(_.matches(defn.MainAnnot))
111-
.map(annot => insertTypeSplices.transform(annot.tree))
111+
.map(annot => TypedSplice(annot.tree)(using annotsCtx))
112112
val mainMeth = DefDef(nme.main, (mainArg :: Nil) :: Nil, TypeTree(defn.UnitType), body)
113113
.withFlags(JavaStatic | Synthetic)
114114
.withAnnotations(annots)

tests/pos/annot-main-22364.scala

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
def id[T](x: T): T = x
2+
3+
class ann(x: Int) extends annotation.Annotation
4+
5+
@ann(id(22)) @main def blop = ()

tests/pos/annot-main-22364b.scala

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import util.chaining.*
2+
3+
class ann(x: Int = 1, y: Int) extends annotation.Annotation
4+
5+
@ann(y = 22.tap(println)) @main def blop = ()
6+

tests/pos/annot-main-22364c.scala

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
package p
2+
3+
object P1:
4+
class ann(x: Int) extends annotation.Annotation
5+
6+
object P2:
7+
def id[T](x: T): T = x
8+
9+
object P3:
10+
@P1.ann(P2.id(22)) @main def blop = ()

0 commit comments

Comments
 (0)