From efe67212b0d30037b5cb04a94456b98f4067b64d Mon Sep 17 00:00:00 2001 From: Vitalii Elenhaupt Date: Sat, 12 May 2018 18:24:56 +0300 Subject: [PATCH] Support of Crystal::UnitializedVar --- spec/ameba/rule/useless_assign_spec.cr | 28 +++++++++++++++++++++++++ src/ameba/ast/visitors/scope_visitor.cr | 11 +++++++++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/spec/ameba/rule/useless_assign_spec.cr b/spec/ameba/rule/useless_assign_spec.cr index 0d73443b..0cb27b7b 100644 --- a/spec/ameba/rule/useless_assign_spec.cr +++ b/spec/ameba/rule/useless_assign_spec.cr @@ -852,5 +852,33 @@ module Ameba::Rule subject.catch(s).should_not be_valid end end + + context "uninitialized" do + it "reports if uninitialized assignment is not referenced at a top level" do + s = Source.new %( + a = uninitialized U + ) + subject.catch(s).should_not be_valid + end + + it "reports if uninitialized assignment is not referenced in a method" do + s = Source.new %( + def foo + a = uninitialized U + end + ) + subject.catch(s).should_not be_valid + end + + it "doesn't report if uninitialized assignment is referenced" do + s = Source.new %( + def foo + a = uninitialized U + a + end + ) + subject.catch(s).should be_valid + end + end end end diff --git a/src/ameba/ast/visitors/scope_visitor.cr b/src/ameba/ast/visitors/scope_visitor.cr index af86cee6..84f06c25 100644 --- a/src/ameba/ast/visitors/scope_visitor.cr +++ b/src/ameba/ast/visitors/scope_visitor.cr @@ -81,7 +81,7 @@ module Ameba::AST @current_assign : Crystal::ASTNode? # :nodoc: - def visit(node : Crystal::Assign | Crystal::OpAssign | Crystal::MultiAssign) + def visit(node : Crystal::Assign | Crystal::OpAssign | Crystal::MultiAssign | Crystal::UninitializedVar) @current_assign = node end @@ -89,12 +89,21 @@ module Ameba::AST def end_visit(node : Crystal::Assign | Crystal::OpAssign) @current_scope.assign_variable(node.target) @current_assign = nil + on_scope_end(node) if @current_scope.eql?(node) end # :nodoc: def end_visit(node : Crystal::MultiAssign) node.targets.each { |target| @current_scope.assign_variable(target) } @current_assign = nil + on_scope_end(node) if @current_scope.eql?(node) + end + + # :nodoc: + def end_visit(node : Crystal::UninitializedVar) + @current_scope.assign_variable(node.var) + @current_assign = nil + on_scope_end(node) if @current_scope.eql?(node) end # :nodoc: