From: John Carter Date: 2008-04-30T07:01:30+09:00 Subject: Small tweak to ruby lexing to create optimal aspects / DbC / debugtraces. On Wed, 30 Apr 2008, Joel VanderWerf wrote: > You can put debug code (invariant checks, and puts), flush with the left > margin (unindented). Then these lines can be grepped for with ^\w, more or > less. They also stand out when you scan the code visually. Hokay, now that's an idea! But lets generalize it a little.... What if we added a switch to ruby... ruby -A regexp -R replacementString filename.rb Which would have the meaning that all occurences of #regexp in the code get replaced by replacementString. Where the default replacementString is empty. So for example, if you had ruby code "myfile.rb" like so... def myfunc(a) #PRECOND raise "Bad a" unless someexpression(a) do_stuff #DEBUG_LOG "a=#{a}, b=#{b}" do_otherstuff #POSTCOND raise "Didn't work" unless otherexpression end Then running it with an old version of ruby, or with the new version the code would just work, the #PREBLAH would be treated as comments at lex time and discarded. def myfunc(a) do_stuff do_otherstuff end The code would run optimally fast. Not run it with.... ruby -A PRECOND myfile.rb The lexer would replace "#PRECOND" with "", and the parser would see it and evaluated it, leaving the POSTCOND commented out. def myfunc(a) raise "Bad a" unless someexpression(a) do_stuff do_otherstuff end It gets even better... ruby -A "(PRE|POST)COND" -R "check_invariant;" myfile.rb and the parser sees a full Design by Contract checking def myfunc(a) check_invariant;raise "Bad a" unless someexpression(a) do_stuff do_otherstuff check_invariant; raise "Didn't work" unless otherexpression end Or if you just want a debug logging trace... ruby -A DEBUG_LOG -R "puts" myfile.rb or ruby -A DEBUG_LOG -R "STDERR.puts" myfile.rb or ruby -A DEBUG_LOG -R "$log_file.puts" -e '$log_file=open("logfile.txt","w")' myfile.rb Of course one can just create a wrapper on ruby that accepts any options, but grabs the -A and -R options if present and any file names, does a search and replace on the file "filename.rb", writing the result to a temporary file "_aspect_filename.rb" and then invoking ruby with the rest of the parameters on "_aspect_filename.rb". The problem with that is the search and replace is just done on the top level file, not on any files loaded or required. Another problem is that a lot of care would have to be taken not to get confused by # characters in all the many varieties of strings, heredocs, regexps and character literals. Hmm. Possibly one can search and replace loads and requires to do the same. Hmm. Anyway, any suggestions before I try a write the proof of concept wrapper and then maybe make it an RCR? John Carter Phone : (64)(3) 358 6639 Tait Electronics Fax : (64)(3) 359 4632 PO Box 1645 Christchurch Email : john.carter@tait.co.nz New Zealand