我可以从实时 Scala 代码中获取 AST 吗? [英] Can I get AST from live scala code?

查看:22
本文介绍了我可以从实时 Scala 代码中获取 AST 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我说实时代码"是因为我的意思不是来自文本源文件或源字符串,而是来自 partialFunctions/lambdas.(我知道 Ruby1.8 的 parseTree 和 C# linq 可以做到)

I said "live code" because I mean not from text source files or source strings, but from partialFunctions / lambdas. (I know Ruby1.8's parseTree and C# linq can do it)

考虑一个partialFunction f:

consider a partialFunction f:

val f = (i: Int, j: Int) => (i + j) * 2

我希望有一些工具是这样的:

I hope there is some tool works like this:

getBodyAstFrom(f) //=> (Infix('*'), (Infix('+'), Id('i'), Id('j')), Val('2'))

我不在乎语义(上下文解析和隐式太复杂,对我来说没有必要),我只需要来自实时代码的语法树,这可能吗?

I don't care the semantic things (context parsing and implicits are too complex, and unnecessary for me), I just need the syntax tree from live code, is it possible?

检查别人的代码可能会有问题,但我自己的代码呢?有以下可能吗?

There may be issues with inspecting other people's code, but what about my own code? Is the following things possible?

val f = AstFunction(i: Int, j: Int){(i + j) * 2}
f(5, 6) //=> 22
f.ast   //=> (Infix('*'), (Infix('+'), Id('i'), Id('j')), Val('2'))

似乎需要对编译器进行一些破解,嗯...

It seems to need some hacking into the compiler, hmmmm...

推荐答案

编译器本身就是一个库,你可以调用它.实际上,这就是 REPL 的工作方式.但是,虽然您可以获得一串代码的树(在不同阶段),但您无法获得已编译代码的树.

The compiler itself is a library, which you can call. That's how REPL works, in fact. But while you can get the tree (at various stages) for a string of code, you can't get it for compiled code.

当然,除非您使用可以随时更改或不复存在的实验性内容.在这种情况下,您可以尝试:

Except, of course, if you use experimental stuff that can change at any moment or simply cease to exist. In that case, you can try:

scala.reflect.Code.lift(f).tree

并得到:

res17: scala.reflect.Tree = Select(Select(Select(Ident(Field(line26$object,PrefixedType(ThisType(RootSymbol),Class(line26$object)))),Field($iw,PrefixedType(ThisType(Class(line26$object)),Class($iw)))),Field($iw,PrefixedType(ThisType(Class($iw)),Class($iw)))),Method(f,PolyType(List(),List(),AppliedType(PrefixedType(ThisType(Class(scala)),Class(scala.Function2)),List(PrefixedType(ThisType(Class(scala)),Class(scala.Int)), PrefixedType(ThisType(Class(scala)),Class(scala.Int)), PrefixedType(ThisType(Class(scala)),Class(scala.Int)))))))

这是否有帮助...您可能想查看 Miguel Garcia 的The Scala Compiler角落".

Whether that helps or not... You may want to check Miguel Garcia's "The Scala Compiler Corner".

这篇关于我可以从实时 Scala 代码中获取 AST 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆