简体   繁体   English

module_eval / class_eval / instance_eval如何计算行号

[英]How does module_eval / class_eval / instance_eval counts the line numbers

I have found the line_number passed to class_eval , module_eval and instance_eval doesn't match the line numbers reported by the error. 我发现传递给class_eval的line_number, module_evalinstance_eval与错误报告的行号不匹配。 This behaviour is not explained by the ruby-doc which says: (use instance_eval as an example) ruby-doc没有解释此行为,它说:(以instance_eval为例)

the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors. 可选的第二和第三个参数提供了在报告编译错误时使用的文件名和起始行号。

All these three methods class_eval , module_eval and instance_eval accepts two additional params to specify the filename and lineno parameters set the text for error messages. 这三个方法class_evalmodule_evalinstance_eval接受两个附加参数来指定文件名和lineno参数,以设置错误消息的文本。

this question has a practical demo for this behavior. 这个问题对此行为有一个实际的演示。

However, I have found the calculation of line numbers more complex than the explanation. 但是,我发现行号的计算比解释要复杂。 Here is a demo 这是一个演示

class Thing
  def add_method
    a = %{
      non_exist
    }
    instance_eval(a, 'dummy', 12)
  end
end

# error will raise to 15 instead of 12 which is specified 
puts Thing.new.add_method

The code above proves that the line_no param passed to instance_eval is not the line numbers reported by the error but is only related to the line_no . 上面的代码证明传递给instance_evalline_no参数不是错误报告的行号,而仅与line_no

I am wondering about the exact behavior of this params? 我想知道这些参数的确切行为吗?

As your snippet of the documentation states, lineno specifies the starting line number of the pseudo-file. 如文档片段所述, lineno指定伪文件的起始行号。 The string you eval contains three lines, where the second line contains non_exist ( %{} preserves line breaks). 您评估的字符串包含三行,第二行包含non_exist%{}保留换行符)。

When I execute your code, I get an error in line 14, not the 15 you receive. 当我执行代码时,在第14行出现错误,而不是收到的15。 I would originally have expected to get 13, but it seems that the ruby parser will only "notice" the error on the next line, possibly looking for method arguments or something else to make sense of non_exists (I am not completely sure on that). 我原本希望得到13,但似乎ruby解析器只会“注意”下一行的错误,可能正在寻找方法参数或其他有意义的non_exists (我不太确定) 。 If I insert another blank line (that contains no indentation) after non_exists , I get the expected 13. 如果我在non_exists之后插入另一个空行(不包含缩进), non_exists得到预期的13。

Any lines inserted after %{ but before non_exists will increment the line number in the error by one, as should be expected. 可以预期,在%{但在non_exists之前插入的任何non_exists会使错误中的行号增加1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM