Show hash duplicated keys in error message

closes #45
This commit is contained in:
Vitalii Elenhaupt 2018-04-12 19:18:33 +03:00
parent b225b17b5b
commit 9e2ab9c002
No known key found for this signature in database
GPG key ID: 7558EF3A4056C706
2 changed files with 16 additions and 5 deletions

View file

@ -35,7 +35,16 @@ module Ameba::Rule
error = s.errors.first
error.rule.should_not be_nil
error.location.to_s.should eq "source.cr:2:13"
error.message.should eq "Duplicated keys in hash literal."
error.message.should eq %(Duplicated keys in hash literal: "a")
end
it "reports multiple duplicated keys" do
s = Source.new %q(
h = {"key1" => 1, "key1" => 2, "key2" => 3, "key2" => 4}
)
subject.catch(s).should_not be_valid
error = s.errors.first
error.message.should eq %(Duplicated keys in hash literal: "key1","key2")
end
end
end

View file

@ -30,15 +30,17 @@ module Ameba::Rule
end
def test(source, node : Crystal::HashLiteral)
return unless duplicated_keys?(node.entries)
return unless (keys = duplicated_keys(node.entries)).any?
source.error self, node.location, "Duplicated keys in hash literal."
source.error self, node.location,
"Duplicated keys in hash literal: #{keys.join(",")}"
end
private def duplicated_keys?(entries)
private def duplicated_keys(entries)
entries.map(&.key)
.group_by(&.itself)
.any? { |_, v| v.size > 1 }
.select { |_, v| v.size > 1 }
.map { |k, _| k }
end
end
end