【问题标题】:Scala Interpreter: anyway to get the line of a compile error?Scala解释器:无论如何要得到编译错误的行?
【发布时间】:2011-09-28 15:52:31
【问题描述】:

我正在使用 scala 解释器来运行一些用户定义的脚本。为此,我使用“IMain”类。除了报告编译错误发生的行之外,它就像一个魅力。 为了得到错误行号,我只是解析解释器输出消息,它的形式是 :lineNumber: error: ...

问题在于行号似乎会根据错误的性质和封闭范围(是否在 def 内)而变化。

REPL 也会发生这种情况,例如:

Welcome to Scala version 2.9.1.final (Java HotSpot(TM) Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val a=7
a: Int = 7

scala> a.toString2
<console>:9: error: value toString2 is not a member of Int
              a.toString2
                ^

scala> a2.toString
<console>:8: error: not found: value a2
              a2.toString
              ^

scala> a.toString.length3
<console>:9: error: value length3 is not a member of java.lang.String
              a.toString.length3
                         ^

我希望所有错误消息都以“:1”开头,因为错误位于要解释的代码的第一行...

使用 IMain 类,是否有另一种方法来获取错误行号? (除了不正确的结果之外,解析输出感觉有点像黑客......)

【问题讨论】:

  • 你得到的数字代表错误在行中的位置,而不是行本身的位置。
  • 你使用的是IMain的compile()方法,还是IMain的interpret()方法?
  • 到目前为止,我使用的是 IMain 解释器,它在 Scala 2.9.0.1 上运行良好
  • 在写这个问题之前,我只是切换到 Scala 2.9.1.final。我第一次尝试时,行为与 2.9.0.1 相同(如您在原始问题中所见)。现在,由于某种原因,我得到了相同的行号:两种情况下都是 8(但在“g}”的情况下是 1)

标签: scala error-handling interpreter read-eval-print-loop


【解决方案1】:

部分答案是您键入的内容并不是 scala 解释器真正运行的内容。

您可以通过 scala -Xprint:parser 看到这一点:(我使用的是 scala 2.8.1,所以这说明了一些差异)

scala> a.toString2
[[syntax trees at end of parser]]// Scala source: <console>
package <empty> {
  object line2$object extends scala.ScalaObject {
    def <init>() = {
      super.<init>();
      ()
    };
    object $iw extends scala.ScalaObject {
      def <init>() = {
        super.<init>();
        ()
      };
      import line0$object.$iw.$iw.a;
      object $iw extends scala.ScalaObject {
        def <init>() = {
          super.<init>();
          ()
        };
        val res0 = a.toString2
      }
    }
  }
}

<console>:7: error: value toString2 is not a member of Int
       a.toString2
         ^

对比:

scala> a2.toString
[[syntax trees at end of parser]]// Scala source: <console>
package <empty> {
  object line3$object extends scala.ScalaObject {
    def <init>() = {
      super.<init>();
      ()
    };
    object $iw extends scala.ScalaObject {
      def <init>() = {
        super.<init>();
        ()
      };
      object $iw extends scala.ScalaObject {
        def <init>() = {
          super.<init>();
          ()
        };
        val res1 = a2.toString
      }
    }
  }
}

<console>:6: error: not found: value a2
       a2.toString
       ^

比较两行之后的输出。请参阅输出的第一位中的额外行:

 import line0$object.$iw.$iw.a;

?额外的导入行说明了您在行号中看到的差异。

所以现在您需要 IMain 类以某种方式告诉您在错误之前它在代码顶部添加了多少内容。 (这仍然不能完全解决问题 - 请参阅g} 得到的错误行)

【讨论】:

  • 感谢您的解释,此选项肯定有助于了解发生了什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-12
  • 2011-02-21
  • 2016-07-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多