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

@@ -4915,6 +4915,28 @@
49154915 if mname == "first" || mname == "last"
49164916 if recv >= 0
49174917 rt = infer_type(recv)
4918+ # Literal `[nil, ...].first` / `.last`: every element is nil so
4919+ # the result is nil. Without this, `.first` returns "int" via
4920+ # the int_array fallback and `.nil?` folds to false (the
4921+ # element-tag is lost the moment a nil literal lands in an
4922+ # int_array slot). Same shape as the codegen-side peephole.
4923+ # Issue #619 puzzle 5.
4924+ if @nd_type[recv] == "ArrayNode"
4925+ recv_elems = parse_id_list(@nd_elements[recv])
4926+ if recv_elems.length > 0
4927+ all_nil = 1
4928+ re_k = 0
4929+ while re_k < recv_elems.length
4930+ if @nd_type[recv_elems[re_k]] != "NilNode"
4931+ all_nil = 0
4932+ end
4933+ re_k = re_k + 1
4934+ end
4935+ if all_nil == 1
4936+ return "nil"
4937+ end
4938+ end
4939+ end
49184940 # With arg → returns array of same type
49194941 if @nd_arguments[nid] >= 0
49204942 aargs = get_args(@nd_arguments[nid])