From: Robert Klemme Date: 2010-11-10T05:50:21+09:00 Subject: Re: Analyzer for errors in code ? On 11/09/2010 07:55 PM, David Unric wrote: > Robert Klemme wrote in post #960353: >> On Tue, Nov 9, 2010 at 5:00 PM, David Unric wrote: >>> I would like to check a source code for common errors like use of unused >>> variables. The "ruby -c" only checks for syntax errors. >>> >>> Is there some tool for Ruby like pylint or pyflakes for Python ? >>> It has to _not_ run the code to do analysis. At least mistypos of method >>> and variable names would be enough. >> >> Unused local variables would be doable, but detection of typos of >> variable and method names is almost impossible without running the >> code. The reason is that the set of valid method names may change at >> will during the course of a programs execution. Plus, with >> #method_missing you can properly handle methods that are never ever >> defined. The usability of such a tool might be very limited. >> >> Having said that you may want to try ruby's command line option -w. >> >> See also >> > http://stackoverflow.com/questions/1805146/where-can-i-find-an-actively-developed-lint-tool-for-ruby > I understand it is difficult because the dynamic nature of Ruby, but > Python is in the same league and PyLint tool does "wonders" at detecting > possible errors without code execution > (http://www.logilab.org/card/pylintfeatures). It uses Abstract Syntax > Tree parser and Ruby also has its own AST so it would be possible. > > But I asked for something more simplistic, like revealing trivial errors > like mentioned variable name typo. > > See the following example: > > Running with 'ruby -c' returns 'Syntax OK'. > Running with 'ruby -w' also doesn't warn about undefined 'mymsg' > variable. > > Only when the condition becomes true, execution aborts with `
': > undefined local variable or method `mymsg' for main:Object (NameError) > > if __FILE__ == $0 > my_msg = 'Hello' > if ARGV[0] == 'doit' > puts mymsg > else > puts 'Nope' > end > end > > > How to avoid such pitfalls with writing more complex ruby code ? I can't > believe there is no other way how to verify the code without 'waiting > for exception at proper conditions' and then solve the bug. Well, actually you would catch the bug during testing which you have to do anyway. If you don't catch it during testing you have bad test coverage. :-) The problem with this is that "mymsg" might be a method call or a local variable read. Ruby recognizes local variables (via assignment) so it knows that "my_msg" is a local variable. But there is no easy way I am aware of to reliably detect that "mymsg" is a typo from "my_msg". ;aybe one could do some fuzzy pattern matching. Kind regards robert