检测ruby ripper解析过程中的错误

时间:2011-10-10 17:06:15

标签: ruby ruby-ripper

有没有人想到如何在Ruby的ripper库中输入格式错误的输入时检测错误?

ruby-1.9.2-p180 :002 > Ripper.sexp("array[1 2]")
 => [:program, [:@int, "2", [1, 8]]] 
ruby-1.9.2-p180 :003 >

我稍微探讨了这些消息来源并发现了#compile_error,#warning,#warn和#yydebug,但目前尚不清楚如何让这些方法发挥作用。毫无疑问,这里有一些简单的答案。

1 个答案:

答案 0 :(得分:0)

我想我在某处读到了ruby ripper扩展仍处于 active 开发之下,所以如果没有人开始连接#compile_error,#warning或#warn,我也不会感到惊讶爱好。

开膛手#yydebug在Ruby 1.9.3中工作,它可能在1.9.2中工作,我只是做错了。但它打印出调试信息,只有一小部分与错误有关。

这是一种直接检测错误的方法:

require 'ripper'
require 'pp'

class SexpBuilderPP < Ripper::SexpBuilderPP
  def on_parse_error(*)
    raise "parse error!"
  end
end

while input = $stdin.gets
  pp SexpBuilderPP.new(input).parse
end

有几个事件在名称中包含“error”:on_alias_error,on_assign_error,on_class_name_error,on_param_error和on_parse_error。