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 Lint/TopLevelOperatorDefinition #579

Merged
merged 4 commits into from
Feb 27, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions spec/ameba/rule/lint/useless_def_spec.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
require "../../../spec_helper"

module Ameba::Rule::Lint
describe UselessDef do
subject = UselessDef.new

it "passes if an operator method is defined within a class" do
expect_no_issues subject, <<-CRYSTAL
class Foo
def +(other)
end
end
CRYSTAL
end

it "passes if an operator method is defined within an enum" do
expect_no_issues subject, <<-CRYSTAL
enum Foo
def +(other)
end
end
CRYSTAL
end

it "passes if an operator method is defined within a module" do
expect_no_issues subject, <<-CRYSTAL
module Foo
def +(other)
end
end
CRYSTAL
end

it "passes if a top-level operator method has a receiver" do
expect_no_issues subject, <<-CRYSTAL
def Foo.+(other)
end
CRYSTAL
end

it "fails if a + operator method is defined top-level" do
expect_issue subject, <<-CRYSTAL
def +(other)
# ^^^^^^^^^^ error: Useless method definition
end
CRYSTAL
end

it "fails if an index operator method is defined top-level" do
expect_issue subject, <<-CRYSTAL
def [](other)
# ^^^^^^^^^^^ error: Useless method definition
end
CRYSTAL
end
end
end
48 changes: 48 additions & 0 deletions src/ameba/rule/lint/useless_def.cr
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
module Ameba::Rule::Lint
# A rule that disallows useless method definitions.
#
# For example, this is considered invalid:
#
# ```
# def +(other)
# end
# ```
#
# And has to be written within a class, struct, or module:
#
# ```
# class Foo
# def +(other)
# end
# end
# ```
#
# YAML configuration example:
#
# ```
# Lint/UselessDef:
# Enabled: true
# ```
class UselessDef < Base
properties do
since_version "1.7.0"
description "Disallows useless method definitions"
end

MSG = "Useless method definition"

def test(source)
AST::NodeVisitor.new self, source, skip: [
Crystal::ClassDef,
Crystal::EnumDef,
Crystal::ModuleDef,
]
end

def test(source, node : Crystal::Def)
return if node.receiver || node.name.chars.any?(&.alphanumeric?)

issue_for node, MSG
end
end
end