Skip to content

Commit

Permalink
Update UselessAssign rule to report unreferenced type declarations
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Dec 14, 2023
1 parent 3448ad9 commit 51b45f5
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
47 changes: 44 additions & 3 deletions spec/ameba/rule/lint/useless_assign_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -492,8 +492,8 @@ module Ameba::Rule::Lint
subject.catch(s).should be_valid
end

it "doesn't report if type declaration assigned inside class" do
s = Source.new %(
it "reports if type declaration assigned inside class" do
s = Source.new path: "source.cr", code: %(
class A
foo : String? = "foo"
Expand All @@ -502,7 +502,11 @@ module Ameba::Rule::Lint
end
end
)
subject.catch(s).should be_valid
subject.catch(s).should_not be_valid

issue = s.issues.first
issue.location.to_s.should eq "source.cr:2:3"
issue.message.should eq "Useless assignment to variable `foo`"
end
end

Expand Down Expand Up @@ -1068,6 +1072,43 @@ module Ameba::Rule::Lint
subject.catch(s).should be_valid
end

context "type declaration" do
it "reports if it's not referenced at a top level" do
s = Source.new %(
a : String?
)
subject.catch(s).should_not be_valid
end

it "reports if it's not referenced in a method" do
s = Source.new %(
def foo
a : String?
end
)
subject.catch(s).should_not be_valid
end

it "reports if it's not referenced in a class" do
s = Source.new %(
class Foo
a : String?
end
)
subject.catch(s).should_not be_valid
end

it "doesn't report if it's referenced" do
s = Source.new %(
def foo
a : String?
a
end
)
subject.catch(s).should be_valid
end
end

context "uninitialized" do
it "reports if uninitialized assignment is not referenced at a top level" do
s = Source.new %(
Expand Down
6 changes: 5 additions & 1 deletion src/ameba/rule/lint/useless_assign.cr
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,11 @@ module Ameba::Rule::Lint
def test(source, node, scope : AST::Scope)
scope.variables.each do |var|
next if var.ignored? || var.used_in_macro? || var.captured_by_block?
next if scope.assigns_type_dec?(var.name)

if scope.assigns_type_dec?(var.name) && var.assignments.empty?
issue_for var.node, MSG % var.name
return
end

var.assignments.each do |assign|
next if assign.referenced?
Expand Down

0 comments on commit 51b45f5

Please sign in to comment.