Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autocorrect with Style/EmptyElse in nested if statements causes syntax error #4491

Closed
andrewngo opened this issue Jun 10, 2017 · 1 comment
Closed
Labels

Comments

@andrewngo
Copy link

Running autocorrect on nested if statements can cause a syntax error if there's an if block with an empty else. Seems to be deleting one extra end statement. I just fixed it manually in our code, but autocorrect shouldn't introduce syntax errors if possible.


Expected behavior

Deletes only the else and empty line.

def nested_if_empty_else(s)
  if s.is_a?(Hash)
    if s.empty?
      puts 'hello'
    end
  end
end

Actual behavior

An extra end is deleted causing a syntax error

def nested_if_empty_else(s)
  if s.is_a?(Hash)
    if s.empty?
      puts 'hello'
    end
end

unexpected token $end

Steps to reproduce the problem

Run the following on this test code
rubocop --only EmptyElse -a test_file.rb

def nested_if_empty_else(s)
  if s.is_a?(Hash)
    if s.empty?
      puts 'hello'
    else

    end
  end
end

RuboCop version

$ rubocop -V
0.49.1 (using Parser 2.4.0.0, running on ruby 2.3.4 x86_64-darwin16)
@bbatsov bbatsov added the bug label Jun 10, 2017
@pocke
Copy link
Collaborator

pocke commented Jun 10, 2017

👍
I'll fix the problem.

pocke added a commit to pocke/rubocop that referenced this issue Jun 10, 2017
…nested `if`

See rubocop#4491.

Reproduce
======

```ruby
if cond
  if cond2
    some
  else
  end
end
```

```bash
$ rubocop -a --only EmptyElse
Inspecting 1 file
E

Offenses:

test.rb:4:3: C: [Corrected] Redundant else-clause.
  else
  ^^^^
test.rb:5:1: E: unexpected token $end
(Using Ruby 2.1 parser; configure using TargetRubyVersion parameter, under AllCops)

1 file inspected, 2 offenses detected, 1 offense corrected

$ cat test.rb
if cond
  if cond2
    some
  end
```

This change fixes the bug.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants