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

查看:190
本文介绍了我可以从实时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的 Scala编译器角

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

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

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