fix(lint): useless assignment for type definition

closes #342
This commit is contained in:
Vitalii Elenhaupt 2023-02-04 16:56:37 +02:00
parent bd68e8c3b3
commit ddbcf5cb3f
No known key found for this signature in database
GPG Key ID: CD0BF17825928BC0
3 changed files with 37 additions and 3 deletions

View File

@ -475,6 +475,32 @@ module Ameba::Rule::Lint
issue.location.to_s.should eq "source.cr:1:1"
issue.message.should eq "Useless assignment to variable `foo`"
end
it "doesn't report if top level variable defined inside class is referenced" do
s = Source.new %(
class A
foo : String? = "foo"
end
puts foo
)
subject.catch(s).should be_valid
end
it "doesn't report if top level variable assigned inside class and referenced" do
s = Source.new %(
class A
foo : String? = "foo"
bar do
foo = "bar"
end
end
puts foo
)
subject.catch(s).should be_valid
end
end
context "branching" do

View File

@ -161,7 +161,7 @@ module Ameba::AST
# Returns `true` if this scope is a top level scope, `false` otherwise.
def top_level?
outer_scope.nil?
outer_scope.nil? || type_definition?
end
# Returns `true` if var is an argument in current scope, `false` otherwise.

View File

@ -102,10 +102,18 @@ module Ameba::AST
# :nodoc:
def visit(node : Crystal::TypeDeclaration)
return if @current_scope.type_definition?
return if !(var = node.var).is_a?(Crystal::Var)
return unless (var = node.var).is_a?(Crystal::Var)
@current_scope.add_variable(var)
@current_assign = node.value unless node.value.nil?
end
def end_visit(node : Crystal::TypeDeclaration)
return unless (var = node.var).is_a?(Crystal::Var)
on_assign_end(node.var, node)
@current_assign = nil
on_scope_end(node) if @current_scope.eql?(node)
end
# :nodoc: