Commit 07735de4

07735de43d02Merged

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

Description

Add M12: Range as a value type

  • types/codegen: TY_RANGE -> sp_Range value struct {first,last,excl}; RangeNode -> sp_range_new(left, right, excl) (flags bit 4 = exclusive); range locals/params/returns.
  • analyze: range methods to_a (-> int_array), include?/member?/cover? (-> bool), sum/min/max/first/last/size/count/begin/end (-> int), range.map (-> array of block-body type).
  • codegen: range methods evaluate the range once into a temp, then read .first/.last/.excl; to_a via sp_IntArray_from_range; include? via sp_range_include. (a..b).each generalized to any range-typed receiver, not just literal RangeNodes.

Ranges (literal and stored in locals) with to_a/sum/include?/min/max/size /each match CRuby. make test: see count above.

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

Details

Commit
07735de43d02
Parent
b9b363271fc1

src/analyze.cmodifiedView file

@@ -130,6 +130,24 @@
130130 if (!strcmp(name, "[]=")) return ty_array_elem(rt);
131131 }
132132
133+ /* range receiver methods */
134+ if (recv >= 0 && rt == TY_RANGE) {
135+ if (!strcmp(name, "to_a")) return TY_INT_ARRAY;
136+ if (!strcmp(name, "include?") || !strcmp(name, "member?") ||
137+ !strcmp(name, "cover?")) return TY_BOOL;
138+ if (!strcmp(name, "sum") || !strcmp(name, "min") || !strcmp(name, "max") ||
139+ !strcmp(name, "first") || !strcmp(name, "last") ||
140+ !strcmp(name, "size") || !strcmp(name, "count") ||
141+ !strcmp(name, "begin") || !strcmp(name, "end")) return TY_INT;
142+ int block = nt_ref(nt, id, "block");
143+ if (block >= 0 && (!strcmp(name, "map") || !strcmp(name, "collect"))) {
144+ int body = nt_ref(nt, block, "body");
145+ int bn = 0;
146+ const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL;
147+ return ty_array_of(bn > 0 ? infer_type(c, bb[bn - 1]) : TY_UNKNOWN);
148+ }
149+ }
150+
133151 /* hash receiver methods */
134152 if (recv >= 0 && ty_is_hash(rt)) {
135153 if (!strcmp(name, "[]")) return ty_hash_val(rt);