Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Typing/ProcLiteralReturnTypeRestriction #522

Merged
1 change: 1 addition & 0 deletions spec/ameba/base_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module Ameba::Rule
Naming
Performance
Style
Typing
]
end
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require "../../../spec_helper"

module Ameba::Rule::Typing
subject = ProcLiteralReturnTypeRestriction.new

it "passes if a proc literal has a return type restriction" do
expect_no_issues subject, <<-CRYSTAL
my_proc = ->(var : String) : Nil { puts var }
CRYSTAL
end

it "fails if a proc literal doesn't have a return type restriction" do
expect_issue subject, <<-CRYSTAL
my_proc = ->(var : String) { puts var }
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: Proc literal should have a return type restriction
CRYSTAL
end
end
1 change: 1 addition & 0 deletions src/ameba/ast/visitors/node_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ module Ameba::AST
ModuleDef,
MultiAssign,
NilLiteral,
ProcLiteral,
StringInterpolation,
Unless,
Until,
Expand Down
45 changes: 45 additions & 0 deletions src/ameba/rule/typing/proc_literal_return_type_restriction.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
module Ameba::Rule::Typing
# A rule that enforces that `Proc` literals have a return type.
#
# For example, these are considered valid:
#
# ```
# greeter = ->(name : String) : String { "Hello #{name}" }
# ```
#
# ```
# task = -> : Task { Task.new("execute this command") }
# ```
#
# And these are invalid:
#
# ```
# greeter = ->(name : String) { "Hello #{name}" }
# ```
#
# ```
# task = -> { Task.new("execute this command") }
# ```
#
# YAML configuration example:
#
# ```
# Typing/ProcLiteralReturnTypeRestriction:
# Enabled: false
# ```
class ProcLiteralReturnTypeRestriction < Base
properties do
Sija marked this conversation as resolved.
Show resolved Hide resolved
since_version "1.7.0"
description "Disallows Proc literals without return type restrictions"
enabled false
end

MSG = "Proc literal should have a return type restriction"

def test(source, node : Crystal::ProcLiteral)
return if node.def.return_type

issue_for node, MSG
end
end
end
Loading