|
| 1 | +package dotty.tools.dotc |
| 2 | +package transform |
| 3 | + |
| 4 | +import core._ |
| 5 | +import ast.tpd._ |
| 6 | +import Contexts._ |
| 7 | +import MegaPhase._ |
| 8 | +import Annotations._ |
| 9 | +import Symbols.defn |
| 10 | +import Constants._ |
| 11 | +import Types._ |
| 12 | +import Decorators._ |
| 13 | + |
| 14 | +class RepeatableAnnotations extends MiniPhase: |
| 15 | + override def phaseName = "repeatableAnnotations" |
| 16 | + |
| 17 | + override def transformTypeDef(tree: TypeDef)(using Context): Tree = transformDef(tree) |
| 18 | + override def transformValDef(tree: ValDef)(using Context): Tree = transformDef(tree) |
| 19 | + override def transformDefDef(tree: DefDef)(using Context): Tree = transformDef(tree) |
| 20 | + |
| 21 | + private def transformDef(tree: DefTree)(using Context) = |
| 22 | + val annotations = tree.symbol.annotations |
| 23 | + if (!annotations.isEmpty) then |
| 24 | + tree.symbol.annotations = aggregateAnnotations(tree.symbol.annotations) |
| 25 | + tree |
| 26 | + |
| 27 | + private def aggregateAnnotations(annotations: Seq[Annotation])(using Context): List[Annotation] = |
| 28 | + val annsByType = annotations.groupBy(_.symbol) |
| 29 | + annsByType.flatMap { |
| 30 | + case (_, a :: Nil) => a :: Nil |
| 31 | + case (sym, anns) if sym.derivesFrom(defn.ClassfileAnnotationClass) => |
| 32 | + sym.getAnnotation(defn.JavaRepeatableAnnot).flatMap(_.argumentConstant(0)) match |
| 33 | + case Some(Constant(containerTpe: Type)) => |
| 34 | + val clashingAnns = annsByType.getOrElse(containerTpe.classSymbol, Nil) |
| 35 | + if clashingAnns.nonEmpty then |
| 36 | + // this is the same error javac would raise in this case |
| 37 | + val pos = clashingAnns.head.tree.srcPos |
| 38 | + report.error("Container must not be present at the same time as the element it contains", pos) |
| 39 | + Nil |
| 40 | + else |
| 41 | + val aggregated = JavaSeqLiteral(anns.map(_.tree).toList, TypeTree(sym.typeRef)) |
| 42 | + Annotation(containerTpe, NamedArg("value".toTermName, aggregated)) :: Nil |
| 43 | + case _ => |
| 44 | + val pos = anns.head.tree.srcPos |
| 45 | + report.error("Not repeatable annotation repeated", pos) |
| 46 | + Nil |
| 47 | + case (_, anns) => anns |
| 48 | + }.toList |
0 commit comments