|
| 1 | +package dotty.tools.backend.sjs |
| 2 | + |
| 3 | +import scala.annotation.tailrec |
| 4 | + |
| 5 | +import dotty.tools.dotc._ |
| 6 | + |
| 7 | +import dotty.tools.dotc.core._ |
| 8 | +import Constants._ |
| 9 | +import Contexts._ |
| 10 | +import Decorators._ |
| 11 | +import Flags._ |
| 12 | +import Names._ |
| 13 | +import NameOps._ |
| 14 | +import Phases._ |
| 15 | +import Scopes._ |
| 16 | +import Symbols._ |
| 17 | +import StdNames._ |
| 18 | +import Types._ |
| 19 | + |
| 20 | +import dotty.tools.dotc.transform.MegaPhase._ |
| 21 | + |
| 22 | +/** Generates JUnit bootstrapper objects for Scala.js. |
| 23 | + * |
| 24 | + * On the JVM, JUnit uses run-time reflection to list and invoke JUnit-related |
| 25 | + * methods. They are identified by annotations such as `@Test`, `@Before`, |
| 26 | + * etc. In Scala.js, there is no such reflection for methods and annotations, |
| 27 | + * so a different strategy is used: this phase performs the necessary |
| 28 | + * inspections at compile-time, and generates a so-called bootstrapper object |
| 29 | + * where all those metadata have been reified. |
| 30 | + * |
| 31 | + * With an example: given the following JUnit test class: |
| 32 | + * |
| 33 | + * ``` |
| 34 | + * class MyTest { |
| 35 | + * @Before def myBefore(): Unit = ... |
| 36 | + * @Before def otherBefore(): Unit = ... |
| 37 | + * |
| 38 | + * @Test def syncTest(): Unit = ... |
| 39 | + * @Test def asyncTest(): Future[Try[Unit]] = ... |
| 40 | + * |
| 41 | + * @Ignore @Test def ignoredTest(): Unit = ... |
| 42 | + * } |
| 43 | + * |
| 44 | + * object MyTest { |
| 45 | + * @AfterClass def myAfterClass(): Unit = ... |
| 46 | + * } |
| 47 | + * ``` |
| 48 | + * |
| 49 | + * this phase generates the following bootstrapper module class: |
| 50 | + * |
| 51 | + * ``` |
| 52 | + * object MyTest$scalajs$junit$bootstrapper extends Object with Bootstrapper { |
| 53 | + * def beforeClass(): Unit = { |
| 54 | + * // nothing, since there is no @BeforeClass method in object MyTest |
| 55 | + * } |
| 56 | + * |
| 57 | + * def afterClass(): Unit = { |
| 58 | + * MyTest.myAfterClass() |
| 59 | + * } |
| 60 | + * |
| 61 | + * def before(instance: Object): Unit = { |
| 62 | + * // typically 0 or 1, but also support 2 or more |
| 63 | + * instance.asInstanceOf[MyTest].myBefore() |
| 64 | + * instance.asInstanceOf[MyTest].otherBefore() |
| 65 | + * } |
| 66 | + * |
| 67 | + * def after(instance: Object): Unit = { |
| 68 | + * // nothing, since there is no @After method in class MyTest |
| 69 | + * } |
| 70 | + * |
| 71 | + * def tests(): Array[TestMetadata] = Array( |
| 72 | + * new TestMetadata("syncTest", false, new org.junit.Test()), |
| 73 | + * new TestMetadata("asyncTest", false, new org.junit.Test()), |
| 74 | + * new TestMetadata("ignoredTest", true, new org.junit.Test()), |
| 75 | + * ) |
| 76 | + * |
| 77 | + * def invokeTest(instance: Object, name: String): Future[Unit] = { |
| 78 | + * val castInstance: MyTest = instance.asInstanceOf[MyTest] |
| 79 | + * if ("syncTest".equals(name)) |
| 80 | + * Future.successful(scala.util.Success(castInstance.syncTest())) |
| 81 | + * else if ("asyncTest".equals(name)) |
| 82 | + * castInstance.asyncTest() // asyncTest() already returns a Future[Try[Unit]] |
| 83 | + * else if ("ignoredTest".equals(name)) |
| 84 | + * Future.successful(scala.util.Success(castInstance.ignoredTest())) |
| 85 | + * else |
| 86 | + * throw new NoSuchMethodException(name) |
| 87 | + * } |
| 88 | + * |
| 89 | + * def newInstance(): Object = new MyTest() |
| 90 | + * } |
| 91 | + * ``` |
| 92 | + * |
| 93 | + * Note that the support for test methods returning `Future`s is specific to |
| 94 | + * Scala.js, and not advertised as a public feature. It is necessary to test |
| 95 | + * some things in Scala.js itself, but outside users should use a testing |
| 96 | + * framework with official asynchronous support instead. |
| 97 | + * |
| 98 | + * Because `Booststrapper` is annotated with `@EnableReflectiveInstantiation`, |
| 99 | + * the run-time implementation of JUnit for Scala.js can load the boostrapper |
| 100 | + * module using `scala.scalajs.reflect.Reflect`, and then use the methods of |
| 101 | + * Bootstrapper, which are implemented in the bootstrapper object, to perform |
| 102 | + * test discovery and invocation. |
| 103 | + * |
| 104 | + * TODO At the moment, this phase does not handle `@Test` annotations with |
| 105 | + * parameters, notably the expected exception class. This should be handled at |
| 106 | + * some point in the future. |
| 107 | + */ |
| 108 | +class JUnitBootstrappers extends MiniPhase { |
| 109 | + import JUnitBootstrappers._ |
| 110 | + import ast.tpd._ |
| 111 | + import JSDefinitions.jsdefn |
| 112 | + |
| 113 | + def phaseName: String = "junitBootstrappers" |
| 114 | + |
| 115 | + override def isEnabled(implicit ctx: Context): Boolean = |
| 116 | + super.isEnabled && ctx.settings.scalajs.value |
| 117 | + |
| 118 | + // The actual transform ------------------------------- |
| 119 | + |
| 120 | + override def transformPackageDef(tree: PackageDef)(implicit ctx: Context): Tree = { |
| 121 | + val junitdefn = jsdefn.junit |
| 122 | + |
| 123 | + @tailrec |
| 124 | + def hasTests(sym: ClassSymbol): Boolean = { |
| 125 | + sym.info.decls.exists(m => m.is(Method) && m.hasAnnotation(junitdefn.TestAnnotClass)) || |
| 126 | + sym.superClass.exists && hasTests(sym.superClass.asClass) |
| 127 | + } |
| 128 | + |
| 129 | + def isTestClass(sym: Symbol): Boolean = { |
| 130 | + sym.isClass && |
| 131 | + !sym.is(ModuleClass | Abstract | Trait) && |
| 132 | + hasTests(sym.asClass) |
| 133 | + } |
| 134 | + |
| 135 | + val bootstrappers = tree.stats.collect { |
| 136 | + case clDef: TypeDef if isTestClass(clDef.symbol) => |
| 137 | + genBootstrapper(clDef.symbol.asClass) |
| 138 | + } |
| 139 | + |
| 140 | + if (bootstrappers.isEmpty) tree |
| 141 | + else cpy.PackageDef(tree)(tree.pid, tree.stats ::: bootstrappers) |
| 142 | + } |
| 143 | + |
| 144 | + private def genBootstrapper(testClass: ClassSymbol)(implicit ctx: Context): TypeDef = { |
| 145 | + val junitdefn = jsdefn.junit |
| 146 | + |
| 147 | + /* The name of the boostrapper module. It is derived from the test class name by |
| 148 | + * appending a specific suffix string mandated "by spec". It will indeed also be |
| 149 | + * computed as such at run-time by the Scala.js JUnit Runtime support. Therefore, |
| 150 | + * it must *not* be a dotc semantic name. |
| 151 | + */ |
| 152 | + val bootstrapperName = (testClass.name ++ "$scalajs$junit$bootstrapper").toTermName |
| 153 | + |
| 154 | + val owner = testClass.owner |
| 155 | + val moduleSym = ctx.newCompleteModuleSymbol(owner, bootstrapperName, |
| 156 | + Synthetic, Synthetic, |
| 157 | + List(defn.ObjectType, junitdefn.BootstrapperType), newScope, |
| 158 | + coord = testClass.span, assocFile = testClass.assocFile).entered |
| 159 | + val classSym = moduleSym.moduleClass.asClass |
| 160 | + |
| 161 | + val constr = genConstructor(classSym) |
| 162 | + |
| 163 | + val testMethods = annotatedMethods(testClass, junitdefn.TestAnnotClass) |
| 164 | + |
| 165 | + val defs = List( |
| 166 | + genCallOnModule(classSym, junitNme.beforeClass, testClass.companionModule, junitdefn.BeforeClassAnnotClass), |
| 167 | + genCallOnModule(classSym, junitNme.afterClass, testClass.companionModule, junitdefn.AfterClassAnnotClass), |
| 168 | + genCallOnParam(classSym, junitNme.before, testClass, junitdefn.BeforeAnnotClass), |
| 169 | + genCallOnParam(classSym, junitNme.after, testClass, junitdefn.AfterAnnotClass), |
| 170 | + genTests(classSym, testMethods), |
| 171 | + genInvokeTest(classSym, testClass, testMethods), |
| 172 | + genNewInstance(classSym, testClass) |
| 173 | + ) |
| 174 | + |
| 175 | + sbt.APIUtils.registerDummyClass(classSym) |
| 176 | + |
| 177 | + ClassDef(classSym, constr, defs) |
| 178 | + } |
| 179 | + |
| 180 | + private def genConstructor(owner: ClassSymbol)(implicit ctx: Context): DefDef = { |
| 181 | + val sym = ctx.newDefaultConstructor(owner).entered |
| 182 | + DefDef(sym, { |
| 183 | + Block( |
| 184 | + Super(This(owner), nme.EMPTY.toTypeName, inConstrCall = true).select(defn.ObjectClass.primaryConstructor).appliedToNone :: Nil, |
| 185 | + unitLiteral |
| 186 | + ) |
| 187 | + }) |
| 188 | + } |
| 189 | + |
| 190 | + private def genCallOnModule(owner: ClassSymbol, name: TermName, module: Symbol, annot: Symbol)(implicit ctx: Context): DefDef = { |
| 191 | + val sym = ctx.newSymbol(owner, name, Synthetic | Method, |
| 192 | + MethodType(Nil, Nil, defn.UnitType)).entered |
| 193 | + |
| 194 | + DefDef(sym, { |
| 195 | + if (module.exists) { |
| 196 | + val calls = annotatedMethods(module.moduleClass.asClass, annot) |
| 197 | + .map(m => Apply(ref(module).select(m), Nil)) |
| 198 | + Block(calls, unitLiteral) |
| 199 | + } else { |
| 200 | + unitLiteral |
| 201 | + } |
| 202 | + }) |
| 203 | + } |
| 204 | + |
| 205 | + private def genCallOnParam(owner: ClassSymbol, name: TermName, testClass: ClassSymbol, annot: Symbol)(implicit ctx: Context): DefDef = { |
| 206 | + val sym = ctx.newSymbol(owner, name, Synthetic | Method, |
| 207 | + MethodType(junitNme.instance :: Nil, defn.ObjectType :: Nil, defn.UnitType)).entered |
| 208 | + |
| 209 | + DefDef(sym, { (paramRefss: List[List[Tree]]) => |
| 210 | + val List(List(instanceParamRef)) = paramRefss |
| 211 | + val calls = annotatedMethods(testClass, annot) |
| 212 | + .map(m => Apply(instanceParamRef.cast(testClass.typeRef).select(m), Nil)) |
| 213 | + Block(calls, unitLiteral) |
| 214 | + }) |
| 215 | + } |
| 216 | + |
| 217 | + private def genTests(owner: ClassSymbol, tests: List[Symbol])(implicit ctx: Context): DefDef = { |
| 218 | + val junitdefn = jsdefn.junit |
| 219 | + |
| 220 | + val sym = ctx.newSymbol(owner, junitNme.tests, Synthetic | Method, |
| 221 | + MethodType(Nil, defn.ArrayOf(junitdefn.TestMetadataType))).entered |
| 222 | + |
| 223 | + DefDef(sym, { |
| 224 | + val metadata = for (test <- tests) yield { |
| 225 | + val name = Literal(Constant(test.name.toString)) |
| 226 | + val ignored = Literal(Constant(test.hasAnnotation(junitdefn.IgnoreAnnotClass))) |
| 227 | + // TODO Handle @Test annotations with arguments |
| 228 | + // val reifiedAnnot = New(mydefn.TestAnnotType, test.getAnnotation(mydefn.TestAnnotClass).get.arguments) |
| 229 | + val testAnnot = test.getAnnotation(junitdefn.TestAnnotClass).get |
| 230 | + if (testAnnot.arguments.nonEmpty) |
| 231 | + ctx.error("@Test annotations with arguments are not yet supported in Scala.js for dotty", testAnnot.tree.sourcePos) |
| 232 | + val noArgConstr = junitdefn.TestAnnotType.member(nme.CONSTRUCTOR).suchThat(_.info.paramInfoss.head.isEmpty).symbol.asTerm |
| 233 | + val reifiedAnnot = New(junitdefn.TestAnnotType, noArgConstr, Nil) |
| 234 | + New(junitdefn.TestMetadataType, List(name, ignored, reifiedAnnot)) |
| 235 | + } |
| 236 | + JavaSeqLiteral(metadata, TypeTree(junitdefn.TestMetadataType)) |
| 237 | + }) |
| 238 | + } |
| 239 | + |
| 240 | + private def genInvokeTest(owner: ClassSymbol, testClass: ClassSymbol, tests: List[Symbol])(implicit ctx: Context): DefDef = { |
| 241 | + val junitdefn = jsdefn.junit |
| 242 | + |
| 243 | + val sym = ctx.newSymbol(owner, junitNme.invokeTest, Synthetic | Method, |
| 244 | + MethodType(List(junitNme.instance, junitNme.name), List(defn.ObjectType, defn.StringType), junitdefn.FutureType)).entered |
| 245 | + |
| 246 | + DefDef(sym, { (paramRefss: List[List[Tree]]) => |
| 247 | + val List(List(instanceParamRef, nameParamRef)) = paramRefss |
| 248 | + val castInstanceSym = ctx.newSymbol(sym, junitNme.castInstance, Synthetic, testClass.typeRef, coord = owner.span) |
| 249 | + Block( |
| 250 | + ValDef(castInstanceSym, instanceParamRef.cast(testClass.typeRef)) :: Nil, |
| 251 | + tests.foldRight[Tree] { |
| 252 | + val tp = junitdefn.NoSuchMethodExceptionType |
| 253 | + val constr = tp.member(nme.CONSTRUCTOR).suchThat { c => |
| 254 | + c.info.paramInfoss.head.size == 1 && |
| 255 | + c.info.paramInfoss.head.head.isRef(defn.StringClass) |
| 256 | + }.symbol.asTerm |
| 257 | + Throw(New(tp, constr, nameParamRef :: Nil)) |
| 258 | + } { (test, next) => |
| 259 | + If(Literal(Constant(test.name.toString)).select(defn.Any_equals).appliedTo(nameParamRef), |
| 260 | + genTestInvocation(testClass, test, ref(castInstanceSym)), |
| 261 | + next) |
| 262 | + } |
| 263 | + ) |
| 264 | + }) |
| 265 | + } |
| 266 | + |
| 267 | + private def genTestInvocation(testClass: ClassSymbol, testMethod: Symbol, instance: Tree)(implicit ctx: Context): Tree = { |
| 268 | + val junitdefn = jsdefn.junit |
| 269 | + |
| 270 | + val resultType = testMethod.info.resultType |
| 271 | + if (resultType.isRef(defn.UnitClass)) { |
| 272 | + val newSuccess = ref(junitdefn.SuccessModule_apply).appliedTo(ref(defn.BoxedUnit_UNIT)) |
| 273 | + Block( |
| 274 | + instance.select(testMethod).appliedToNone :: Nil, |
| 275 | + ref(junitdefn.FutureModule_successful).appliedTo(newSuccess) |
| 276 | + ) |
| 277 | + } else if (resultType.isRef(junitdefn.FutureClass)) { |
| 278 | + instance.select(testMethod).appliedToNone |
| 279 | + } else { |
| 280 | + // We lie in the error message to not expose that we support async testing. |
| 281 | + ctx.error("JUnit test must have Unit return type", testMethod.sourcePos) |
| 282 | + EmptyTree |
| 283 | + } |
| 284 | + } |
| 285 | + |
| 286 | + private def genNewInstance(owner: ClassSymbol, testClass: ClassSymbol)(implicit ctx: Context): DefDef = { |
| 287 | + val sym = ctx.newSymbol(owner, junitNme.newInstance, Synthetic | Method, |
| 288 | + MethodType(Nil, defn.ObjectType)).entered |
| 289 | + |
| 290 | + DefDef(sym, New(testClass.typeRef, Nil)) |
| 291 | + } |
| 292 | + |
| 293 | + private def castParam(param: Symbol, clazz: Symbol)(implicit ctx: Context): Tree = |
| 294 | + ref(param).cast(clazz.typeRef) |
| 295 | + |
| 296 | + private def annotatedMethods(owner: ClassSymbol, annot: Symbol)(implicit ctx: Context): List[Symbol] = |
| 297 | + owner.info.decls.filter(m => m.is(Method) && m.hasAnnotation(annot)) |
| 298 | +} |
| 299 | + |
| 300 | +object JUnitBootstrappers { |
| 301 | + |
| 302 | + private object junitNme { |
| 303 | + val beforeClass: TermName = termName("beforeClass") |
| 304 | + val afterClass: TermName = termName("afterClass") |
| 305 | + val before: TermName = termName("before") |
| 306 | + val after: TermName = termName("after") |
| 307 | + val tests: TermName = termName("tests") |
| 308 | + val invokeTest: TermName = termName("invokeTest") |
| 309 | + val newInstance: TermName = termName("newInstance") |
| 310 | + |
| 311 | + val instance: TermName = termName("instance") |
| 312 | + val name: TermName = termName("name") |
| 313 | + val castInstance: TermName = termName("castInstance") |
| 314 | + } |
| 315 | + |
| 316 | +} |
0 commit comments