diff --git a/spec/ameba/rule/lint/unused_literal_spec.cr b/spec/ameba/rule/lint/unused_literal_spec.cr index 340c5a9fa..af17b796f 100644 --- a/spec/ameba/rule/lint/unused_literal_spec.cr +++ b/spec/ameba/rule/lint/unused_literal_spec.cr @@ -399,6 +399,32 @@ module Ameba::Rule::Lint CRYSTAL end + it "passes if an unused method call is the last line of a method with a Nil return type restriction" do + expect_no_issues subject, <<-CRYSTAL + def foo : Nil + bar("baz") + end + CRYSTAL + end + + it "fails if an unused literal is the last line of a method with a Nil return type restriction" do + expect_issue subject, <<-CRYSTAL + def foo : Nil + 1234 + # ^^^^ error: Literal value is not used + end + CRYSTAL + end + + it "fails if an unused literal is the last line of an initialize method" do + expect_issue subject, <<-CRYSTAL + def initialize + 1234 + # ^^^^ error: Literal value is not used + end + CRYSTAL + end + it "passes if a literal is used in outputting macro expression" do expect_no_issues subject, <<-CRYSTAL {{ "foo" }} diff --git a/src/ameba/ast/visitors/implicit_return_visitor.cr b/src/ameba/ast/visitors/implicit_return_visitor.cr index 6de191c33..4b5b27a92 100644 --- a/src/ameba/ast/visitors/implicit_return_visitor.cr +++ b/src/ameba/ast/visitors/implicit_return_visitor.cr @@ -127,14 +127,13 @@ module Ameba::AST node.block_arg.try &.accept(self) end - if (return_type = node.return_type).is_a?(Crystal::Path) + case + when node.name == "initialize", + node.return_type.as?(Crystal::Path).try(&.names.join("::").in?("::Nil", "Nil")) # Special case of the return type being nil, meaning the last # line of the method body is ignored - if return_type.names.join("::").in?("::Nil", "Nil") - node.body.accept(self) - else - incr_stack { node.body.accept(self) } - end + # Last line of initialize methods are also ignored + swap_stack { node.body.accept(self) } else incr_stack { node.body.accept(self) } end