scala - 在 REPL 中将代码扩展为原始 AST Scala 3
问题描述
我目前正在做很多编译器研究。这不仅需要编写编译器插件,还需要修改 dotty 编译器,从解析器到类型器。因此,我需要不断查看原始 AST 以勾勒出必要的转换。
在 Scala 2 中,反射库提供了以下功能:
val expression = ....
val tree = reify{expression}.tree
showRaw(tree)
现在根据我从文档中了解到的情况,最后一步已替换为Printer.TreeStructure.show(tree)
但是,我在元编程文档中找不到任何替代reify
. 现在,我显然可以在 Scala 程序中使用各种元编程技术并将树打印到其中,stdout
但与在 REPL 中扩展以进行快速手动验证相比,这是一个非常耗时的过程。
有没有办法在 Scala 3 REPL 中做到这一点?
解决方案
reify
您可以在项目中定义自己的
import scala.quoted.*
object App {
inline def reify(inline a: Any) = ${reifyImpl('a)}
def reifyImpl(a: Expr[Any])(using Quotes): Expr[String] = {
import quotes.reflect.*
Literal(StringConstant(Printer.TreeStructure.show(a.asTerm))).asExprOf[String]
}
}
并在 REPL 中使用它
sbt console
scala> import App.reify
scala> reify{ class A }
val res0: String = Inlined(None, Nil, Block(List(ClassDef("A", DefDef("<init>", List(TermParamClause(Nil)), Inferred(), None), List(Apply(Select(New(Inferred()), "<init>"), Nil)), None, Nil)), Literal(UnitConstant())))
不幸的是,reify
直接在 REPL 中定义似乎不起作用
scala> import scala.quoted.*; inline def reify(inline a: Any) = ${reifyImpl('a)}; def reifyImpl(a: Expr[Any])(using Quotes): Expr[String] = {import quotes.reflect.*; Literal(StringConstant(Printer.TreeStructure.show(a.asTerm))).asExprOf[String]}
def reify(a: Any): String
def reifyImpl
(a: quoted.Expr[Any])(using x$2: quoted.Quotes): quoted.Expr[String]
scala> reify{class A}
-- Error:
1 |reify{class A}
|^^^^^^^^^^^^^^
|Failed to evaluate macro.
| Caused by class java.lang.ClassNotFoundException: rs$line$6
| java.lang.ClassLoader.loadClass(ClassLoader.java:418)
| java.lang.ClassLoader.loadClass(ClassLoader.java:351)
| dotty.tools.repl.AbstractFileClassLoader.loadClass(AbstractFileClassLoader.scala:55)
| dotty.tools.dotc.transform.Splicer$Interpreter.loadReplLineClass(Splicer.scala:402)
| dotty.tools.dotc.transform.Splicer$Interpreter.interpretedStaticMethodCall(Splicer.scala:354)
| dotty.tools.dotc.transform.Splicer$Interpreter.interpretTree(Splicer.scala:260)
| dotty.tools.dotc.transform.Splicer$Interpreter.interpretTree$$anonfun$2(Splicer.scala:281)
|
| This location contains code that was inlined from rs$line$7:1
推荐阅读
- javascript - 求和嵌套数组
- android - Gradle 忽略 google maven 存储库,仅在 jcenter 上搜索
- python - 错误:在 Tensorflow1.x 中输入占位符时,无法识别张量,有什么建议吗?
- c++ - 如何使用 RAII 包装 C 分配返回错误代码
- php - 如果 print_r 在 PHP 中为空条件
- multithreading - 理解和分析多线程代码的最佳方法是什么?
- reactjs - 基于状态变化的组件条件渲染
- python - 从python代码执行字节码.pyc?
- mysql - Mysql 删除和时间戳
- javascript - 创建对象复制旧的