Skip to content

Commit 1420853

Browse files
committed
Fix #2760: Support defaults in Java annotations parsed from sources
This commit is enough to get the added testcase to compile but not to run (it crashes with a NoSuchFieldError), this is fixed in the next commit.
1 parent 9229f9f commit 1420853

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

compiler/src/dotty/tools/dotc/parsing/JavaParsers.scala

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,8 +132,8 @@ object JavaParsers {
132132

133133
def makeSyntheticParam(count: Int, tpt: Tree): ValDef =
134134
makeParam(nme.syntheticParamName(count), tpt)
135-
def makeParam(name: TermName, tpt: Tree): ValDef =
136-
ValDef(name, tpt, EmptyTree).withMods(Modifiers(Flags.JavaDefined | Flags.ParamAccessor))
135+
def makeParam(name: TermName, tpt: Tree, defaultValue: Tree = EmptyTree): ValDef =
136+
ValDef(name, tpt, defaultValue).withMods(Modifiers(Flags.JavaDefined | Flags.ParamAccessor))
137137

138138
def makeConstructor(formals: List[Tree], tparams: List[TypeDef], flags: FlagSet = Flags.JavaDefined) = {
139139
val vparams = formals.zipWithIndex.map { case (p, i) => makeSyntheticParam(i + 1, p) }
@@ -772,7 +772,18 @@ object JavaParsers {
772772
val name = identForType()
773773
val (statics, body) = typeBody(AT, name, List())
774774
val constructorParams = body.collect {
775-
case dd: DefDef => makeParam(dd.name, dd.tpt)
775+
case dd: DefDef =>
776+
val hasDefault =
777+
dd.mods.annotations.exists {
778+
case Apply(Select(New(Select(_, tpnme.AnnotationDefaultATTR)), nme.CONSTRUCTOR), Nil) =>
779+
true
780+
case _ =>
781+
false
782+
}
783+
// If the annotation has a default value we don't need to parse it, providing
784+
// any value at all is enough to typecheck usages of annotations correctly.
785+
val defaultParam = if (hasDefault) unimplementedExpr else EmptyTree
786+
makeParam(dd.name, dd.tpt, defaultParam)
776787
}
777788
val constr = DefDef(nme.CONSTRUCTOR,
778789
List(), List(constructorParams), TypeTree(), EmptyTree).withMods(Modifiers(Flags.JavaDefined))

tests/run/i2760/Fork.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import java.lang.annotation.*;
2+
3+
@Retention(RetentionPolicy.RUNTIME)
4+
public @interface Fork {
5+
int value() default -1;
6+
int warmups() default -1;
7+
}

tests/run/i2760/Test.scala

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
@Fork(value = 16) class HasFork
2+
3+
object Test {
4+
def main(args: Array[String]): Unit = {
5+
val fork = classOf[HasFork].getAnnotation(classOf[Fork])
6+
assert(fork.value == 16, s"fork.value is ${fork.value} but should have been 16")
7+
assert(fork.warmups == -1, s"fork.warmups is ${fork.warmups} but should have been -1")
8+
}
9+
}

0 commit comments

Comments
 (0)