Add Hash#sort_by#1548
Conversation
`sort_by` on a hash hit the unsupported-call diagnostic. It yields each |key, value| pair and returns the `[key, value]` pairs ordered by the block's value. `emit_hash_sort_by_expr` walks the entries through the shared `emit_hash_block_eval` binder, building a `[sort_key, pair]` tuple per entry, then defers to a new runtime `sp_PolyArray_sort_by_first` that sorts the tuples by their comparable sort key and projects out the pairs (a Schwartzian transform). Inference reports the result as a poly array. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Code Review
This pull request implements support for Hash#sort_by by adding type inference, code generation, and runtime sorting helpers, along with corresponding tests. The feedback highlights two critical safety issues: first, declaring and rooting GC variables (_tup and _tpair) inside a loop in src/codegen_fold.c can lead to dangling stack pointers and GC root stack overflow; second, using standard qsort in lib/sp_runtime.h with a comparison function that can trigger Ruby method calls is unsafe due to potential longjmp exceptions and GC compaction.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
Implements
Hash#sort_by, which previously hit the unsupported-call diagnostic. It yields each|key, value|pair and returns the[key, value]pairs ordered by the block's value.What
emit_hash_sort_by_exprwalks the entries through the sharedemit_hash_block_evalbinder, building a[sort_key, pair]tuple per entry.sp_PolyArray_sort_by_firstsorts those tuples by their comparable sort key (sp_poly_cmpon element 0) and projects out the pairs — a Schwartzian transform. GC roots cover the dup, the working array, and the result.Testing
test/hash_sort_by.rbcovers sorting by value, by a negated value, by string length, by the key, by a key transform (k.to_s), and over a string-valued hash — through monomorphic method parameters. Expected generated from realruby.