Skip to content

Lint/UselessAssignment must be considered unsafe #14445

@shyouhei

Description

@shyouhei

Expected behavior

I don't mind if this code has offenses, but this auto-correction is WRONG; must not happen.

It is super-duper difficult -- if not impossible -- to statically prove if a variable assignment is useless or not. Rubocop does not have such feature. That is a reasonable, practical design decision that I support. You should just stop pretending that you do so.

Actual behavior

Autocorrection breaks semantics of the code.

Steps to reproduce the problem

$ cat tmp.rb
def foo
  backtrack = []
  result = []
  node = self

  until node.nil?
    children = node.children
    result << children.first

    unless children.second
      node = backtrack.pop
      next
    end

    backtrack.push(children[2..]).flatten! if children.third
    node = children.second
  end

  result
end
$
$
$ bin/rubocop --safe-auto-correct tmp.rb
--safe-auto-correct is deprecated; use --autocorrect instead.
Inspecting 1 file
W

Offenses:

tmp.rb:11:7: W: [Corrected] Lint/UselessAssignment: Useless assignment to variable - node.
      node = backtrack.pop
      ^^^^

1 file inspected, 1 offense detected, 1 offense corrected

RuboCop version

$ bin/rubocop -V
1.79.0 (using Parser 3.3.9.0, rubocop-ast 1.46.0, analyzing as Ruby 3.2, running on ruby 3.2.4) [x86_64-linux]
  - rubocop-faker 1.1.0
  - rubocop-performance 1.21.1
  - rubocop-rails 2.25.1
  - rubocop-rspec 3.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions