|
1 | 1 | package dotty.tools.dotc.quoted |
2 | 2 |
|
| 3 | +import dotty.tools.dotc.ast.tpd |
3 | 4 | import dotty.tools.dotc.Driver |
4 | 5 | import dotty.tools.dotc.core.Contexts.Context |
5 | 6 | import dotty.tools.dotc.core.StdNames._ |
6 | 7 | import dotty.tools.io.{AbstractFile, Directory, PlainDirectory, VirtualDirectory} |
7 | 8 | import dotty.tools.repl.AbstractFileClassLoader |
| 9 | +import dotty.tools.dotc.printing.DecompilerPrinter |
8 | 10 |
|
9 | 11 | import scala.quoted.Expr |
10 | | -import java.io.ByteArrayOutputStream |
11 | | -import java.io.PrintStream |
12 | | -import java.nio.charset.StandardCharsets |
13 | 12 |
|
14 | 13 | class QuoteDriver extends Driver { |
| 14 | + import tpd._ |
15 | 15 |
|
16 | 16 | def run[T](expr: Expr[T], settings: Runners.RunSettings): T = { |
17 | 17 | val ctx: Context = initCtx.fresh |
@@ -39,18 +39,24 @@ class QuoteDriver extends Driver { |
39 | 39 | } |
40 | 40 |
|
41 | 41 | def show(expr: Expr[_]): String = { |
| 42 | + def show(tree: Tree, ctx: Context): String = { |
| 43 | + val printer = new DecompilerPrinter(ctx) |
| 44 | + val pageWidth = ctx.settings.pageWidth.value(ctx) |
| 45 | + printer.toText(tree).mkString(pageWidth, false) |
| 46 | + } |
| 47 | + withTree(expr, show) |
| 48 | + } |
| 49 | + |
| 50 | + def withTree[T](expr: Expr[_], f: (Tree, Context) => T): T = { |
42 | 51 | val ctx: Context = initCtx.fresh |
43 | 52 | ctx.settings.color.update("never")(ctx) // TODO support colored show |
44 | | - val baos = new ByteArrayOutputStream |
45 | | - var ps: PrintStream = null |
46 | | - try { |
47 | | - ps = new PrintStream(baos, true, "utf-8") |
48 | | - |
49 | | - new ExprDecompiler(ps).newRun(ctx).compileExpr(expr) |
50 | | - |
51 | | - new String(baos.toByteArray, StandardCharsets.UTF_8) |
| 53 | + var output: Option[T] = None |
| 54 | + def registerTree(tree: tpd.Tree)(ctx: Context): Unit = { |
| 55 | + assert(output.isEmpty) |
| 56 | + output = Some(f(tree, ctx)) |
52 | 57 | } |
53 | | - finally if (ps != null) ps.close() |
| 58 | + new ExprDecompiler(registerTree).newRun(ctx).compileExpr(expr) |
| 59 | + output.getOrElse(throw new Exception("Could not extact " + expr)) |
54 | 60 | } |
55 | 61 |
|
56 | 62 | override def initCtx: Context = { |
|
0 commit comments