Commit d6291adf

d6291adffe13Merged

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

Description

Add puts/print of typed arrays (element-per-line)

puts of an int/str/float array prints each element on its own line (empty array -> blank line), matching CRuby. Evaluates the array once.

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

Details

Commit
d6291adffe13
Parent
5bba0e4447c4

src/codegen.cmodifiedView file

@@ -983,6 +983,22 @@
983983 buf_puts(b, "puts(("); emit_expr(c, arg, b); buf_puts(b, ") ? \"true\" : \"false\");\n");
984984 } else if (t == TY_SYMBOL) {
985985 buf_puts(b, "puts(sp_sym_to_s("); emit_expr(c, arg, b); buf_puts(b, "));\n");
986+ } else if (ty_is_array(t) && array_kind(t)) {
987+ /* puts [a,b,c] prints each element on its own line (empty array: blank) */
988+ const char *k = array_kind(t);
989+ Buf ab; memset(&ab, 0, sizeof ab); emit_expr(c, arg, &ab);
990+ const char *a = ab.p ? ab.p : "";
991+ int ti = ++g_tmp;
992+ buf_printf(b, "if (sp_%sArray_length(%s) == 0) putchar('\\n');\n", k, a);
993+ emit_indent(b, indent);
994+ buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_%sArray_length(%s); _t%d++) ", ti, ti, k, a, ti);
995+ if (t == TY_INT_ARRAY)
996+ buf_printf(b, "printf(\"%%lld\\n\", (long long)sp_IntArray_get(%s, _t%d));\n", a, ti);
997+ else if (t == TY_FLOAT_ARRAY)
998+ buf_printf(b, "{ const char *_fs = sp_float_to_s(sp_FloatArray_get(%s, _t%d)); fputs(_fs, stdout); putchar('\\n'); }\n", a, ti);
999+ else /* str */
1000+ buf_printf(b, "{ const char *_ps = sp_StrArray_get(%s, _t%d); if (_ps) { fputs(_ps, stdout); if (!*_ps || _ps[strlen(_ps)-1] != '\\n') putchar('\\n'); } else putchar('\\n'); }\n", a, ti);
1001+ free(ab.p);
9861002 } else if (ty_is_object(t) && comp_method_in_class(c, ty_object_class(t), "to_s") >= 0) {
9871003 int cid = ty_object_class(t);
9881004 buf_puts(b, "{ const char *_ps = (const char *)(");