Skip to content

Commit

Permalink
Merge pull request #544 from crystal-ameba/scope-visitor-fixup
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija authored Jan 24, 2025
2 parents 504017b + 389c5a1 commit db2d6c6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 10 deletions.
24 changes: 24 additions & 0 deletions spec/ameba/rule/lint/useless_assign_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,18 @@ module Ameba::Rule::Lint
CRYSTAL
end

it "reports if it's not referenced at a top level + in a method" do
expect_issue subject, <<-CRYSTAL
a : String?
# ^{} error: Useless assignment to variable `a`
def foo
b : String?
# ^ error: Useless assignment to variable `b`
end
CRYSTAL
end

it "reports if it's not referenced in a method" do
expect_issue subject, <<-CRYSTAL
def foo
Expand Down Expand Up @@ -1078,6 +1090,18 @@ module Ameba::Rule::Lint
CRYSTAL
end

it "reports if uninitialized assignment is not referenced at a top level + in a method" do
expect_issue subject, <<-CRYSTAL
a = uninitialized U
# ^{} error: Useless assignment to variable `a`
def foo
b = uninitialized U
# ^ error: Useless assignment to variable `b`
end
CRYSTAL
end

it "reports if uninitialized assignment is not referenced in a method" do
expect_issue subject, <<-CRYSTAL
def foo
Expand Down
16 changes: 6 additions & 10 deletions src/ameba/ast/visitors/scope_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,12 @@ module Ameba::AST

super @rule, @source

@scope_queue.each do |scope|
@rule.test @source, scope.node, scope
if @scope_queue.empty?
@rule.test @source, @current_scope.node, @current_scope
else
@scope_queue.each do |scope|
@rule.test @source, scope.node, scope
end
end
end

Expand Down Expand Up @@ -101,24 +105,18 @@ module Ameba::AST
def end_visit(node : Crystal::Assign | Crystal::OpAssign)
on_assign_end(node.target, node)
@current_assign = nil

on_scope_end(node) if @current_scope.eql?(node)
end

# :nodoc:
def end_visit(node : Crystal::MultiAssign)
node.targets.each { |target| on_assign_end(target, node) }
@current_assign = nil

on_scope_end(node) if @current_scope.eql?(node)
end

# :nodoc:
def end_visit(node : Crystal::UninitializedVar)
on_assign_end(node.var, node)
@current_assign = nil

on_scope_end(node) if @current_scope.eql?(node)
end

# :nodoc:
Expand All @@ -137,8 +135,6 @@ module Ameba::AST

on_assign_end(var, node)
@current_assign = nil

on_scope_end(node) if @current_scope.eql?(node)
end

# :nodoc:
Expand Down

0 comments on commit db2d6c6

Please sign in to comment.