|
| 1 | +package dotty.tools.dotc.quoted |
| 2 | + |
| 3 | +import dotty.tools.dotc.CompilationUnit |
| 4 | +import dotty.tools.dotc.ast.tpd |
| 5 | +import dotty.tools.dotc.core.Contexts.Context |
| 6 | +import dotty.tools.dotc.core.Flags._ |
| 7 | +import dotty.tools.dotc.core.Scopes._ |
| 8 | +import dotty.tools.dotc.core.StdNames._ |
| 9 | +import dotty.tools.dotc.core.Symbols._ |
| 10 | +import dotty.tools.dotc.core.Types._ |
| 11 | +import dotty.tools.dotc.typer.FrontEnd |
| 12 | +import dotty.tools.dotc.util.Positions._ |
| 13 | +import dotty.tools.dotc.util.SourceFile |
| 14 | +import dotty.tools.io._ |
| 15 | + |
| 16 | +import scala.quoted.Expr |
| 17 | + |
| 18 | +/** Frontend that receives scala.quoted.Expr as input */ |
| 19 | +class ExprFrontend(putInClass: Boolean) extends FrontEnd { |
| 20 | + import tpd._ |
| 21 | + import PickledQuotes.quotedToTree |
| 22 | + |
| 23 | + override def isTyper = false |
| 24 | + |
| 25 | + override def runOn(units: List[CompilationUnit])(implicit ctx: Context): List[CompilationUnit] = { |
| 26 | + units.map { |
| 27 | + case exprUnit: ExprCompilationUnit => |
| 28 | + val tree = |
| 29 | + if (putInClass) inClass(exprUnit.expr) |
| 30 | + else quotedToTree(exprUnit.expr) |
| 31 | + val source = new SourceFile("", Seq()) |
| 32 | + CompilationUnit.mkCompilationUnit(source, tree, forceTrees = true) |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + /** Places the contents of expr in a compilable tree for a class |
| 37 | + * with the following format. |
| 38 | + * `package __root__ { class ' { def apply: Any = <expr> } }` |
| 39 | + */ |
| 40 | + private def inClass(expr: Expr[_])(implicit ctx: Context): Tree = { |
| 41 | + val pos = Position(0) |
| 42 | + val assocFile = new PlainFile(Path("<quote>")) |
| 43 | + |
| 44 | + val cls = ctx.newCompleteClassSymbol(defn.RootClass, nme.QUOTE.toTypeName, EmptyFlags, |
| 45 | + defn.ObjectType :: Nil, newScope, coord = pos, assocFile = assocFile).entered.asClass |
| 46 | + cls.enter(ctx.newDefaultConstructor(cls), EmptyScope) |
| 47 | + val meth = ctx.newSymbol(cls, nme.apply, Method, ExprType(defn.AnyType), coord = pos).entered |
| 48 | + |
| 49 | + val quoted = quotedToTree(expr)(ctx.withOwner(meth)) |
| 50 | + |
| 51 | + val run = DefDef(meth, quoted) |
| 52 | + val classTree = ClassDef(cls, DefDef(cls.primaryConstructor.asTerm), run :: Nil) |
| 53 | + PackageDef(ref(defn.RootPackage).asInstanceOf[Ident], classTree :: Nil).withPos(pos) |
| 54 | + } |
| 55 | +} |
0 commit comments