burnettk
burnettk

Reputation: 14047

Is Rubocop a superset of the "ruby -c" syntax check?

We had a test that found every Ruby file in our application and ran ruby -c on it. We introduced Rubocop and made it check the same list of files.

Is the test that ran ruby -c actually now useless, or is there an example of a failure mode that would be caught by ruby -c but not Rubocop?

The documentation for ruby -c says:

Causes Ruby to check the syntax of the script and exit without executing. If there are no syntax errors, Ruby will print "Syntax OK" to the standard output.

This is an example of a syntax issue that will be caught by either:

% echo "puts 'hello world" > hot_script.rb
% ruby -c hot_script.rb
hot_script.rb:1: unterminated string meets end of file

% rubocop hot_script.rb
Inspecting 1 file
F

Offenses:

hot_script.rb:1:6: F: unterminated string meets end of file
(Using Ruby 1.9 parser; configure using TargetRubyVersion parameter, under AllCops)
puts 'hello world
     ^

1 file inspected, 1 offense detected

Rubocop even catches some of the same warnings, though I didn't have ruby -c configured to catch these previously, and I am therefore more interested in errors. Here's an example of relative parity in handling a warning:

% cat unused_var.rb
def hot_method
  a = 1
  b = 2
  puts b
end

% ruby -cwW2 unused_var.rb
unused_var.rb:2: warning: assigned but unused variable - a
Syntax OK

% rubocop unused_var.rb
Inspecting 1 file
W

Offenses:

unused_var.rb:2:3: W: Lint/UselessAssignment: Useless assignment to variable - a.
  a = 1
  ^

1 file inspected, 1 offense detected

I searched using

but I may be doing it wrong. The test is way slower in Ruby 1.9 than it was in Ruby 1.8, so the answer to this question is actually valuable to me. And you have to admit, you're curious, right?

Upvotes: 4

Views: 309

Answers (2)

Drenmi
Drenmi

Reputation: 8777

The answer is "most of the time." RuboCop builds on the parser gem, which is a standalone Ruby parser which mimics, more or less, the MRI parser. RuboCop wraps parser's syntax checks and will properly report issues. However, as stated on the parser's GitHub:

Unfortunately MRI often changes syntax in patch level versions [...] there is no simple way to track these changes.

This policy makes it all but impossible to make Parser precisely compatible with the Ruby MRI parser.

In addition, parser supports the latest minor version of whatever release you are using, and doesn't backport minor versions. So if you use Ruby 2.4.0, RuboCop will use a parser version supporting 2.4.1 syntax.

For all intents and purposes, parser is equivalent to the official MRI parser, and unless you have a specific reason to use both, using RuboCop alone should be sufficient.

Upvotes: 4

Michael Mior
Michael Mior

Reputation: 28752

Rubocop will also identify and report syntax errors since the code cannot be properly parsed if that is the case, so there's no need for both.

Upvotes: 2

Related Questions