Commit a626da32
a626da320c2fMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 3 files · +2 added · ~1 modified
Description
fix(analyze): [nil, ...].first / .last returns nil
[nil].first.nil? should fold to true, not false. The array
literal lowered each NilNode element to sp_IntArray_push(_, 0)
under the int_array default, and .first returned int 0 -- the
nil tag was lost at literal-construction time. .nil? on int
then statically folds to false and the expression evaluates wrong.
Lifting all-nil array literals to poly_array at inference time
would fix this, but cascades through optcarrot's [nil] * N slot
init pattern (every typed read on the widened slot starts
collapsing to poly and the bitwise / arithmetic ops on the
result drop their typed-int operand). Instead, recognise the
narrower <all-nil literal>.first / .last shape at the
analyzer's CallNode return-type site and return "nil" directly.
Refs #619 puzzle 5.
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- a626da320c2f
- Parent
- 690d45c6482e
spinel_analyze.rbmodifiedView file
if mname == "first" || mname == "last" if recv >= 0 rt = infer_type(recv) # Literal `[nil, ...].first` / `.last`: every element is nil so # the result is nil. Without this, `.first` returns "int" via # the int_array fallback and `.nil?` folds to false (the # element-tag is lost the moment a nil literal lands in an # int_array slot). Same shape as the codegen-side peephole. # Issue #619 puzzle 5. if @nd_type[recv] == "ArrayNode" recv_elems = parse_id_list(@nd_elements[recv]) if recv_elems.length > 0 all_nil = 1 re_k = 0 while re_k < recv_elems.length if @nd_type[recv_elems[re_k]] != "NilNode" all_nil = 0 end re_k = re_k + 1 end if all_nil == 1 return "nil" end end end # With arg → returns array of same type if @nd_arguments[nid] >= 0 aargs = get_args(@nd_arguments[nid])test/array_literal_all_nil_first_is_nil.rbaddedView file
Loading diff…
test/array_literal_all_nil_first_is_nil.rb.expectedaddedView file
Loading diff…