From: Phlip Date: 2001-12-07T00:13:06+09:00 Subject: [ruby-talk:27688] Re: Controlling the error messages of eval. Christian Szegedy wrote: > I am writing a small preprocessor for C++ in Ruby, I it for example to > generate functions and declaration for accessing data members, > or to define enum types which works like bitmasks. > > The idea is that I interpret all code segments between /*% and */ as > ruby code and the ouput of this code is written into the output file. > > The main loop of the preprocessor is the following function: > > def file_fusion(ifile_name) > f = File.open(ifile_name) > raise "Can't open file #{fname} for reading." if !f > > f.read.scan(/(.*?)^([ \t]*)\/\*%(.*?)\*\//m) do > |before,$prefix,to_eval| > $ofile.print before > to_eval = (to_eval.split("\n").map!{ |l| l.strip }).join("\n") > begin > eval to_eval > rescue > p $! > puts "This error occured while processing :",to_eval > end > end > f.close > > $ofile.print $' > end > > It works quite fine as long as there are no error messages, but if > the eval encounters some parse error, then there is no exception, > but simply the progcess simply aborts. 'rescue' is really 'rescue Exception', and Exception is not the root throwable. It derives from the root throwable class and then gets thrown for runtime errors, including syntax errors but not including things like signals. You may need to look up and call the root throwable. I forget its name but it's in the docs under 'rescue'. > What I would like that > > 1) eval reports the error in the correct place of the input file. It did; the line number was wrapped in the first error message. Snag it like this: def scriptError thing, contents thing = thing.inspect puts thing badLine = thing.split (':')[2].to_i return contents.split ("\n")[badLine] end begin eval contents rescue Exception puts scriptError ($!, contents) end > 2) Should not terminate after each parse error. Is there a "retry" or something? More important style wise, if I were your programmer-user, I want my system to drop dead at the first error. If it "recovers" and continues I might not notice the error message, because it might be high above a console full of output. -- Phlip http://www.greencheese.org/HatTrick