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

Implement #sort_by inside macros using Enumerable#sort_by #14895

Merged
Merged
Show file tree
Hide file tree
Changes from all 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
14 changes: 10 additions & 4 deletions spec/compiler/macro/macro_methods_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,16 @@ module Crystal
assert_macro %({{["c".id, "b", "a".id].sort}}), %([a, "b", c])
end

it "executes sort_by" do
assert_macro %({{["abc", "a", "ab"].sort_by { |x| x.size }}}), %(["a", "ab", "abc"])
end

it "calls block exactly once for each element in #sort_by" do
assert_macro <<-CRYSTAL, %(5)
{{ (i = 0; ["abc", "a", "ab", "abcde", "abcd"].sort_by { i += 1 }; i) }}
CRYSTAL
end

it "executes uniq" do
assert_macro %({{[1, 1, 1, 2, 3, 1, 2, 3, 4].uniq}}), %([1, 2, 3, 4])
end
Expand Down Expand Up @@ -1020,10 +1030,6 @@ module Crystal
assert_macro %({{{:a => 1, :b => 3}.size}}), "2"
end

it "executes sort_by" do
assert_macro %({{["abc", "a", "ab"].sort_by { |x| x.size }}}), %(["a", "ab", "abc"])
end

it "executes empty?" do
assert_macro %({{{:a => 1}.empty?}}), "false"
end
Expand Down
21 changes: 13 additions & 8 deletions src/compiler/crystal/macros/methods.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3232,12 +3232,17 @@ end
private def sort_by(object, klass, block, interpreter)
block_arg = block.args.first?

klass.new(object.elements.sort { |x, y|
block_arg.try { |arg| interpreter.define_var(arg.name, x) }
x_result = interpreter.accept(block.body)
block_arg.try { |arg| interpreter.define_var(arg.name, y) }
y_result = interpreter.accept(block.body)

x_result.interpret_compare(y_result)
})
klass.new(object.elements.sort_by do |elem|
block_arg.try { |arg| interpreter.define_var(arg.name, elem) }
result = interpreter.accept(block.body)
InterpretCompareWrapper.new(result)
end)
end

private record InterpretCompareWrapper, node : Crystal::ASTNode do
include Comparable(self)

def <=>(other : self)
node.interpret_compare(other.node)
end
end
Loading