Eric Walker
Eric Walker

Reputation: 7571

detecting errors during ruby ripper parsing

Has anyone figured out how to detect errors when malformed input is given to Ruby's ripper library?

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

I've poked around the sources a little and discovered #compile_error, #warning, #warn, and #yydebug, but it's not yet clear how to get any of these methods to work. No doubt there's some simple answer here.

Upvotes: 1

Views: 302

Answers (1)

Eric Walker
Eric Walker

Reputation: 7571

I think I read somewhere that the ruby ripper extension is still under active development, so I wouldn't be surprised if no one has gotten around to wiring up #compile_error, #warning or #warn yet.

Ripper#yydebug works in Ruby 1.9.3, and it might work in 1.9.2 and I was just doing something wrong. But it prints out debugging information, only a little of which will be related to an error.

This is one straightforward way to detect errors:

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

There are several events that contain "error" in the name: on_alias_error, on_assign_error, on_class_name_error, on_param_error and on_parse_error.

Upvotes: 1

Related Questions