Skip to content

Commit 773023b

Browse files
committed
Require string literals as target name arguments
1 parent d4fca54 commit 773023b

File tree

3 files changed

+19
-1
lines changed

3 files changed

+19
-1
lines changed

compiler/src/dotty/tools/dotc/typer/Checking.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1073,6 +1073,19 @@ trait Checking {
10731073
if !Inliner.inInlineMethod && !ctx.isInlineContext then
10741074
report.error(em"$what can only be used in an inline method", pos)
10751075

1076+
/** Check arguments of compiler-defined annotations */
1077+
def checkAnnotArgs(tree: Tree)(using Context): tree.type =
1078+
val cls = Annotations.annotClass(tree)
1079+
def needsStringLit(arg: Tree) =
1080+
report.error(em"@${cls.name} needs a string literal as argument", arg.srcPos)
1081+
tree match
1082+
case Apply(tycon, arg :: Nil) if cls == defn.TargetNameAnnot =>
1083+
arg match
1084+
case Literal(_) => // ok
1085+
case _ => needsStringLit(arg)
1086+
case _ =>
1087+
tree
1088+
10761089
/** 1. Check that all case classes that extend `scala.reflect.Enum` are `enum` cases
10771090
* 2. Check that parameterised `enum` cases do not extend java.lang.Enum.
10781091
* 3. Check that only a static `enum` base class can extend java.lang.Enum.
@@ -1235,6 +1248,7 @@ trait NoChecking extends ReChecking {
12351248
override def checkImplicitConversionDefOK(sym: Symbol)(using Context): Unit = ()
12361249
override def checkImplicitConversionUseOK(tree: Tree)(using Context): Unit = ()
12371250
override def checkFeasibleParent(tp: Type, pos: SrcPos, where: => String = "")(using Context): Type = tp
1251+
override def checkAnnotArgs(tree: Tree)(using Context): tree.type = tree
12381252
override def checkInlineConformant(tpt: Tree, tree: Tree, sym: Symbol)(using Context): Unit = ()
12391253
override def checkNoTargetNameConflict(stats: List[Tree])(using Context): Unit = ()
12401254
override def checkParentCall(call: Tree, caller: ClassSymbol)(using Context): Unit = ()

compiler/src/dotty/tools/dotc/typer/Typer.scala

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1920,7 +1920,7 @@ class Typer extends Namer
19201920
}
19211921

19221922
def typedAnnotation(annot: untpd.Tree)(using Context): Tree =
1923-
typed(annot, defn.AnnotationClass.typeRef)
1923+
checkAnnotArgs(typed(annot, defn.AnnotationClass.typeRef))
19241924

19251925
def typedValDef(vdef: untpd.ValDef, sym: Symbol)(using Context): Tree = {
19261926
val ValDef(name, tpt, _) = vdef

tests/neg/targetName-illegal.scala

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import annotation.targetName
2+
3+
val s = "x"
4+
@targetName(s) def y = 1 // error

0 commit comments

Comments
 (0)