Commit 4ab5f574

4ab5f574821dMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

Add M13: nil for the declare-then-assign pattern

Treat x = nil (and @x = nil) as the absent/default value rather than a type-pinning assignment: nil writes no longer pollute a variable's inferred type (it takes its non-nil assignments' type), and a nil assignment emits the target type's default (0 / 0.0 / NULL / empty string / (sp_Range){0}). NilNode in an expression falls back to 0.

This unblocks the very common "declare nil, assign later / in a block" pattern. True nil/false truthiness (e.g. !nil, if x with nil) remains future work -- bang_op_ruby_truthy now compiles but mismatches (it was unsupported before, so no regression).

Co-Authored-By: Claude Opus 4.8 (1M context) [email protected]

Details

Commit
4ab5f574821d
Parent
07735de43d02

src/analyze.cmodifiedView file

@@ -514,6 +514,7 @@
514514 if (!strcmp(ty, "InstanceVariableWriteNode")) {
515515 const char *nm = nt_str(nt, id, "name");
516516 TyKind vt = infer_type(c, nt_ref(nt, id, "value"));
517+ if (vt == TY_NIL) continue; /* nil write doesn't pin the ivar type */
517518 Scope *s = comp_scope_of(c, id);
518519 if (!nm || s->class_id < 0) continue;
519520 ClassInfo *ci = &c->classes[s->class_id];
@@ -576,6 +577,9 @@
576577 if (!strcmp(ty, "LocalVariableWriteNode")) {
577578 nm = nt_str(nt, id, "name");
578579 newt = infer_type(c, nt_ref(nt, id, "value"));
580+ /* a `x = nil` write doesn't pin the type: nil is the absent/default
581+ value, so the variable takes its non-nil assignments' type */
582+ if (newt == TY_NIL) newt = TY_UNKNOWN;
579583 } else if (!strcmp(ty, "LocalVariableOperatorWriteNode")) {
580584 nm = nt_str(nt, id, "name");
581585 Scope *s = comp_scope_of(c, id);