如何让 Scala ToolBox 查看 REPL 定义? [英] How can I get Scala ToolBox to see REPL definitions?

查看:48
本文介绍了如何让 Scala ToolBox 查看 REPL 定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当反思仍处于初期阶段时,在 Scala 2.10.0 里程碑的日子里,我提出了一个问题我可以用它来查看 REPL 中的代码片段树吗?优秀的答案比我问的更进一步,并展示了如何使用它们来解析和评估树,所以我继续尝试在我今天正在进行的一个小项目中使用它.

Back when reflection was still incipient, on the days of Scala 2.10.0 milestones, I asked a question about how could I use it to see the trees of code snippets from REPL. The excellent answer went further than I asked, and showed how they can be used to parse and evaluate trees as well, so I went ahead and tried to use that on a little project I had going on today.

不幸的是,以这种方式解析和评估的代码似乎没有看到任何 REPL 定义:

Unfortunately, code parsed and evaluated that way doesn't seem to see any REPL definition:

scala> val x = 1
x: Int = 1

scala> import scala.tools.reflect.ToolBox
import scala.tools.reflect.ToolBox

scala> val tb = scala.reflect.runtime.universe.runtimeMirror(
  getClass.getClassLoader).mkToolBox()
tb: scala.tools.reflect.ToolBox[reflect.runtime.universe.type] = ...

scala> tb.eval(tb.parse("x"))
scala.tools.reflect.ToolBoxError: reflective compilation has failed:

not found: value x

有没有办法让它识别 REPL 上的定义?

Is there a way to get it to recognize definitions made on REPL?

推荐答案

最近我深入研究了 repl,试图让它支持类型宏,所以我有能力解释为什么它不起作用.下一步是让它工作:)

Recently I dug into repl, when trying to make it support type macros, so I'm well equipped to explain why it doesn't work. Getting it to work would be the next step :)

我知道您知道输入到 repl 中的每个片段在编译之前都会被包装到一些样板中.因此, x 最终成为包中嵌套嵌套对象中的字段,名称很奇怪.

I know that you know that every snippet entered into repl gets wrapped into some boilerplate before being compiled. Therefore that x ends up being a field in a nested-nested-nested object in a package with a weird name.

显然,repl 会跟踪所有定义的符号,然后将必要的导入与其生成的样板一起注入.因此后续行可以看到 x 不合格.相比之下,工具箱只是重用了 repl 的类加载器,但不对导入做任何事情,因此失败了.

Apparently, repl keeps track of all defined symbols and then injects the necessary imports along with the boilerplate it generates. Therefore subsequent lines can see that x unqualified. To the contrast, toolboxes simply reuse repl's classloader, but don't do anything about the imports, hence the failure.

一种解决方法是以某种方式获取一个表示 repl 的对象,向它询问已定义的符号,然后将相应的导入生成到您提供给工具箱的代码中.如果您提交工单,我会在 2.10.1 代码冻结疯狂结束后(据说是本周末)尝试编写解决方法.

A workaround would be to somehow get to an object representing a repl, ask it about defined symbols and then generate corresponding imports into the code that you feed to a toolbox. If you file a ticket, I'll try to code up a workaround after the 2.10.1 code freeze madness ends (supposedly, end of this week).

这篇关于如何让 Scala ToolBox 查看 REPL 定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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