|
| 1 | +package dotty.tools |
| 2 | +package dotc |
| 3 | +package fromtasty |
| 4 | + |
| 5 | +import dotty.tools.dotc.ast.tpd |
| 6 | +import dotty.tools.dotc.core.Contexts.Context |
| 7 | +import dotty.tools.dotc.core.Decorators._ |
| 8 | +import dotty.tools.dotc.core.Names._ |
| 9 | +import dotty.tools.dotc.core.NameOps._ |
| 10 | +import dotty.tools.dotc.core.SymDenotations.ClassDenotation |
| 11 | +import dotty.tools.dotc.core._ |
| 12 | +import dotty.tools.dotc.typer.FrontEnd |
| 13 | + |
| 14 | +class ReadTastyTreesFromClasses extends FrontEnd { |
| 15 | + |
| 16 | + override def isTyper = false |
| 17 | + |
| 18 | + override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = |
| 19 | + units.flatMap(readTASTY) |
| 20 | + |
| 21 | + def readTASTY(unit: CompilationUnit)(implicit ctx: Context): Option[CompilationUnit] = unit match { |
| 22 | + case unit: TASTYCompilationUnit => |
| 23 | + val className = unit.className.toTypeName |
| 24 | + def compilationUnit(className: TypeName): Option[CompilationUnit] = { |
| 25 | + tree(className).flatMap { |
| 26 | + case (clsd, unpickled) => |
| 27 | + if (unpickled.isEmpty) None |
| 28 | + else Some(CompilationUnit.mkCompilationUnit(clsd, unpickled, forceTrees = true)) |
| 29 | + |
| 30 | + } |
| 31 | + } |
| 32 | + // The TASTY section in a/b/C.class may either contain a class a.b.C, an object a.b.C, or both. |
| 33 | + // We first try to load the class and fallback to loading the object if the class doesn't exist. |
| 34 | + // Note that if both the class and the object are present, then loading the class will also load |
| 35 | + // the object, this is why we use orElse here, otherwise we could load the object twice and |
| 36 | + // create ambiguities! |
| 37 | + compilationUnit(className).orElse(compilationUnit(className.moduleClassName)) |
| 38 | + } |
| 39 | + |
| 40 | + private def tree(className: TypeName)(implicit ctx: Context): Option[(ClassDenotation, tpd.Tree)] = { |
| 41 | + val clsd = ctx.base.staticRef(className) |
| 42 | + ctx.base.staticRef(className) match { |
| 43 | + case clsd: ClassDenotation => |
| 44 | + def cannotUnpickle(reason: String) = |
| 45 | + ctx.error(s"class $className cannot be unpickled because $reason") |
| 46 | + def tryToLoad = clsd.infoOrCompleter match { |
| 47 | + case info: ClassfileLoader => |
| 48 | + info.load(clsd) |
| 49 | + Option(clsd.symbol.asClass.tree).orElse { |
| 50 | + cannotUnpickle(s"its class file ${info.classfile} does not have a TASTY attribute") |
| 51 | + None |
| 52 | + } |
| 53 | + |
| 54 | + case info => |
| 55 | + cannotUnpickle(s"its info of type ${info.getClass} is not a ClassfileLoader") |
| 56 | + None |
| 57 | + } |
| 58 | + Option(clsd.symbol.asClass.tree).orElse(tryToLoad).map(tree => (clsd, tree)) |
| 59 | + |
| 60 | + case _ => |
| 61 | + ctx.error(s"class not found: $className") |
| 62 | + None |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments