Merge pull request #451 from crystal-ameba/tweak-useless-assign

Refactor `Lint/UselessAssign` rule a bit
This commit is contained in:
Sijawusz Pur Rahnama 2024-01-20 16:15:56 +01:00 committed by GitHub
commit 590640b559
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 11 deletions

View File

@ -461,7 +461,7 @@ module Ameba::Rule::Lint
expect_issue subject, <<-CRYSTAL expect_issue subject, <<-CRYSTAL
class A class A
foo : String? = "foo" foo : String? = "foo"
# ^^^^^^^^^^^^^^^^^^^^^ error: Useless assignment to variable `foo` # ^^^ error: Useless assignment to variable `foo`
def method def method
foo = "bar" foo = "bar"
@ -992,7 +992,7 @@ module Ameba::Rule::Lint
it "reports if it's not referenced at a top level" do it "reports if it's not referenced at a top level" do
expect_issue subject, <<-CRYSTAL expect_issue subject, <<-CRYSTAL
a : String? a : String?
# ^^^^^^^^^ error: Useless assignment to variable `a` # ^{} error: Useless assignment to variable `a`
CRYSTAL CRYSTAL
end end
@ -1000,7 +1000,7 @@ module Ameba::Rule::Lint
expect_issue subject, <<-CRYSTAL expect_issue subject, <<-CRYSTAL
def foo def foo
a : String? a : String?
# ^^^^^^^^^^^ error: Useless assignment to variable `a` # ^ error: Useless assignment to variable `a`
end end
CRYSTAL CRYSTAL
end end
@ -1009,7 +1009,7 @@ module Ameba::Rule::Lint
expect_issue subject, <<-CRYSTAL expect_issue subject, <<-CRYSTAL
class Foo class Foo
a : String? a : String?
# ^^^^^^^^^^^ error: Useless assignment to variable `a` # ^ error: Useless assignment to variable `a`
end end
CRYSTAL CRYSTAL
end end

View File

@ -43,18 +43,31 @@ module Ameba::Rule::Lint
scope.variables.each do |var| scope.variables.each do |var|
next if var.ignored? || var.used_in_macro? || var.captured_by_block? next if var.ignored? || var.used_in_macro? || var.captured_by_block?
if scope.assigns_type_dec?(var.name) if scope.assigns_type_dec?(var.name)
next if exclude_type_declarations? next if exclude_type_declarations? || expressions_with_call?(node)
# exclude type declarations within calls
if node.is_a?(Crystal::Expressions)
next if node.expressions.first?.is_a?(Crystal::Call)
end
end end
var.assignments.each do |assign| var.assignments.each do |assign|
next if assign.referenced? check_assignment(source, assign, var)
issue_for assign.target_node, MSG % var.name
end end
end end
end end
private def expressions_with_call?(node)
node.is_a?(Crystal::Expressions) &&
node.expressions.first?.is_a?(Crystal::Call)
end
private def check_assignment(source, assign, var)
return if assign.referenced?
case target_node = assign.target_node
when Crystal::TypeDeclaration
issue_for target_node.var, MSG % var.name
else
issue_for target_node, MSG % var.name
end
end
end end
end end