You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala 3 REPL中将代码展开为原始AST

Scala 3 REPL 查看原始AST的解决方案

方案1:使用REPL内置命令(推荐用于快速验证)

Scala 3 REPL 原生提供了直接打印表达式AST的命令,无需导入任何依赖,完全匹配快速手动验证的需求:

  • 查看类型检查后的完整AST结构:使用:tree命令,直接跟要展开的表达式即可
    示例:
    scala> :tree 1 + 2 * 3
    Inlined(EmptyTree, Nil, Apply(Select(Lit(1), +), List(Apply(Select(Lit(2), *), List(Lit(3))))))
    
  • 查看解析器阶段未类型检查的原始AST:使用:parseTree命令,适合研究解析器链路逻辑的场景
    示例:
    scala> :parseTree def foo(x: Int) = x + 1
    DefDef(Modifiers(),foo,List(List(ValDef(Modifiers(PARAM),x,Ident(Int),EmptyTree))),TypeTree[TypeRef(ThisType(TypeRef(NoPrefix,scala)),Int)],Apply(Select(Ident(x), +), List(Lit(1))))
    

方案2:自定义reify方法(适合需要操作AST变量的场景)

如果需要将AST存储为变量做后续处理,可以通过Scala 3的staging API封装和Scala 2等效的reify逻辑:

  1. 首先在REPL中导入依赖并初始化编译器上下文:
import scala.quoted.*
import scala.quoted.staging.*
given Compiler = Compiler.make(getClass.getClassLoader)
  1. 封装自定义的reify方法:
def reify[A](expr: Quotes ?=> Expr[A]): String = 
  Printer.TreeStructure.show(expr)
  1. 使用方式和Scala 2完全一致:
scala> reify { "test".length + 5 }
val res0: String = Inlined(EmptyTree, Nil, Apply(Select(Apply(Select(Lit("test"), length), Nil), +), List(Lit(5))))

内容的提问来源于stack exchange,提问作者sinanspd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:39:04