Commit d36068ab
d36068ab256aMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 1 file · ~1 modified
Description
codegen: extract scalar-receiver dispatch from emit_call into emit_scalar_call
Third step of splitting emit_call by receiver type (after array and hash). Lift
the if (recv >= 0 && (rt == TY_STRING || rt == TY_INT || rt == TY_FLOAT)) { ... } block (scalar-receiver method dispatch -- evaluates the receiver once into a
temp, then splices its text) into a static emit_scalar_call helper recomputing
the shared locals it reads (name/recv/args/argc/argv/rt/a0) and returning 1/0.
Pure extraction: emitted C is byte-for-byte identical across optcarrot and all 1007 benchmark/test inputs.
Gates: 950 tests pass, optcarrot checksum 59662.
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- d36068ab256a
- Parent
- 2b56992258f8
src/codegen_call.cmodifiedView file
return 0;}void emit_call(Compiler *c, int id, Buf *b) {static int emit_scalar_call(Compiler *c, int id, Buf *b) { const NodeTable *nt = c->nt; /* `require` / `require_relative` is a compile-time directive: top-level ones are textually spliced away before codegen, and native libs are provided by the runtime. One that still reaches codegen -- indented inside an `if`, module, or method body -- is a runtime no-op (it would otherwise be an unsupported CallNode). Returns nil in value position via emit_boxed. */ { int rcv = nt_ref(nt, id, "receiver"); const char *cn = nt_str(nt, id, "name"); if (rcv < 0 && cn && (!strcmp(cn, "require") || !strcmp(cn, "require_relative"))) { buf_puts(b, "0"); return; } } if (emit_partition_expr(c, id, b)) return; if (emit_with_index_expr(c, id, b)) return; if (emit_collect_expr(c, id, b)) return; if (emit_predicate_expr(c, id, b)) return; if (emit_grep_expr(c, id, b)) return; if (emit_minmax_by_expr(c, id, b)) return; if (emit_flat_map_expr(c, id, b)) return; if (emit_filter_map_expr(c, id, b)) return; if (emit_poly_uniq_block(c, id, b)) return; if (emit_sort_cmp_expr(c, id, b)) return; if (emit_minmax_cmp_expr(c, id, b)) return; if (emit_step_array_expr(c, id, b)) return; if (emit_chunk_while_expr(c, id, b)) return; if (emit_slice_when_chunk_inspect_expr(c, id, b)) return; if (emit_product_inspect_expr(c, id, b)) return; if (emit_bsearch_expr(c, id, b)) return; if (emit_sum_block_expr(c, id, b)) return; if (emit_transform_hash_expr(c, id, b)) return; if (emit_gsub_block_expr(c, id, b)) return; if (emit_inject_expr(c, id, b)) return; if (emit_reduce_block_expr(c, id, b)) return; if (emit_sortby_expr(c, id, b)) return; if (emit_each_with_object_expr(c, id, b)) return; if (emit_tap_then_expr(c, id, b)) return; if (emit_group_by_expr(c, id, b)) return; if (emit_inline_expr(c, id, b)) return; /* value-returning yield method */ const char *name = nt_str(nt, id, "name"); int recv = nt_ref(nt, id, "receiver"); int args = nt_ref(nt, id, "arguments"); int argc = 0; const int *argv = NULL; if (args >= 0) argv = nt_arr(nt, args, "arguments", &argc); if (!name) unsupported(c, id, "call (no name)"); TyKind rt = recv >= 0 ? comp_ntype(c, recv) : TY_UNKNOWN; TyKind a0 = argc >= 1 ? comp_ntype(c, argv[0]) : TY_UNKNOWN; /* scalar receiver methods: evaluate the receiver once into rs, then splice its text (so a literal/complex receiver isn't rebuilt). */ if (recv >= 0 && (rt == TY_STRING || rt == TY_INT || rt == TY_FLOAT)) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; /* A String-typed receiver that resolved to a poly nil -- e.g. an unresolvable chain like `Rails.application.class.to_s` in a method that is compiled but never called -- emits sp_box_nil(); coerce it to a const char* (yields "" at runtime) so the string ops below type-check. */ if (rt == TY_STRING && !strcmp(r, "sp_box_nil()")) r = "sp_poly_to_s(sp_box_nil())"; int handled = 1; /* `@nested[i]` inferred as an int array (poly array of int arrays): unbox the poly element to sp_IntArray* so the surrounding code stays typed. */ if (recv >= 0 && !strcmp(name, "[]") && argc == 1 && comp_ntype(c, recv) == TY_POLY_ARRAY && comp_ntype(c, id) == TY_INT_ARRAY) { buf_puts(b, "((sp_IntArray *)((sp_PolyArray_get("); emit_expr(c, recv, b); buf_puts(b, ", "); emit_int_expr(c, argv[0], b); buf_puts(b, ")).v.p))"); return; } /* ---- Complex / Rational value types ---- */ /* Kernel#Complex(re[, im]) */ if (recv < 0 && !strcmp(name, "Complex") && argc >= 1) { buf_puts(b, "((sp_Complex){(mrb_float)("); emit_expr(c, argv[0], b); buf_puts(b, "), (mrb_float)("); if (argc >= 2) emit_expr(c, argv[1], b); else buf_puts(b, "0"); buf_puts(b, ")})"); return; } if (recv >= 0) { const char *rrty = nt_type(nt, recv); /* Complex.polar(magnitude, angle) */ if (rrty && !strcmp(rrty, "ConstantReadNode") && nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "Complex") && !strcmp(name, "polar") && argc >= 1) { buf_puts(b, "sp_complex_polar("); emit_float_expr(c, argv[0], b); buf_puts(b, ", "); if (argc >= 2) emit_float_expr(c, argv[1], b); else buf_puts(b, "0"); buf_puts(b, ")"); return; } TyKind crt = comp_ntype(c, recv); if (crt == TY_COMPLEX) { if (!strcmp(name, "real")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").re"); return; } if (!strcmp(name, "imaginary") || !strcmp(name, "imag")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").im"); return; } if (!strcmp(name, "conjugate") || !strcmp(name, "conj")) { buf_puts(b, "sp_complex_conjugate("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if ((!strcmp(name, "+") || !strcmp(name, "*")) && argc == 1 && comp_ntype(c, argv[0]) == TY_COMPLEX) { buf_printf(b, "sp_complex_%s(", name[0] == '+' ? "add" : "mul"); emit_expr(c, recv, b); buf_puts(b, ", "); emit_expr(c, argv[0], b); buf_puts(b, ")"); return; if (rt == TY_STRING) { /* blockless "a".upto("c") materializes the succ-sequence as an array */ if (!strcmp(name, "upto") && argc == 1 && nt_ref(nt, id, "block") < 0) { buf_printf(b, "sp_StrArray_from_string_range(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", 0)"); } if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "sp_complex_inspect("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } } /* Proc#curry and curry application. */ if (crt == TY_PROC && !strcmp(name, "curry") && argc == 0) { buf_puts(b, "sp_curry_new("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if (crt == TY_CURRY && (!strcmp(name, "[]") || !strcmp(name, "call") || !strcmp(name, "()")) && argc == 1) { /* The application that reaches the proc's arity realizes the curry to its (int) result; earlier applications return another curry. */ int complete = 0; TyKind cret = TY_UNKNOWN; int realize = curry_apply_info(c, id, &complete, &cret) && complete && cret == TY_INT; if (realize) buf_puts(b, "sp_curry_to_int("); buf_puts(b, "sp_curry_apply("); emit_expr(c, recv, b); buf_puts(b, ", (mrb_int)("); emit_expr(c, argv[0], b); buf_puts(b, "))"); if (realize) buf_puts(b, ")"); return; } if (crt == TY_INT && !strcmp(name, "quo") && argc == 1) { buf_puts(b, "sp_rational_new((mrb_int)("); emit_expr(c, recv, b); buf_puts(b, "), (mrb_int)("); emit_expr(c, argv[0], b); buf_puts(b, "))"); return; } if (crt == TY_RATIONAL) { if (!strcmp(name, "numerator")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").num"); return; } if (!strcmp(name, "denominator")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").den"); return; } if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "sp_rational_inspect("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } } } /* loop { break val } as expression: emit pre-statement for-loop, result via break var */ /* Kernel#caller / caller(start) / caller(start, len) -> the current stack (method-granularity, via sp_caller_now). Bare `caller` is `caller(1)`. */ if (recv < 0 && !strcmp(name, "caller") && argc <= 2) { buf_puts(b, "sp_caller("); if (argc >= 1) emit_int_expr(c, argv[0], b); else buf_puts(b, "1"); if (argc == 2) { buf_puts(b, ", 1, "); emit_int_expr(c, argv[1], b); } else buf_puts(b, ", 0, 0"); buf_puts(b, ")"); return; } if (recv < 0 && !strcmp(name, "loop") && argc == 0) { int blk = nt_ref(nt, id, "block"); if (blk >= 0) { TyKind bt = infer_type(c, id); if (bt != TY_UNKNOWN && bt != TY_NIL) { int t = ++g_tmp; emit_indent(g_pre, g_indent); emit_ctype(c, bt, g_pre); buf_printf(g_pre, " _t%d = %s;\n", t, (bt == TY_INT) ? "0" : "NULL"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "for (;;) {\n"); const char *sv_lb = g_loop_break_var; char lb_buf[32]; snprintf(lb_buf, sizeof lb_buf, "_t%d", t); g_loop_break_var = lb_buf; int lbody = nt_ref(nt, blk, "body"); emit_stmts(c, lbody, g_pre, g_indent + 1); g_loop_break_var = sv_lb; emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); buf_printf(b, "_t%d", t); return; /* string methods taking a regex-literal argument route to the engine */ else if ((!strcmp(name, "gsub") || !strcmp(name, "sub")) && argc == 2 && re_lit_index(c, argv[0]) >= 0) { const char *suf = comp_ntype(c, argv[1]) == TY_STR_STR_HASH ? "_str_str_hash" : ""; buf_printf(b, "sp_re_%s%s(sp_re_pat_%d, %s, ", name, suf, re_lit_index(c, argv[0]), r); emit_expr(c, argv[1], b); buf_puts(b, ")"); } } } /* catch(:tag) { ... [throw :tag, val] ... } as expression: a setjmp scope whose value is the block's last expression, or the thrown value. */ if (recv < 0 && !strcmp(name, "catch") && argc == 1) { int blk = nt_ref(nt, id, "block"); if (blk >= 0) { TyKind bt = comp_ntype(c, id); if (bt == TY_UNKNOWN || bt == TY_VOID) bt = TY_INT; int ptr = proc_slot_is_ptr(bt); int t = ++g_tmp; emit_indent(g_pre, g_indent); emit_ctype(c, bt, g_pre); buf_printf(g_pre, " _t%d = %s;\n", t, default_value(bt)); emit_indent(g_pre, g_indent); buf_puts(g_pre, "sp_catch_tag[sp_catch_top] = "); emit_catch_tag(c, argv[0], g_pre); buf_puts(g_pre, ";\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "sp_catch_top++;\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "if (setjmp(sp_catch_stack[sp_catch_top-1]) == 0) {\n"); int body = nt_ref(nt, blk, "body"); int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL; for (int k = 0; k < bn - 1; k++) emit_stmt(c, bb[k], g_pre, g_indent + 1); if (bn > 0) { int last = bb[bn - 1]; const char *lty = nt_type(nt, last); const char *lnm = (lty && !strcmp(lty, "CallNode")) ? nt_str(nt, last, "name") : NULL; int last_throw = (lnm && !strcmp(lnm, "throw") && nt_ref(nt, last, "receiver") < 0); TyKind lt = comp_ntype(c, last); if (last_throw || lt == TY_VOID || lt == TY_UNKNOWN) { emit_stmt(c, last, g_pre, g_indent + 1); } else { emit_indent(g_pre, g_indent + 1); buf_printf(g_pre, "_t%d = ", t); if (bt == TY_POLY && lt != TY_POLY) emit_boxed(c, last, g_pre); else emit_expr(c, last, g_pre); buf_puts(g_pre, ";\n"); } else if ((!strcmp(name, "gsub") || !strcmp(name, "sub")) && argc == 2 && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "InterpolatedRegularExpressionNode")) { Buf rp; memset(&rp, 0, sizeof rp); emit_regex_pat_to_buf(c, argv[0], &rp); buf_printf(b, "sp_re_%s(%s, %s, ", name, rp.p ? rp.p : "NULL", r); emit_expr(c, argv[1], b); buf_puts(b, ")"); free(rp.p); } emit_indent(g_pre, g_indent + 1); buf_puts(g_pre, "sp_catch_top--;\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "else {\n"); emit_indent(g_pre, g_indent + 1); buf_puts(g_pre, "sp_catch_top--;\n"); emit_indent(g_pre, g_indent + 1); if (ptr) { buf_printf(g_pre, "_t%d = (", t); emit_ctype(c, bt, g_pre); buf_printf(g_pre, ")(uintptr_t)sp_catch_val[sp_catch_top];\n"); else if (!strcmp(name, "split") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_split(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else { buf_printf(g_pre, "_t%d = sp_catch_val[sp_catch_top];\n", t); else if (!strcmp(name, "scan") && argc == 1 && re_lit_index(c, argv[0]) >= 0 && !re_has_captures(re_lit_src(c, argv[0]))) { buf_printf(b, "sp_re_scan(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); buf_printf(b, "_t%d", t); return; } } /* throw :tag[, val] -> non-local jump to the matching catch scope. */ if (recv < 0 && !strcmp(name, "throw")) { buf_puts(b, "sp_throw("); if (argc >= 1) emit_catch_tag(c, argv[0], b); else buf_puts(b, "(&(\"\\xff\")[1])"); buf_puts(b, ", "); if (argc >= 2) { if (proc_slot_is_ptr(comp_ntype(c, argv[1]))) { buf_puts(b, "(mrb_int)(uintptr_t)("); emit_expr(c, argv[1], b); buf_puts(b, ")"); else if (!strcmp(name, "scan") && argc == 1 && re_lit_index(c, argv[0]) >= 0 && re_has_captures(re_lit_src(c, argv[0]))) { buf_printf(b, "sp_re_scan_poly(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else emit_expr(c, argv[1], b); } else buf_puts(b, "0"); buf_puts(b, ")"); return; } /* system(cmd, ...) expr: run and return bool */ else if (!strcmp(name, "to_sym") || !strcmp(name, "intern")) buf_printf(b, "sp_sym_intern(%s)", r); else if (!strcmp(name, "length") || !strcmp(name, "size")) { if (g_hoist_len_var && g_hoist_len_recv && recv >= 0 && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "LocalVariableReadNode") && nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), g_hoist_len_recv)) buf_puts(b, g_hoist_len_var); else buf_printf(b, "sp_str_length(%s)", r); } else if (!strcmp(name, "bytesize")) buf_printf(b, "(mrb_int)sp_str_byte_len(%s)", r); else if (!strcmp(name, "upcase")) buf_printf(b, "sp_str_upcase(%s)", r); else if (!strcmp(name, "downcase")) buf_printf(b, "sp_str_downcase(%s)", r); else if (!strcmp(name, "capitalize")) buf_printf(b, "sp_str_capitalize(%s)", r); else if (!strcmp(name, "reverse")) buf_printf(b, "sp_str_reverse(%s)", r); else if (!strcmp(name, "strip")) buf_printf(b, "sp_str_strip(%s)", r); else if (!strcmp(name, "lstrip")) buf_printf(b, "sp_str_lstrip(%s)", r); else if (!strcmp(name, "rstrip")) buf_printf(b, "sp_str_rstrip(%s)", r); else if (!strcmp(name, "chomp") && argc == 1) { const char *a0ty = nt_type(nt, argv[0]); if (a0ty && !strcmp(a0ty, "NilNode")) { /* chomp(nil) returns the string unchanged */ buf_puts(b, r); } else { buf_printf(b, "sp_str_chomp_sep(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } } else if (!strcmp(name, "chomp")) buf_printf(b, "sp_str_chomp(%s)", r); else if (!strcmp(name, "chop")) buf_printf(b, "sp_str_chop(%s)", r); else if (!strcmp(name, "to_s") || !strcmp(name, "to_str")) buf_puts(b, r); else if ((!strcmp(name, "dup") || !strcmp(name, "clone")) && argc == 0) buf_printf(b, "sp_str_dup_external(%s)", r); else if (!strcmp(name, "inspect")) { int tv = ++g_tmp; buf_printf(b, "({ const char *_t%d = %s; _t%d ? sp_str_inspect(_t%d) : SPL(\"nil\"); })", tv, r, tv, tv); } else if (!strcmp(name, "empty?")) buf_printf(b, "(sp_str_length(%s) == 0)", r); else if (!strcmp(name, "include?") && argc == 1) { buf_printf(b, "sp_str_include(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "start_with?") && argc == 1) { buf_printf(b, "sp_str_start_with(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "end_with?") && argc == 1) { buf_printf(b, "sp_str_end_with(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "ascii_only?") && argc == 0) buf_printf(b, "sp_str_ascii_only(%s)", r); else if (!strcmp(name, "valid_encoding?") && argc == 0) buf_printf(b, "sp_str_valid_encoding(%s)", r); else if (!strcmp(name, "index") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_index_poly(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "index") && argc == 1) { /* nil-on-miss carried as the SP_INT_NIL sentinel (a nullable int) */ buf_printf(b, "sp_str_index_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "index") && argc == 2) { buf_printf(b, "sp_str_index_from_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if ((!strcmp(name, "partition") || !strcmp(name, "rpartition")) && argc == 1 && re_lit_index(c, argv[0]) < 0) { buf_printf(b, "sp_str_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "partition") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { /* [before, match, after] from the first regex match, else [s, "", ""] */ int tr = ++g_tmp; buf_printf(b, "({ sp_StrArray *_t%d = sp_StrArray_new();" " if (sp_re_match(sp_re_pat_%d, %s) >= 0) {" " sp_StrArray_push(_t%d, sp_re_match_pre); sp_StrArray_push(_t%d, sp_re_match_str);" " sp_StrArray_push(_t%d, sp_re_match_post); } else {" " sp_StrArray_push(_t%d, %s); sp_StrArray_push(_t%d, SPL(\"\")); sp_StrArray_push(_t%d, SPL(\"\")); }" " _t%d; })", tr, re_lit_index(c, argv[0]), r, tr, tr, tr, tr, r, tr, tr, tr); } else if (!strcmp(name, "rpartition") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_rpartition(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "rindex") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_rindex_opt(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "rindex") && argc == 1) { buf_printf(b, "sp_str_rindex_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rindex") && argc == 2) { buf_printf(b, "sp_str_rindex_from(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "crypt") && argc == 1) { buf_printf(b, "sp_str_crypt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "scrub") && argc == 0) buf_printf(b, "sp_str_scrub(%s, 0)", r); else if (!strcmp(name, "scrub") && argc == 1) { buf_printf(b, "sp_str_scrub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && re_lit_index(c, argv[0]) >= 0) { /* s[/re/] -> the matched substring, or nil (NULL) on no match */ buf_printf(b, "(sp_re_match(sp_re_pat_%d, %s) >= 0 ? sp_re_match_str : NULL)", re_lit_index(c, argv[0]), r); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")) { /* s[a..b] / s[a...b]; beginless/endless ranges use 0 / length */ int rn = argv[0]; int excl = (int)(nt_int(c->nt, rn, "flags", 0) & 4) ? 1 : 0; int lo = nt_ref(c->nt, rn, "left"), hi = nt_ref(c->nt, rn, "right"); buf_printf(b, "sp_str_sub_range_r(%s, ", r); if (lo >= 0) emit_expr(c, lo, b); else buf_puts(b, "0"); buf_puts(b, ", "); if (hi >= 0) { emit_expr(c, hi, b); buf_printf(b, ", %d)", excl); } else buf_printf(b, "(mrb_int)sp_str_length(%s), 0)", r); /* endless: to the end */ } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 2) { /* s[start, len] */ buf_printf(b, "sp_str_sub_range(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1) { buf_printf(b, "sp_str_char_at_or_nil(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "split") && argc == 0) buf_printf(b, "sp_str_split_ws(%s)", r); else if (!strcmp(name, "split") && argc == 1) { /* split(nil) and split(" ") are whitespace-mode; split(sep) drops trailing empties */ const char *aty = nt_type(c->nt, argv[0]); int nil_arg = aty && !strcmp(aty, "NilNode"); int ws = nil_arg || (aty && !strcmp(aty, "StringNode") && nt_str(c->nt, argv[0], "content") && !strcmp(nt_str(c->nt, argv[0], "content"), " ")); if (ws) buf_printf(b, "sp_str_split_ws(%s)", r); else { buf_printf(b, "sp_str_split_drop_trailing(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } } else if (!strcmp(name, "split") && argc == 2) { buf_printf(b, "sp_str_split_limit(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "clamp") && (argc == 2 || (argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")))) { int lo_n, hi_n; if (argc == 2) { lo_n = argv[0]; hi_n = argv[1]; } else { int rn = argv[0]; lo_n = nt_ref(c->nt, rn, "left"); hi_n = nt_ref(c->nt, rn, "right"); } int tc = ++g_tmp, tlo = ++g_tmp, thi = ++g_tmp; buf_printf(b, "({ const char *_t%d = %s; const char *_t%d = ", tc, r, tlo); emit_expr(c, lo_n, b); buf_printf(b, "; const char *_t%d = ", thi); emit_expr(c, hi_n, b); buf_printf(b, "; strcmp(_t%d, _t%d) < 0 ? _t%d : (strcmp(_t%d, _t%d) > 0 ? _t%d : _t%d); })", tc, tlo, tlo, tc, thi, thi, tc); } else if (!strcmp(name, "oct") && argc == 0) buf_printf(b, "sp_str_oct(%s)", r); else if (!strcmp(name, "hex") && argc == 0) buf_printf(b, "sp_str_to_i_base(%s, 16)", r); else if (!strcmp(name, "ord") && argc == 0) buf_printf(b, "sp_str_ord(%s)", r); else if ((!strcmp(name, "force_encoding") || !strcmp(name, "b") || !strcmp(name, "encode")) && argc <= 1) buf_printf(b, "(%s)", r); else if (!strcmp(name, "encoding") && argc == 0) buf_printf(b, "((void)(%s), sp_box_encoding(sp_encoding_utf8()))", r); else if (!strcmp(name, "dump") && argc == 0) buf_printf(b, "sp_str_dump(%s)", r); else if (!strcmp(name, "undump") && argc == 0) buf_printf(b, "sp_str_undump(%s)", r); else if (!strcmp(name, "casecmp") && argc == 1) { buf_printf(b, "sp_str_casecmp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "casecmp?") && argc == 1) { buf_printf(b, "(sp_str_casecmp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ") == 0)"); } else if (!strcmp(name, "byteslice") && argc == 2) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "byteslice") && argc == 1) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", 1)"); } else if (!strcmp(name, "setbyte") && argc == 2) { buf_printf(b, "sp_str_setbyte(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "getbyte") && argc == 1) { /* inline to a direct byte load (matches the legacy generator): the per-byte sp_str_getbyte call recomputes the string length and bounds every iteration, which the C compiler can't hoist across an aliasing setbyte. An out-of-range index reads adjacent bytes (as in legacy). */ buf_printf(b, "((mrb_int)(unsigned char)(%s)[", r); emit_int_expr(c, argv[0], b); buf_puts(b, "])"); } else if (!strcmp(name, "squeeze") && argc == 0) buf_printf(b, "sp_str_squeeze(%s)", r); else if (!strcmp(name, "squeeze") && argc == 1) { buf_printf(b, "sp_str_squeeze_chars(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "squeeze") && argc >= 2) { buf_printf(b, "sp_str_squeeze_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); } else if ((!strcmp(name, "tr") || !strcmp(name, "tr_s")) && argc == 2) { buf_printf(b, "sp_str_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "delete") && argc == 0) { buf_printf(b, "(%s)", r); return 1; } else if (!strcmp(name, "delete") && argc == 1) { buf_printf(b, "sp_str_delete(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "delete") && argc >= 2) { buf_printf(b, "sp_str_delete_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); } else if (!strcmp(name, "count") && argc == 0) { buf_printf(b, "(sp_raise_cls(\"TypeError\", \"no implicit conversion of nil into String\"), 0LL)"); return 1; } else if (!strcmp(name, "count") && argc == 1) { buf_printf(b, "sp_str_count(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "count") && argc >= 2) { buf_printf(b, "sp_str_count_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); } else if (!strcmp(name, "lines") && argc == 0) buf_printf(b, "sp_str_lines(%s)", r); else if (!strcmp(name, "lines") && argc == 1 && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "KeywordHashNode")) { int chomp_v = struct_kwarg_value(c, argv[0], "chomp"); int is_chomp = (chomp_v >= 0 && nt_type(nt, chomp_v) && !strcmp(nt_type(nt, chomp_v), "TrueNode")); buf_printf(b, "%s(%s)", is_chomp ? "sp_str_lines_chomp" : "sp_str_lines", r); } else if (!strcmp(name, "bytes") && argc == 0) buf_printf(b, "sp_str_bytes(%s)", r); else if (!strcmp(name, "codepoints") && argc == 0) buf_printf(b, "sp_str_codepoints(%s)", r); else if (!strcmp(name, "unpack") && argc == 1) { buf_printf(b, "sp_str_unpack(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "chars") && argc == 0) buf_printf(b, "sp_str_chars(%s)", r); else if ((!strcmp(name, "succ") || !strcmp(name, "next")) && argc == 0) buf_printf(b, "sp_str_succ(%s)", r); else if (!strcmp(name, "to_i") && argc == 0) buf_printf(b, "sp_str_to_i_cruby(%s)", r); else if (!strcmp(name, "to_i") && argc == 1) { buf_printf(b, "sp_str_to_i_base(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "to_f") && argc == 0) buf_printf(b, "atof(%s)", r); else if (!strcmp(name, "gsub") && argc == 2) { buf_printf(b, "sp_str_gsub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "sub") && argc == 2 && comp_ntype(c, argv[1]) == TY_STR_STR_HASH) { buf_printf(b, "sp_str_sub_str_str_hash(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "sub") && argc == 2) { buf_printf(b, "sp_str_sub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "tr") && argc == 2) { buf_printf(b, "sp_str_tr(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "center") && argc == 1) { buf_printf(b, "sp_str_center(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "center") && argc == 2) { buf_printf(b, "sp_str_center2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "ljust") && argc == 1) { buf_printf(b, "sp_str_ljust(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "ljust") && argc == 2) { buf_printf(b, "sp_str_ljust2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "rjust") && argc == 1) { buf_printf(b, "sp_str_rjust(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rjust") && argc == 2) { buf_printf(b, "sp_str_rjust2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else handled = 0; } else if (rt == TY_INT) { /* a nullable int's to_s/inspect tests the value and converts it -- bind the receiver to a temp first so a side-effecting `r` (e.g. ARGF.read, a method call) is evaluated exactly once, not twice. */ if (!strcmp(name, "to_s") && argc == 0) { int _tn = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn); } else if (!strcmp(name, "inspect")) { int _tn = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"nil\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn); } else if (!strcmp(name, "to_f")) buf_printf(b, "((mrb_float)(%s))", r); else if ((!strcmp(name, "to_i") || !strcmp(name, "to_int") || !strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 0) buf_printf(b, "(%s)", r); else if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 1) { buf_printf(b, "sp_int_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "abs")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "chr")) buf_printf(b, "sp_int_chr(%s)", r); else if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "(((%s) >> (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) & 1)"); } else if (!strcmp(name, "even?")) buf_printf(b, "((%s) %% 2 == 0)", r); else if (!strcmp(name, "odd?")) buf_printf(b, "((%s) %% 2 != 0)", r); else if (!strcmp(name, "zero?")) buf_printf(b, "((%s) == 0)", r); else if (!strcmp(name, "nonzero?")) buf_printf(b, "((%s) == 0 ? SP_INT_NIL : (%s))", r, r); else if (!strcmp(name, "positive?")) buf_printf(b, "((%s) > 0)", r); else if (!strcmp(name, "negative?")) buf_printf(b, "((%s) < 0)", r); else if (!strcmp(name, "divmod") && argc == 1) { int tb = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", tb); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, sp_idiv(%s, _t%d));" " sp_IntArray_push(_t%d, sp_imod(%s, _t%d)); _t%d; })", o, o, r, tb, o, r, tb, o); } else if (!strcmp(name, "div") && argc == 1) { buf_printf(b, "sp_idiv(%s, ", r); emit_int_divisor(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "gcd") && argc == 1) { buf_printf(b, "sp_gcd(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "lcm") && argc == 1) { buf_printf(b, "sp_lcm(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "magnitude") && argc == 0) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "modulo") && argc == 1) { buf_printf(b, "sp_imod(%s, ", r); emit_int_divisor(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "remainder") && argc == 1) { buf_printf(b, "((%s) %% (", r); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if (!strcmp(name, "size") && argc == 0) buf_puts(b, "((mrb_int)sizeof(mrb_int))"); else if (!strcmp(name, "gcdlcm") && argc == 1) { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, sp_gcd(%s, _t%d));" " sp_IntArray_push(_t%d, sp_lcm(%s, _t%d)); _t%d; })", o, o, r, ta, o, r, ta, o); } else if (!strcmp(name, "clamp") && argc == 2) { buf_printf(b, "sp_int_clamp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "clamp") && argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")) { int rn = argv[0]; int tcr = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", tcr); emit_expr(c, argv[0], b); buf_printf(b, "; sp_int_clamp(%s, _t%d.first, _t%d.last - _t%d.excl); })", r, tcr, tcr, tcr); (void)rn; } else if (!strcmp(name, "digits") && argc == 0) buf_printf(b, "sp_int_digits(%s, 10)", r); else if (!strcmp(name, "allbits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_printf(b, ")) == ("); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if (!strcmp(name, "anybits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) != 0)"); } else if (!strcmp(name, "nobits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) == 0)"); } else if (!strcmp(name, "ceildiv") && argc == 1) { buf_printf(b, "sp_ceildiv(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pow") && argc == 2) { buf_printf(b, "sp_powmod(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "pow") && argc == 1) { buf_printf(b, "sp_int_pow(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pred") && argc == 0) buf_printf(b, "((%s) - 1)", r); else if ((!strcmp(name, "succ") || !strcmp(name, "next")) && argc == 0) buf_printf(b, "((%s) + 1)", r); else if (!strcmp(name, "to_s") && argc == 1) { buf_printf(b, "sp_int_to_s_base(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "coerce") && argc == 1) { TyKind a0 = comp_ntype(c, argv[0]); if (a0 == TY_FLOAT) { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_float _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, _t%d);" " sp_FloatArray_push(_t%d, (mrb_float)(%s)); _t%d; })", o, o, ta, o, r, o); } else { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new();" " sp_IntArray_push(_t%d, _t%d);" " sp_IntArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); } } else handled = 0; } else { /* TY_FLOAT */ /* round/ceil/floor/truncate(n>0) -> Float to n decimals; else Integer */ int ndig = 0; if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 1) { const char *aty = nt_type(c->nt, argv[0]); if (aty && !strcmp(aty, "IntegerNode")) ndig = (int)nt_int(c->nt, argv[0], "value", 0); } const char *cfn = !strcmp(name, "floor") ? "floor" : !strcmp(name, "ceil") ? "ceil" : !strcmp(name, "truncate") ? "trunc" : "round"; if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate"))) { if (ndig > 0) buf_printf(b, "({ double _f = pow(10, %d); %s((%s) * _f) / _f; })", ndig, cfn, r); else if (ndig < 0) /* round to a power of ten left of the decimal -> Integer */ buf_printf(b, "({ double _f = pow(10, %d); (mrb_int)(%s((%s) / _f) * _f); })", -ndig, cfn, r); else buf_printf(b, "((mrb_int)%s(%s))", cfn, r); } else if (!strcmp(name, "to_i")) buf_printf(b, "((mrb_int)(%s))", r); else if (!strcmp(name, "to_f")) buf_printf(b, "(%s)", r); else if (!strcmp(name, "divmod") && argc == 1) { /* Float#divmod(n) -> [floor(x/n) (Integer), x - q*n (Float)] */ int tx = ++g_tmp, tn = ++g_tmp, tq = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_float _t%d = (%s); mrb_float _t%d = ", tx, r, tn); emit_expr(c, argv[0], b); buf_printf(b, "; if (isnan(_t%d) || isnan(_t%d)) sp_raise_cls(\"FloatDomainError\", \"NaN\");" " if (_t%d == 0.0) sp_raise_cls(\"ZeroDivisionError\", \"divided by 0\");" " mrb_int _t%d = (mrb_int)floor(_t%d / _t%d); sp_PolyArray *_t%d = sp_PolyArray_new();" " sp_PolyArray_push(_t%d, sp_box_int(_t%d));" " sp_PolyArray_push(_t%d, sp_box_float(_t%d - (mrb_float)_t%d * _t%d)); _t%d; })", tx, tn, tn, tq, tx, tn, o, o, tq, o, tx, tq, tn, o); } else if (!strcmp(name, "to_s")) buf_printf(b, "sp_float_opt_to_s(%s)", r); else if (!strcmp(name, "inspect")) buf_printf(b, "sp_float_opt_inspect(%s)", r); else if (!strcmp(name, "abs")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "zero?")) buf_printf(b, "((%s) == 0.0)", r); else if (!strcmp(name, "nan?")) buf_printf(b, "(isnan(%s) != 0)", r); else if (!strcmp(name, "finite?")) buf_printf(b, "(isfinite(%s) != 0)", r); else if (!strcmp(name, "infinite?")) buf_printf(b, "(isinf(%s) ? ((%s) > 0 ? 1LL : -1LL) : SP_INT_NIL)", r, r); else if (!strcmp(name, "positive?")) buf_printf(b, "((%s) > 0)", r); else if (!strcmp(name, "negative?")) buf_printf(b, "((%s) < 0)", r); else if (!strcmp(name, "next_float")) buf_printf(b, "nextafter(%s, INFINITY)", r); else if (!strcmp(name, "prev_float")) buf_printf(b, "nextafter(%s, -INFINITY)", r); else if (!strcmp(name, "magnitude")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "modulo") && argc == 1) { buf_printf(b, "fmod(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "coerce") && argc == 1) { TyKind a0 = comp_ntype(c, argv[0]); int ta = ++g_tmp, o = ++g_tmp; if (a0 == TY_INT) { buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, (mrb_float)_t%d);" " sp_FloatArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); } else { buf_printf(b, "({ mrb_float _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, _t%d);" " sp_FloatArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); } } else handled = 0; } free(rs.p); if (handled) return 1; } return 0;}void emit_call(Compiler *c, int id, Buf *b) { const NodeTable *nt = c->nt; /* `require` / `require_relative` is a compile-time directive: top-level ones are textually spliced away before codegen, and native libs are provided by the runtime. One that still reaches codegen -- indented inside an `if`, module, or method body -- is a runtime no-op (it would otherwise be an unsupported CallNode). Returns nil in value position via emit_boxed. */ { int rcv = nt_ref(nt, id, "receiver"); const char *cn = nt_str(nt, id, "name"); if (rcv < 0 && cn && (!strcmp(cn, "require") || !strcmp(cn, "require_relative"))) { buf_puts(b, "0"); return; } } if (emit_partition_expr(c, id, b)) return; if (emit_with_index_expr(c, id, b)) return; if (emit_collect_expr(c, id, b)) return; if (emit_predicate_expr(c, id, b)) return; if (emit_grep_expr(c, id, b)) return; if (emit_minmax_by_expr(c, id, b)) return; if (emit_flat_map_expr(c, id, b)) return; if (emit_filter_map_expr(c, id, b)) return; if (emit_poly_uniq_block(c, id, b)) return; if (emit_sort_cmp_expr(c, id, b)) return; if (emit_minmax_cmp_expr(c, id, b)) return; if (emit_step_array_expr(c, id, b)) return; if (emit_chunk_while_expr(c, id, b)) return; if (emit_slice_when_chunk_inspect_expr(c, id, b)) return; if (emit_product_inspect_expr(c, id, b)) return; if (emit_bsearch_expr(c, id, b)) return; if (emit_sum_block_expr(c, id, b)) return; if (emit_transform_hash_expr(c, id, b)) return; if (emit_gsub_block_expr(c, id, b)) return; if (emit_inject_expr(c, id, b)) return; if (emit_reduce_block_expr(c, id, b)) return; if (emit_sortby_expr(c, id, b)) return; if (emit_each_with_object_expr(c, id, b)) return; if (emit_tap_then_expr(c, id, b)) return; if (emit_group_by_expr(c, id, b)) return; if (emit_inline_expr(c, id, b)) return; /* value-returning yield method */ const char *name = nt_str(nt, id, "name"); int recv = nt_ref(nt, id, "receiver"); int args = nt_ref(nt, id, "arguments"); int argc = 0; const int *argv = NULL; if (args >= 0) argv = nt_arr(nt, args, "arguments", &argc); if (!name) unsupported(c, id, "call (no name)"); /* `@nested[i]` inferred as an int array (poly array of int arrays): unbox the poly element to sp_IntArray* so the surrounding code stays typed. */ if (recv >= 0 && !strcmp(name, "[]") && argc == 1 && comp_ntype(c, recv) == TY_POLY_ARRAY && comp_ntype(c, id) == TY_INT_ARRAY) { buf_puts(b, "((sp_IntArray *)((sp_PolyArray_get("); emit_expr(c, recv, b); buf_puts(b, ", "); emit_int_expr(c, argv[0], b); buf_puts(b, ")).v.p))"); return; } /* ---- Complex / Rational value types ---- */ /* Kernel#Complex(re[, im]) */ if (recv < 0 && !strcmp(name, "Complex") && argc >= 1) { buf_puts(b, "((sp_Complex){(mrb_float)("); emit_expr(c, argv[0], b); buf_puts(b, "), (mrb_float)("); if (argc >= 2) emit_expr(c, argv[1], b); else buf_puts(b, "0"); buf_puts(b, ")})"); return; } if (recv >= 0) { const char *rrty = nt_type(nt, recv); /* Complex.polar(magnitude, angle) */ if (rrty && !strcmp(rrty, "ConstantReadNode") && nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "Complex") && !strcmp(name, "polar") && argc >= 1) { buf_puts(b, "sp_complex_polar("); emit_float_expr(c, argv[0], b); buf_puts(b, ", "); if (argc >= 2) emit_float_expr(c, argv[1], b); else buf_puts(b, "0"); buf_puts(b, ")"); return; } TyKind crt = comp_ntype(c, recv); if (crt == TY_COMPLEX) { if (!strcmp(name, "real")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").re"); return; } if (!strcmp(name, "imaginary") || !strcmp(name, "imag")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").im"); return; } if (!strcmp(name, "conjugate") || !strcmp(name, "conj")) { buf_puts(b, "sp_complex_conjugate("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if ((!strcmp(name, "+") || !strcmp(name, "*")) && argc == 1 && comp_ntype(c, argv[0]) == TY_COMPLEX) { buf_printf(b, "sp_complex_%s(", name[0] == '+' ? "add" : "mul"); emit_expr(c, recv, b); buf_puts(b, ", "); emit_expr(c, argv[0], b); buf_puts(b, ")"); return; } if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "sp_complex_inspect("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } } /* Proc#curry and curry application. */ if (crt == TY_PROC && !strcmp(name, "curry") && argc == 0) { buf_puts(b, "sp_curry_new("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if (crt == TY_CURRY && (!strcmp(name, "[]") || !strcmp(name, "call") || !strcmp(name, "()")) && argc == 1) { /* The application that reaches the proc's arity realizes the curry to its (int) result; earlier applications return another curry. */ int complete = 0; TyKind cret = TY_UNKNOWN; int realize = curry_apply_info(c, id, &complete, &cret) && complete && cret == TY_INT; if (realize) buf_puts(b, "sp_curry_to_int("); buf_puts(b, "sp_curry_apply("); emit_expr(c, recv, b); buf_puts(b, ", (mrb_int)("); emit_expr(c, argv[0], b); buf_puts(b, "))"); if (realize) buf_puts(b, ")"); return; } if (crt == TY_INT && !strcmp(name, "quo") && argc == 1) { buf_puts(b, "sp_rational_new((mrb_int)("); emit_expr(c, recv, b); buf_puts(b, "), (mrb_int)("); emit_expr(c, argv[0], b); buf_puts(b, "))"); return; } if (crt == TY_RATIONAL) { if (!strcmp(name, "numerator")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").num"); return; } if (!strcmp(name, "denominator")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_puts(b, ").den"); return; } if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "sp_rational_inspect("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } } } /* loop { break val } as expression: emit pre-statement for-loop, result via break var */ /* Kernel#caller / caller(start) / caller(start, len) -> the current stack (method-granularity, via sp_caller_now). Bare `caller` is `caller(1)`. */ if (recv < 0 && !strcmp(name, "caller") && argc <= 2) { buf_puts(b, "sp_caller("); if (argc >= 1) emit_int_expr(c, argv[0], b); else buf_puts(b, "1"); if (argc == 2) { buf_puts(b, ", 1, "); emit_int_expr(c, argv[1], b); } else buf_puts(b, ", 0, 0"); buf_puts(b, ")"); return; } if (recv < 0 && !strcmp(name, "loop") && argc == 0) { int blk = nt_ref(nt, id, "block"); if (blk >= 0) { TyKind bt = infer_type(c, id); if (bt != TY_UNKNOWN && bt != TY_NIL) { int t = ++g_tmp; emit_indent(g_pre, g_indent); emit_ctype(c, bt, g_pre); buf_printf(g_pre, " _t%d = %s;\n", t, (bt == TY_INT) ? "0" : "NULL"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "for (;;) {\n"); const char *sv_lb = g_loop_break_var; char lb_buf[32]; snprintf(lb_buf, sizeof lb_buf, "_t%d", t); g_loop_break_var = lb_buf; int lbody = nt_ref(nt, blk, "body"); emit_stmts(c, lbody, g_pre, g_indent + 1); g_loop_break_var = sv_lb; emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); buf_printf(b, "_t%d", t); return; } } } /* catch(:tag) { ... [throw :tag, val] ... } as expression: a setjmp scope whose value is the block's last expression, or the thrown value. */ if (recv < 0 && !strcmp(name, "catch") && argc == 1) { int blk = nt_ref(nt, id, "block"); if (blk >= 0) { TyKind bt = comp_ntype(c, id); if (bt == TY_UNKNOWN || bt == TY_VOID) bt = TY_INT; int ptr = proc_slot_is_ptr(bt); int t = ++g_tmp; emit_indent(g_pre, g_indent); emit_ctype(c, bt, g_pre); buf_printf(g_pre, " _t%d = %s;\n", t, default_value(bt)); emit_indent(g_pre, g_indent); buf_puts(g_pre, "sp_catch_tag[sp_catch_top] = "); emit_catch_tag(c, argv[0], g_pre); buf_puts(g_pre, ";\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "sp_catch_top++;\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "if (setjmp(sp_catch_stack[sp_catch_top-1]) == 0) {\n"); int body = nt_ref(nt, blk, "body"); int bn = 0; const int *bb = body >= 0 ? nt_arr(nt, body, "body", &bn) : NULL; for (int k = 0; k < bn - 1; k++) emit_stmt(c, bb[k], g_pre, g_indent + 1); if (bn > 0) { int last = bb[bn - 1]; const char *lty = nt_type(nt, last); const char *lnm = (lty && !strcmp(lty, "CallNode")) ? nt_str(nt, last, "name") : NULL; int last_throw = (lnm && !strcmp(lnm, "throw") && nt_ref(nt, last, "receiver") < 0); TyKind lt = comp_ntype(c, last); if (last_throw || lt == TY_VOID || lt == TY_UNKNOWN) { emit_stmt(c, last, g_pre, g_indent + 1); } else { emit_indent(g_pre, g_indent + 1); buf_printf(g_pre, "_t%d = ", t); if (bt == TY_POLY && lt != TY_POLY) emit_boxed(c, last, g_pre); else emit_expr(c, last, g_pre); buf_puts(g_pre, ";\n"); } } emit_indent(g_pre, g_indent + 1); buf_puts(g_pre, "sp_catch_top--;\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); emit_indent(g_pre, g_indent); buf_puts(g_pre, "else {\n"); emit_indent(g_pre, g_indent + 1); buf_puts(g_pre, "sp_catch_top--;\n"); emit_indent(g_pre, g_indent + 1); if (ptr) { buf_printf(g_pre, "_t%d = (", t); emit_ctype(c, bt, g_pre); buf_printf(g_pre, ")(uintptr_t)sp_catch_val[sp_catch_top];\n"); } else { buf_printf(g_pre, "_t%d = sp_catch_val[sp_catch_top];\n", t); } emit_indent(g_pre, g_indent); buf_puts(g_pre, "}\n"); buf_printf(b, "_t%d", t); return; } } /* throw :tag[, val] -> non-local jump to the matching catch scope. */ if (recv < 0 && !strcmp(name, "throw")) { buf_puts(b, "sp_throw("); if (argc >= 1) emit_catch_tag(c, argv[0], b); else buf_puts(b, "(&(\"\\xff\")[1])"); buf_puts(b, ", "); if (argc >= 2) { if (proc_slot_is_ptr(comp_ntype(c, argv[1]))) { buf_puts(b, "(mrb_int)(uintptr_t)("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else emit_expr(c, argv[1], b); } else buf_puts(b, "0"); buf_puts(b, ")"); return; } /* system(cmd, ...) expr: run and return bool */ if (recv < 0 && !strcmp(name, "system") && argc >= 1) { int ts = ++g_tmp; buf_printf(b, "({ const char *_sys_%d[] = { ", ts); } buf_printf(b, " _t%d; })", rh); return; } if ((!strcmp(name, "members")) && argc == 0) { int rm = ++g_tmp; buf_printf(b, "({ sp_PolyArray *_t%d = sp_PolyArray_new(); SP_GC_ROOT(_t%d);", rm, rm); for (int i = 0; i < sc->nivars; i++) buf_printf(b, " sp_PolyArray_push(_t%d, sp_box_sym((sp_sym)%d));", rm, comp_sym_intern(c, sc->ivars[i] + 1)); buf_printf(b, " _t%d; })", rm); return; } if (!strcmp(name, "dig") && argc >= 1) { /* literal key resolves a member at compile time */ int mi = -1; const char *kty = nt_type(nt, argv[0]); if (kty && !strcmp(kty, "SymbolNode")) { char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", nt_str(nt, argv[0], "value")); mi = comp_ivar_index(sc, ivn); } else if (kty && !strcmp(kty, "IntegerNode")) { int v = (int)nt_int(nt, argv[0], "value", -1); if (v >= 0 && v < sc->nivars) mi = v; } if (mi >= 0) { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); char fld[300]; snprintf(fld, sizeof fld, "_t%d->iv_%s", t, sc->ivars[mi] + 1); TyKind mt = sc->ivar_types[mi]; buf_printf(b, "({ sp_%s *_t%d = %s; ", sc->name, t, rb.p ? rb.p : ""); free(rb.p); if (argc == 1) buf_puts(b, fld); else if (ty_is_hash(mt) && argc == 2) { const char *hn = ty_hash_cname(mt); buf_printf(b, "sp_%sHash_%s(%s, ", hn, ty_hash_val(mt) == TY_INT ? "get_opt" : "get", fld); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (ty_is_array(mt) && argc == 2) { buf_printf(b, "sp_%sArray_get(%s, ", array_kind(mt), fld); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else buf_puts(b, fld); buf_puts(b, "; })"); return; } } if (!strcmp(name, "[]") && argc == 1) { /* struct[:sym] or struct[int_literal]: return member value boxed to poly */ int mi = -1; const char *kty = nt_type(nt, argv[0]); if (kty && !strcmp(kty, "SymbolNode") && nt_str(nt, argv[0], "value")) { char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", nt_str(nt, argv[0], "value")); mi = comp_ivar_index(sc, ivn); } else if (kty && !strcmp(kty, "IntegerNode")) { long long v = (long long)nt_int(nt, argv[0], "value", 0); if (v < 0) v += (long long)sc->nivars; if (v >= 0 && v < sc->nivars) mi = (int)v; } if (mi >= 0) { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_%s *_t%d = %s; ", sc->name, t, rb.p ? rb.p : ""); free(rb.p); buf_printf(b, "_t%d->iv_%s; })", t, sc->ivars[mi] + 1); return; } /* general: generate chain of comparisons */ if (sc->nivars > 0) { int t = ++g_tmp, tk = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_%s *_t%d = %s; sp_RbVal _t%d = ", sc->name, t, rb.p ? rb.p : "", tk); free(rb.p); emit_boxed(c, argv[0], b); buf_puts(b, ";"); for (int i = 0; i < sc->nivars; i++) { buf_printf(b, " if(sp_rbval_eql_key(_t%d,sp_box_sym((sp_sym)%d))||sp_rbval_eql_key(_t%d,sp_box_int(%dLL))){", tk, comp_sym_intern(c, sc->ivars[i]+1), tk, (long long)i); char fld2[300]; snprintf(fld2, sizeof fld2, "_t%d->iv_%s", t, sc->ivars[i] + 1); emit_boxed_text(c, sc->ivar_types[i], fld2, b); buf_printf(b, ";} else"); } buf_puts(b, " sp_box_nil(); })"); return; } } } /* object method call: sp_<DefClass>_<m>((sp_<DefClass>*)&recv, args) */ if (recv >= 0 && ty_is_object(rt)) { int cid = ty_object_class(rt); /* undef'd method: raise NoMethodError */ if (comp_is_undeffed_in_chain(c, cid, name)) { TyKind ret_ty = comp_ntype(c, id); buf_printf(b, "(sp_raise_cls(\"NoMethodError\",\"undefined method '%s' for an instance of %s\"),%s)", name, c->classes[cid].name, ret_ty == TY_RANGE ? "(sp_Range){0}" : default_value(ret_ty)); return; } /* attr reader -> field access (recv).iv_x */ if (comp_reader_in_chain(c, cid, name, NULL)) { const char *rn2 = comp_resolve_alias(c, cid, name); buf_puts(b, "("); emit_expr(c, recv, b); buf_printf(b, ")%siv_%s", comp_ty_value_obj(c, rt) ? "." : "->", rn2); return; } int mi = comp_method_in_chain(c, cid, name, NULL); if (mi >= 0) { /* a value-type receiver is passed by value; an ordinary object by pointer. For a value recv we hand emit_dispatch the value expression (lvalue or hoisted temp); the method takes `self` by value. */ if (comp_ty_value_obj(c, rt)) { char selfv[64]; const char *rty = nt_type(nt, recv); if (rty && (!strcmp(rty, "LocalVariableReadNode") || !strcmp(rty, "InstanceVariableReadNode") || !strcmp(rty, "SelfNode"))) { Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); snprintf(selfv, sizeof selfv, "%s", rb.p ? rb.p : ""); free(rb.p); } else { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); emit_ctype(c, rt, g_pre); buf_printf(g_pre, " _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); snprintf(selfv, sizeof selfv, "_t%d", t); } emit_dispatch(c, cid, name, selfv, nt_ref(nt, id, "arguments"), nt_ref(nt, id, "block"), b); return; } /* receiver is a pointer; reuse it directly if it's a simple lvalue, else stash in a temp (the virtual-dispatch switch references it multiple times) */ char selfptr[64]; const char *rty = nt_type(nt, recv); if (rty && (!strcmp(rty, "LocalVariableReadNode") || !strcmp(rty, "InstanceVariableReadNode") || !strcmp(rty, "SelfNode"))) { Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); snprintf(selfptr, sizeof selfptr, "%s", rb.p ? rb.p : ""); free(rb.p); } else { int t = ++g_tmp; /* emit the receiver first so any setup it pushes into g_pre is fully flushed before we write this temp's declaration line */ Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); emit_ctype(c, rt, g_pre); buf_printf(g_pre, " _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); /* Root the hoisted receiver: a freshly constructed object (e.g. Scene.new.render(...)) must survive any GC the call triggers. */ emit_indent(g_pre, g_indent); buf_printf(g_pre, "SP_GC_ROOT(_t%d);\n", t); snprintf(selfptr, sizeof selfptr, "_t%d", t); } emit_dispatch(c, cid, name, selfptr, nt_ref(nt, id, "arguments"), nt_ref(nt, id, "block"), b); return; } } /* Time instance methods: sp_Time is a value -- splice the receiver once. */ if (recv >= 0 && rt == TY_TIME) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if (!strcmp(name, "utc") || !strcmp(name, "gmtime") || !strcmp(name, "getutc")) buf_printf(b, "sp_time_utc(%s)", r); else if (!strcmp(name, "localtime") || !strcmp(name, "getlocal")) buf_printf(b, "sp_time_localtime(%s)", r); else if (!strcmp(name, "year")) buf_printf(b, "sp_time_year(%s)", r); else if (!strcmp(name, "mon") || !strcmp(name, "month")) buf_printf(b, "sp_time_mon(%s)", r); else if (!strcmp(name, "day") || !strcmp(name, "mday")) buf_printf(b, "sp_time_mday(%s)", r); else if (!strcmp(name, "hour")) buf_printf(b, "sp_time_hour(%s)", r); else if (!strcmp(name, "min")) buf_printf(b, "sp_time_min(%s)", r); else if (!strcmp(name, "sec")) buf_printf(b, "sp_time_sec(%s)", r); else if (!strcmp(name, "wday")) buf_printf(b, "sp_time_wday(%s)", r); else if (!strcmp(name, "yday")) buf_printf(b, "sp_time_yday(%s)", r); else if (!strcmp(name, "to_i") || !strcmp(name, "tv_sec")) buf_printf(b, "(%s).tv_sec", r); else if (!strcmp(name, "to_f")) buf_printf(b, "((mrb_float)(%s).tv_sec + (mrb_float)(%s).tv_nsec / 1e9)", r, r); else if (!strcmp(name, "subsec")) buf_printf(b, "((mrb_float)(%s).tv_nsec / 1e9)", r); else if (!strcmp(name, "tv_usec") || !strcmp(name, "usec")) buf_printf(b, "((mrb_int)(%s).tv_nsec / 1000)", r); else if (!strcmp(name, "tv_nsec") || !strcmp(name, "nsec")) buf_printf(b, "((mrb_int)(%s).tv_nsec)", r); else if (!strcmp(name, "utc?") || !strcmp(name, "gmt?")) buf_printf(b, "((%s).is_utc != 0)", r); else if (!strcmp(name, "dst?") || !strcmp(name, "isdst")) buf_printf(b, "(sp_time_isdst(%s) != 0)", r); else if (!strcmp(name, "utc_offset") || !strcmp(name, "gmt_offset") || !strcmp(name, "gmtoff")) buf_printf(b, "sp_time_utc_offset(%s)", r); else if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) buf_printf(b, "sp_time_inspect_v(%s)", r); else if (!strcmp(name, "iso8601")) buf_printf(b, "sp_time_iso8601(%s)", r); else if (!strcmp(name, "zone")) buf_printf(b, "sp_time_zone(%s)", r); else if (!strcmp(name, "class")) buf_puts(b, "SPL(\"Time\")"); else if (!strcmp(name, "strftime") && argc == 1) { buf_printf(b, "sp_time_strftime(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "+") || !strcmp(name, "-")) && argc == 1) { buf_printf(b, "sp_time_add(%s, %s(mrb_float)(", r, name[0] == '-' ? "-" : ""); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if ((!strcmp(name, "<") || !strcmp(name, ">") || !strcmp(name, "<=") || !strcmp(name, ">=") || !strcmp(name, "==") || !strcmp(name, "!=")) && argc == 1) { int tt = ++g_tmp, tu = ++g_tmp; buf_puts(b, "({ sp_Time _t"); buf_printf(b, "%d = %s; sp_Time _t%d = ", tt, r, tu); emit_expr(c, argv[0], b); buf_printf(b, "; sp_time_cmp(_t%d, _t%d) %s 0; })", tt, tu, name); } else if (!strcmp(name, "<=>") && argc == 1) { int tt = ++g_tmp, tu = ++g_tmp; buf_puts(b, "({ sp_Time _t"); buf_printf(b, "%d = %s; sp_Time _t%d = ", tt, r, tu); emit_expr(c, argv[0], b); buf_printf(b, "; (mrb_int)sp_time_cmp(_t%d, _t%d); })", tt, tu); } else done = 0; free(rs.p); if (done) return; } /* StringScanner instance methods. String-returning methods may yield NULL (nil) on a miss; the NULL-aware string output operators render that. */ if (recv >= 0 && rt == TY_STRINGSCANNER) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if ((!strcmp(name, "scan") || !strcmp(name, "check") || !strcmp(name, "scan_until")) && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_StringScanner_%s(%s, sp_re_pat_%d)", name, r, re_lit_index(c, argv[0])); } else if (!strcmp(name, "matched")) buf_printf(b, "sp_StringScanner_matched(%s)", r); else if (!strcmp(name, "matched?")) buf_printf(b, "sp_StringScanner_matched_p(%s)", r); else if (!strcmp(name, "pre_match")) buf_printf(b, "sp_StringScanner_pre_match(%s)", r); else if (!strcmp(name, "post_match")) buf_printf(b, "sp_StringScanner_post_match(%s)", r); else if (!strcmp(name, "pos") || !strcmp(name, "charpos")) buf_printf(b, "sp_StringScanner_pos(%s)", r); else if (!strcmp(name, "pos=") && argc == 1) { buf_printf(b, "sp_StringScanner_pos_set(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rest")) buf_printf(b, "sp_StringScanner_rest(%s)", r); else if (!strcmp(name, "rest?")) buf_printf(b, "sp_StringScanner_rest_p(%s)", r); else if (!strcmp(name, "rest_size")) buf_printf(b, "sp_StringScanner_rest_size(%s)", r); else if (!strcmp(name, "string")) buf_printf(b, "sp_StringScanner_string(%s)", r); else if (!strcmp(name, "eos?")) buf_printf(b, "sp_StringScanner_eos_p(%s)", r); else if (!strcmp(name, "getch")) buf_printf(b, "sp_StringScanner_getch(%s)", r); else if (!strcmp(name, "peek") && argc == 1) { buf_printf(b, "sp_StringScanner_peek(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "sp_StringScanner_aref(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "reset")) buf_printf(b, "(sp_StringScanner_reset(%s), %s)", r, r); else if (!strcmp(name, "terminate")) buf_printf(b, "(sp_StringScanner_terminate(%s), %s)", r, r); else if (!strcmp(name, "unscan")) buf_printf(b, "(sp_StringScanner_unscan(%s), %s)", r, r); else done = 0; free(rs.p); if (done) return; } /* MatchData instance methods (sp_MatchData *, nullable on no-match). */ if (recv >= 0 && rt == TY_MATCHDATA) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "sp_MatchData_aref(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pre_match")) buf_printf(b, "sp_MatchData_pre_match(%s)", r); else if (!strcmp(name, "post_match")) buf_printf(b, "sp_MatchData_post_match(%s)", r); else if (!strcmp(name, "to_s")) buf_printf(b, "sp_MatchData_to_s(%s)", r); else if ((!strcmp(name, "length") || !strcmp(name, "size")) && argc == 0) buf_printf(b, "sp_MatchData_length(%s)", r); else if (!strcmp(name, "begin") && argc == 1) { buf_printf(b, "sp_MatchData_begin(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "end") && argc == 1) { buf_printf(b, "sp_MatchData_end(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); if ((!strcmp(name, "members")) && argc == 0) { int rm = ++g_tmp; buf_printf(b, "({ sp_PolyArray *_t%d = sp_PolyArray_new(); SP_GC_ROOT(_t%d);", rm, rm); for (int i = 0; i < sc->nivars; i++) buf_printf(b, " sp_PolyArray_push(_t%d, sp_box_sym((sp_sym)%d));", rm, comp_sym_intern(c, sc->ivars[i] + 1)); buf_printf(b, " _t%d; })", rm); return; } else if (!strcmp(name, "offset") && argc == 1) { buf_printf(b, "sp_MatchData_offset(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); if (!strcmp(name, "dig") && argc >= 1) { /* literal key resolves a member at compile time */ int mi = -1; const char *kty = nt_type(nt, argv[0]); if (kty && !strcmp(kty, "SymbolNode")) { char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", nt_str(nt, argv[0], "value")); mi = comp_ivar_index(sc, ivn); } else if (kty && !strcmp(kty, "IntegerNode")) { int v = (int)nt_int(nt, argv[0], "value", -1); if (v >= 0 && v < sc->nivars) mi = v; } if (mi >= 0) { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); char fld[300]; snprintf(fld, sizeof fld, "_t%d->iv_%s", t, sc->ivars[mi] + 1); TyKind mt = sc->ivar_types[mi]; buf_printf(b, "({ sp_%s *_t%d = %s; ", sc->name, t, rb.p ? rb.p : ""); free(rb.p); if (argc == 1) buf_puts(b, fld); else if (ty_is_hash(mt) && argc == 2) { const char *hn = ty_hash_cname(mt); buf_printf(b, "sp_%sHash_%s(%s, ", hn, ty_hash_val(mt) == TY_INT ? "get_opt" : "get", fld); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (ty_is_array(mt) && argc == 2) { buf_printf(b, "sp_%sArray_get(%s, ", array_kind(mt), fld); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else buf_puts(b, fld); buf_puts(b, "; })"); return; } } else if (!strcmp(name, "captures")) buf_printf(b, "sp_MatchData_captures(%s)", r); else if (!strcmp(name, "to_a")) buf_printf(b, "sp_MatchData_to_a(%s)", r); else if (!strcmp(name, "nil?")) buf_printf(b, "(%s == 0)", r); else unsupported(c, id, "MatchData method"); free(rs.p); return; } /* StringIO instance methods (a non-GC heap buffer behind sp_StringIO *). */ if (recv >= 0 && rt == TY_STRINGIO) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if (!strcmp(name, "string")) buf_printf(b, "sp_StringIO_string(%s)", r); else if (!strcmp(name, "pos") || !strcmp(name, "tell")) buf_printf(b, "sp_StringIO_pos(%s)", r); else if (!strcmp(name, "size") || !strcmp(name, "length")) buf_printf(b, "sp_StringIO_size(%s)", r); else if (!strcmp(name, "lineno")) buf_printf(b, "(%s)->lineno", r); else if (!strcmp(name, "puts") && argc == 0) buf_printf(b, "sp_StringIO_puts_empty(%s)", r); else if (!strcmp(name, "puts") && argc == 1) { buf_printf(b, "sp_StringIO_puts(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "print") && argc == 1) { buf_printf(b, "sp_StringIO_print(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "write") || !strcmp(name, "<<")) && argc == 1) { buf_printf(b, "sp_StringIO_write(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "putc") && argc == 1) { if (comp_ntype(c, argv[0]) == TY_STRING) { buf_printf(b, "sp_StringIO_putc(%s, (mrb_int)(unsigned char)(", r); emit_expr(c, argv[0], b); buf_puts(b, ")[0])"); } else { buf_printf(b, "sp_StringIO_putc(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } } else if (!strcmp(name, "fsync") || !strcmp(name, "fileno") || !strcmp(name, "pid")) buf_printf(b, "((void)(%s), 0)", r); else if (!strcmp(name, "read") && argc == 0) buf_printf(b, "sp_StringIO_read(%s)", r); else if (!strcmp(name, "read") && argc == 1) { buf_printf(b, "sp_StringIO_read_n(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "gets")) buf_printf(b, "sp_box_nullable_str(sp_StringIO_gets(%s))", r); else if (!strcmp(name, "getc")) buf_printf(b, "sp_box_nullable_str(sp_StringIO_getc(%s))", r); else if (!strcmp(name, "getbyte")) buf_printf(b, "sp_StringIO_getbyte(%s)", r); else if (!strcmp(name, "rewind")) buf_printf(b, "sp_StringIO_rewind(%s)", r); else if (!strcmp(name, "seek") && argc >= 1) { buf_printf(b, "sp_StringIO_seek(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "truncate") && argc == 1) { buf_printf(b, "sp_StringIO_truncate(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "eof?") || !strcmp(name, "eof")) buf_printf(b, "sp_StringIO_eof_p(%s)", r); else if (!strcmp(name, "close")) buf_printf(b, "sp_StringIO_close(%s)", r); else if (!strcmp(name, "closed?")) buf_printf(b, "sp_StringIO_closed_p(%s)", r); else if (!strcmp(name, "flush")) buf_printf(b, "sp_StringIO_flush(%s)", r); else if (!strcmp(name, "sync")) buf_printf(b, "sp_StringIO_sync(%s)", r); else if (!strcmp(name, "isatty") || !strcmp(name, "tty?")) buf_printf(b, "sp_StringIO_isatty(%s)", r); else done = 0; free(rs.p); if (done) return; } /* Array-reduction methods on a boxed array element of a poly array (e.g. `runs.map { |r| r.sum }` over chunk_while runs). The runtime helper switches on the element's cls_id. Skipped when a user class defines the same method (it falls through to the general poly dispatch below). */ if (recv >= 0 && rt == TY_POLY && argc == 0 && nt_ref(nt, id, "block") < 0) { const char *pm = NULL; if (!strcmp(name, "sum")) pm = "sp_poly_sum"; else if (!strcmp(name, "min")) pm = "sp_poly_min"; else if (!strcmp(name, "max")) pm = "sp_poly_max"; else if (!strcmp(name, "first")) pm = "sp_poly_first"; else if (!strcmp(name, "last")) pm = "sp_poly_last"; /* a Thread (Fiber-modelled) carried through a poly slot: #value/#resume/#join dispatch on the boxed Fiber when no user class defines the name (#1261). */ else if (!strcmp(name, "value") || !strcmp(name, "resume")) pm = "sp_poly_fiber_value"; else if (!strcmp(name, "join")) pm = "sp_poly_fiber_join"; if (pm) { int ncand = 0; for (int k = 0; k < c->nclasses; k++) if (comp_method_in_chain(c, k, name, NULL) >= 0) ncand++; if (ncand == 0) { buf_printf(b, "%s(", pm); emit_expr(c, recv, b); buf_puts(b, ")"); if (!strcmp(name, "[]") && argc == 1) { /* struct[:sym] or struct[int_literal]: return member value boxed to poly */ int mi = -1; const char *kty = nt_type(nt, argv[0]); if (kty && !strcmp(kty, "SymbolNode") && nt_str(nt, argv[0], "value")) { char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", nt_str(nt, argv[0], "value")); mi = comp_ivar_index(sc, ivn); } else if (kty && !strcmp(kty, "IntegerNode")) { long long v = (long long)nt_int(nt, argv[0], "value", 0); if (v < 0) v += (long long)sc->nivars; if (v >= 0 && v < sc->nivars) mi = (int)v; } if (mi >= 0) { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_%s *_t%d = %s; ", sc->name, t, rb.p ? rb.p : ""); free(rb.p); buf_printf(b, "_t%d->iv_%s; })", t, sc->ivars[mi] + 1); return; } /* general: generate chain of comparisons */ if (sc->nivars > 0) { int t = ++g_tmp, tk = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_%s *_t%d = %s; sp_RbVal _t%d = ", sc->name, t, rb.p ? rb.p : "", tk); free(rb.p); emit_boxed(c, argv[0], b); buf_puts(b, ";"); for (int i = 0; i < sc->nivars; i++) { buf_printf(b, " if(sp_rbval_eql_key(_t%d,sp_box_sym((sp_sym)%d))||sp_rbval_eql_key(_t%d,sp_box_int(%dLL))){", tk, comp_sym_intern(c, sc->ivars[i]+1), tk, (long long)i); char fld2[300]; snprintf(fld2, sizeof fld2, "_t%d->iv_%s", t, sc->ivars[i] + 1); emit_boxed_text(c, sc->ivar_types[i], fld2, b); buf_printf(b, ";} else"); } buf_puts(b, " sp_box_nil(); })"); return; } } } /* poly method dispatch: switch on the boxed object's cls_id and call the matching class's method (walking the chain for inherited methods), unboxing the pointer. */ if (recv >= 0 && rt == TY_POLY && argc == 0) { int is_lengthlike = !strcmp(name, "length") || !strcmp(name, "size") || !strcmp(name, "count"); int is_empty = !strcmp(name, "empty?"); int ncand = 0; for (int k = 0; k < c->nclasses; k++) if (comp_method_in_chain(c, k, name, NULL) >= 0 || comp_reader_in_chain(c, k, name, NULL)) ncand++; if (ncand > 0 || is_lengthlike) { TyKind ret = comp_ntype(c, id); int tv = ++g_tmp, tr = ++g_tmp; buf_printf(b, "({ sp_RbVal _t%d = ", tv); emit_expr(c, recv, b); buf_puts(b, "; "); emit_ctype(c, is_scalar_ret(ret) ? ret : TY_INT, b); buf_printf(b, " _t%d = %s; ", tr, is_scalar_ret(ret) ? default_value(ret) : "0"); /* When the dispatch result feeds a poly context, tr is sp_RbVal, so the length-like int branches must box their integer result. */ const char *bopen = (ret == TY_POLY) ? "sp_box_int(" : ""; const char *bclose = (ret == TY_POLY) ? ")" : ""; /* empty? answers a bool; box it (not an int) when the result feeds poly */ const char *ebopen = (ret == TY_POLY) ? "sp_box_bool(" : ""; const char *ebclose = (ret == TY_POLY) ? ")" : ""; /* string/symbol-tagged poly values answer length/size directly */ if (is_lengthlike) { buf_printf(b, "if (_t%d.tag == SP_TAG_SYM) _t%d = %s(mrb_int)strlen(sp_sym_to_s((sp_sym)_t%d.v.i))%s; else ", tv, tr, bopen, tv, bclose); buf_printf(b, "if (_t%d.tag == SP_TAG_STR) _t%d = %s(mrb_int)sp_str_length(_t%d.v.s)%s; else ", tv, tr, bopen, tv, bclose); } /* a string/symbol-tagged poly value answers empty? directly (#1438) */ if (is_empty) { buf_printf(b, "if (_t%d.tag == SP_TAG_STR) _t%d = %ssp_str_length(_t%d.v.s) == 0%s; else ", tv, tr, ebopen, tv, ebclose); buf_printf(b, "if (_t%d.tag == SP_TAG_SYM) _t%d = %sstrlen(sp_sym_to_s((sp_sym)_t%d.v.i)) == 0%s; else ", tv, tr, ebopen, tv, ebclose); } buf_printf(b, "switch (_t%d.cls_id) {", tv); for (int k = 0; k < c->nclasses; k++) { int defcls = -1; int mi = comp_method_in_chain(c, k, name, &defcls); if (mi >= 0 && c->scopes[mi].nrequired == 0) { /* Build the call; append default values for any optional params not provided by the (zero-arg) call site. */ Buf cb; memset(&cb, 0, sizeof cb); buf_printf(&cb, "sp_%s_%s((sp_%s *)_t%d.v.p", c->classes[defcls].name, mc(c->scopes[mi].name), c->classes[defcls].name, tv); if (c->scopes[mi].nparams > 0) { const char *saved_self = g_self; static char selfpbuf[64]; snprintf(selfpbuf, sizeof selfpbuf, "(sp_%s *)_t%d.v.p", c->classes[defcls].name, tv); g_self = selfpbuf; for (int a = 0; a < c->scopes[mi].nparams; a++) { buf_puts(&cb, ", "); emit_arg_or_default(c, &c->scopes[mi], a, -1, &cb); } g_self = saved_self; } buf_puts(&cb, ")"); const char *call = cb.p ? cb.p : ""; buf_printf(b, " case %d: ", k); if (method_is_void(&c->scopes[mi])) buf_puts(b, call); /* void: no usable value */ else { buf_printf(b, "_t%d = ", tr); if (ret == TY_POLY && c->scopes[mi].ret != TY_POLY) emit_boxed_text(c, c->scopes[mi].ret, call, b); else buf_puts(b, call); } buf_puts(b, "; break;"); free(cb.p); continue; /* object method call: sp_<DefClass>_<m>((sp_<DefClass>*)&recv, args) */ if (recv >= 0 && ty_is_object(rt)) { int cid = ty_object_class(rt); /* undef'd method: raise NoMethodError */ if (comp_is_undeffed_in_chain(c, cid, name)) { TyKind ret_ty = comp_ntype(c, id); buf_printf(b, "(sp_raise_cls(\"NoMethodError\",\"undefined method '%s' for an instance of %s\"),%s)", name, c->classes[cid].name, ret_ty == TY_RANGE ? "(sp_Range){0}" : default_value(ret_ty)); return; } /* attr reader -> field access (recv).iv_x */ if (comp_reader_in_chain(c, cid, name, NULL)) { const char *rn2 = comp_resolve_alias(c, cid, name); buf_puts(b, "("); emit_expr(c, recv, b); buf_printf(b, ")%siv_%s", comp_ty_value_obj(c, rt) ? "." : "->", rn2); return; } int mi = comp_method_in_chain(c, cid, name, NULL); if (mi >= 0) { /* a value-type receiver is passed by value; an ordinary object by pointer. For a value recv we hand emit_dispatch the value expression (lvalue or hoisted temp); the method takes `self` by value. */ if (comp_ty_value_obj(c, rt)) { char selfv[64]; const char *rty = nt_type(nt, recv); if (rty && (!strcmp(rty, "LocalVariableReadNode") || !strcmp(rty, "InstanceVariableReadNode") || !strcmp(rty, "SelfNode"))) { Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); snprintf(selfv, sizeof selfv, "%s", rb.p ? rb.p : ""); free(rb.p); } int rdcls = -1; if (comp_reader_in_chain(c, k, name, &rdcls)) { const char *rn3 = comp_resolve_alias(c, k, name); char fld[600]; snprintf(fld, sizeof fld, "((sp_%s *)_t%d.v.p)->iv_%s", c->classes[rdcls].name, tv, rn3); char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", rn3); int ivx = comp_ivar_index(&c->classes[rdcls], ivn); TyKind ivt = ivx >= 0 ? c->classes[rdcls].ivar_types[ivx] : TY_INT; buf_printf(b, " case %d: _t%d = ", k, tr); if (ret == TY_POLY && ivt != TY_POLY) emit_boxed_text(c, ivt, fld, b); else buf_puts(b, fld); buf_puts(b, "; break;"); else { int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); emit_ctype(c, rt, g_pre); buf_printf(g_pre, " _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); snprintf(selfv, sizeof selfv, "_t%d", t); } emit_dispatch(c, cid, name, selfv, nt_ref(nt, id, "arguments"), nt_ref(nt, id, "block"), b); return; } /* built-in array receivers reaching a length-like poly dispatch */ if (!strcmp(name, "length") || !strcmp(name, "size") || !strcmp(name, "count")) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: case SP_BUILTIN_SYM_ARRAY: _t%d = %ssp_IntArray_length((sp_IntArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = %ssp_StrArray_length((sp_StrArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = %ssp_FloatArray_length((sp_FloatArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = %ssp_PolyArray_length((sp_PolyArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: _t%d = %s((sp_PolyPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = %s((sp_SymPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = %s((sp_StrPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); /* receiver is a pointer; reuse it directly if it's a simple lvalue, else stash in a temp (the virtual-dispatch switch references it multiple times) */ char selfptr[64]; const char *rty = nt_type(nt, recv); if (rty && (!strcmp(rty, "LocalVariableReadNode") || !strcmp(rty, "InstanceVariableReadNode") || !strcmp(rty, "SelfNode"))) { Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); snprintf(selfptr, sizeof selfptr, "%s", rb.p ? rb.p : ""); free(rb.p); } /* built-in array / hash receivers reaching a poly empty? dispatch (#1438) */ if (is_empty) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: case SP_BUILTIN_SYM_ARRAY: _t%d = %ssp_IntArray_length((sp_IntArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = %ssp_StrArray_length((sp_StrArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = %ssp_FloatArray_length((sp_FloatArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = %ssp_PolyArray_length((sp_PolyArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: _t%d = %s((sp_PolyPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = %s((sp_SymPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = %s((sp_StrPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); else { int t = ++g_tmp; /* emit the receiver first so any setup it pushes into g_pre is fully flushed before we write this temp's declaration line */ Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); emit_ctype(c, rt, g_pre); buf_printf(g_pre, " _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); /* Root the hoisted receiver: a freshly constructed object (e.g. Scene.new.render(...)) must survive any GC the call triggers. */ emit_indent(g_pre, g_indent); buf_printf(g_pre, "SP_GC_ROOT(_t%d);\n", t); snprintf(selfptr, sizeof selfptr, "_t%d", t); } buf_printf(b, " } _t%d; })", tr); emit_dispatch(c, cid, name, selfptr, nt_ref(nt, id, "arguments"), nt_ref(nt, id, "block"), b); return; } } /* poly method dispatch with arguments: switch on the boxed object's cls_id and call the matching user method (or a builtin array `[]`), passing the arguments evaluated once into temps. */ if (recv >= 0 && rt == TY_POLY && argc > 0) { /* the builtin-array `[]` arm only applies to an integer index */ int is_index = !strcmp(name, "[]") && argc == 1 && comp_ntype(c, argv[0]) == TY_INT; int is_include = (!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "has_key?") || !strcmp(name, "key?")) && argc == 1; int ncand = 0; for (int k = 0; k < c->nclasses; k++) { int mi = comp_method_in_chain(c, k, name, NULL); /* Include if call supplies all required params (pad defaults / truncate extras) */ if (mi >= 0 && argc >= c->scopes[mi].nrequired) ncand++; /* Time instance methods: sp_Time is a value -- splice the receiver once. */ if (recv >= 0 && rt == TY_TIME) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if (!strcmp(name, "utc") || !strcmp(name, "gmtime") || !strcmp(name, "getutc")) buf_printf(b, "sp_time_utc(%s)", r); else if (!strcmp(name, "localtime") || !strcmp(name, "getlocal")) buf_printf(b, "sp_time_localtime(%s)", r); else if (!strcmp(name, "year")) buf_printf(b, "sp_time_year(%s)", r); else if (!strcmp(name, "mon") || !strcmp(name, "month")) buf_printf(b, "sp_time_mon(%s)", r); else if (!strcmp(name, "day") || !strcmp(name, "mday")) buf_printf(b, "sp_time_mday(%s)", r); else if (!strcmp(name, "hour")) buf_printf(b, "sp_time_hour(%s)", r); else if (!strcmp(name, "min")) buf_printf(b, "sp_time_min(%s)", r); else if (!strcmp(name, "sec")) buf_printf(b, "sp_time_sec(%s)", r); else if (!strcmp(name, "wday")) buf_printf(b, "sp_time_wday(%s)", r); else if (!strcmp(name, "yday")) buf_printf(b, "sp_time_yday(%s)", r); else if (!strcmp(name, "to_i") || !strcmp(name, "tv_sec")) buf_printf(b, "(%s).tv_sec", r); else if (!strcmp(name, "to_f")) buf_printf(b, "((mrb_float)(%s).tv_sec + (mrb_float)(%s).tv_nsec / 1e9)", r, r); else if (!strcmp(name, "subsec")) buf_printf(b, "((mrb_float)(%s).tv_nsec / 1e9)", r); else if (!strcmp(name, "tv_usec") || !strcmp(name, "usec")) buf_printf(b, "((mrb_int)(%s).tv_nsec / 1000)", r); else if (!strcmp(name, "tv_nsec") || !strcmp(name, "nsec")) buf_printf(b, "((mrb_int)(%s).tv_nsec)", r); else if (!strcmp(name, "utc?") || !strcmp(name, "gmt?")) buf_printf(b, "((%s).is_utc != 0)", r); else if (!strcmp(name, "dst?") || !strcmp(name, "isdst")) buf_printf(b, "(sp_time_isdst(%s) != 0)", r); else if (!strcmp(name, "utc_offset") || !strcmp(name, "gmt_offset") || !strcmp(name, "gmtoff")) buf_printf(b, "sp_time_utc_offset(%s)", r); else if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) buf_printf(b, "sp_time_inspect_v(%s)", r); else if (!strcmp(name, "iso8601")) buf_printf(b, "sp_time_iso8601(%s)", r); else if (!strcmp(name, "zone")) buf_printf(b, "sp_time_zone(%s)", r); else if (!strcmp(name, "class")) buf_puts(b, "SPL(\"Time\")"); else if (!strcmp(name, "strftime") && argc == 1) { buf_printf(b, "sp_time_strftime(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "+") || !strcmp(name, "-")) && argc == 1) { buf_printf(b, "sp_time_add(%s, %s(mrb_float)(", r, name[0] == '-' ? "-" : ""); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if ((!strcmp(name, "<") || !strcmp(name, ">") || !strcmp(name, "<=") || !strcmp(name, ">=") || !strcmp(name, "==") || !strcmp(name, "!=")) && argc == 1) { int tt = ++g_tmp, tu = ++g_tmp; buf_puts(b, "({ sp_Time _t"); buf_printf(b, "%d = %s; sp_Time _t%d = ", tt, r, tu); emit_expr(c, argv[0], b); buf_printf(b, "; sp_time_cmp(_t%d, _t%d) %s 0; })", tt, tu, name); } if (ncand > 0 || is_index || is_include) { TyKind ret = comp_ntype(c, id); int tv = ++g_tmp, tr = ++g_tmp; int *atmp = malloc(sizeof(int) * argc); buf_printf(b, "({ sp_RbVal _t%d = ", tv); emit_expr(c, recv, b); buf_puts(b, "; "); for (int a = 0; a < argc; a++) { atmp[a] = ++g_tmp; emit_ctype(c, infer_type(c, argv[a]), b); buf_printf(b, " _t%d = ", atmp[a]); emit_expr(c, argv[a], b); buf_puts(b, "; "); } emit_ctype(c, is_scalar_ret(ret) ? ret : TY_INT, b); buf_printf(b, " _t%d = %s; ", tr, is_scalar_ret(ret) ? default_value(ret) : "0"); /* include? on a TAG_STR receiver: check tag before entering cls_id switch */ if (is_include && infer_type(c, argv[0]) == TY_STRING) buf_printf(b, "if (_t%d.tag == SP_TAG_STR) { _t%d = sp_str_include(_t%d.v.s, _t%d); } else ", tv, tr, tv, atmp[0]); /* Integer#[N] bit-extraction: poly recv may hold a tagged int */ if (is_index) { if (ret == TY_POLY) buf_printf(b, "if (_t%d.tag == SP_TAG_INT) { _t%d = sp_box_int((_t%d.v.i >> _t%d) & 1); } else ", tv, tr, tv, atmp[0]); else buf_printf(b, "if (_t%d.tag == SP_TAG_INT) { _t%d = (_t%d.v.i >> _t%d) & 1; } else ", tv, tr, tv, atmp[0]); } buf_printf(b, "switch (_t%d.cls_id) {", tv); for (int k = 0; k < c->nclasses; k++) { int defcls = -1; int mi = comp_method_in_chain(c, k, name, &defcls); if (mi < 0 || argc < c->scopes[mi].nrequired) continue; TyKind mret = c->scopes[mi].ret; int mnp = c->scopes[mi].nparams; Buf cb; memset(&cb, 0, sizeof cb); buf_printf(&cb, "sp_%s_%s((sp_%s *)_t%d.v.p", c->classes[defcls].name, mc(c->scopes[mi].name), c->classes[defcls].name, tv); const char *saved_self = g_self; static char selfpbuf2[64]; snprintf(selfpbuf2, sizeof selfpbuf2, "(sp_%s *)_t%d.v.p", c->classes[defcls].name, tv); for (int a = 0; a < mnp; a++) { /* box the call-site arg if this candidate's parameter is poly; emit default for args beyond the call-site count (padding) */ TyKind pt = TY_UNKNOWN; LocalVar *pv = scope_local(&c->scopes[mi], c->scopes[mi].pnames[a]); if (pv) pt = pv->type; buf_puts(&cb, ", "); if (a < argc) { TyKind at = infer_type(c, argv[a]); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[a]); if (pt == TY_POLY && at != TY_POLY) emit_boxed_text(c, at, tn, &cb); else buf_puts(&cb, tn); }else { g_self = selfpbuf2; emit_arg_or_default(c, &c->scopes[mi], a, -1, &cb); g_self = saved_self; } } g_self = saved_self; buf_puts(&cb, ")"); buf_printf(b, " case %d: ", k); if (mret == TY_VOID || mret == TY_NIL || method_is_void(&c->scopes[mi])) buf_puts(b, cb.p); /* no usable value */ else { buf_printf(b, "_t%d = ", tr); if (ret == TY_POLY && mret != TY_POLY) emit_boxed_text(c, mret, cb.p, b); else buf_puts(b, cb.p); } buf_puts(b, "; break;"); free(cb.p); } if (is_index) { if (ret == TY_POLY) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_box_int(sp_IntArray_get((sp_IntArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = sp_box_str(sp_StrArray_get((sp_StrArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = sp_box_float(sp_FloatArray_get((sp_FloatArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = sp_PolyArray_get((sp_PolyArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_IntArray_get((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } } if (is_include) { TyKind at = infer_type(c, argv[0]); if (at == TY_INT) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_IntArray_include((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_RANGE: _t%d = sp_range_include((sp_Range *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else if (at == TY_STRING) { buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = sp_StrArray_include((sp_StrArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_INT_HASH: _t%d = sp_StrIntHash_has_key((sp_StrIntHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_STR_HASH: _t%d = sp_StrStrHash_has_key((sp_StrStrHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = sp_StrPolyHash_has_key((sp_StrPolyHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else if (at == TY_SYMBOL) { /* sym array is stored as IntArray (sp_sym == mrb_int) */ buf_printf(b, " case SP_BUILTIN_SYM_ARRAY: _t%d = sp_IntArray_include((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = sp_SymPolyHash_has_key((sp_SymPolyHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } /* PolyArray: box the arg for runtime comparison */ { int tbox = ++g_tmp; buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: { sp_RbVal _t%d = ", tbox); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[0]); emit_boxed_text(c, at, tn, b); buf_printf(b, "; _t%d = sp_PolyArray_include((sp_PolyArray *)_t%d.v.p, _t%d); break; }", tr, tv, tbox); } /* PolyPolyHash: keys are boxed sp_RbVal */ { int tbox = ++g_tmp; buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: { sp_RbVal _t%d = ", tbox); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[0]); emit_boxed_text(c, at, tn, b); buf_printf(b, "; _t%d = sp_PolyPolyHash_has_key((sp_PolyPolyHash *)_t%d.v.p, _t%d); break; }", tr, tv, tbox); } } /* the poly value may actually be a string-keyed hash: dispatch `[]` / `fetch` to the matching hash storage, boxing the value into the poly result. */ int is_aref = !strcmp(name, "[]") && argc == 1; int is_fetch = !strcmp(name, "fetch") && (argc == 1 || argc == 2); if ((is_aref || is_fetch) && infer_type(c, argv[0]) == TY_STRING) { TyKind trt = is_scalar_ret(ret) ? ret : TY_INT; /* the result temp's type */ static const struct { const char *cls, *hn; TyKind vt; } HV[] = { {"SP_BUILTIN_STR_STR_HASH", "StrStr", TY_STRING}, {"SP_BUILTIN_STR_INT_HASH", "StrInt", TY_INT}, {"SP_BUILTIN_STR_POLY_HASH", "StrPoly", TY_POLY}, }; for (unsigned hvi = 0; hvi < sizeof HV / sizeof HV[0]; hvi++) { /* only a variant whose value fits the result temp can be emitted */ if (ret != TY_POLY && HV[hvi].vt != trt) continue; char getx[200]; snprintf(getx, sizeof getx, "sp_%sHash_get((sp_%sHash *)_t%d.v.p, _t%d)", HV[hvi].hn, HV[hvi].hn, tv, atmp[0]); buf_printf(b, " case %s: _t%d = sp_%sHash_has_key((sp_%sHash *)_t%d.v.p, _t%d) ? ", HV[hvi].cls, tr, HV[hvi].hn, HV[hvi].hn, tv, atmp[0]); if (ret == TY_POLY) emit_boxed_text(c, HV[hvi].vt, getx, b); else buf_puts(b, getx); buf_puts(b, " : "); if (is_fetch && argc == 2) { char dn[32]; snprintf(dn, sizeof dn, "_t%d", atmp[1]); if (ret == TY_POLY) emit_boxed_text(c, infer_type(c, argv[1]), dn, b); else buf_puts(b, dn); } else if (is_fetch) { buf_puts(b, "(sp_raise_cls(\"KeyError\", \"key not found\"), "); buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, ")"); } else buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, "; break;"); } } /* a symbol-keyed hash (`{ name: ... }`) reaches here as SymPolyHash; add its `[]` / `fetch` arm so a Hash receiver indexed by a symbol is not dropped when a user class also defines an instance `[]` (#1437). */ if ((is_aref || is_fetch) && infer_type(c, argv[0]) == TY_SYMBOL) { TyKind trt = is_scalar_ret(ret) ? ret : TY_INT; char getx[200]; snprintf(getx, sizeof getx, "sp_SymPolyHash_get((sp_SymPolyHash *)_t%d.v.p, _t%d)", tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = sp_SymPolyHash_has_key((sp_SymPolyHash *)_t%d.v.p, _t%d) ? ", tr, tv, atmp[0]); if (ret == TY_POLY) buf_puts(b, getx); else if (trt == TY_STRING) buf_printf(b, "sp_poly_to_s(%s)", getx); else if (trt == TY_FLOAT) buf_printf(b, "sp_poly_to_f(%s)", getx); else buf_printf(b, "sp_poly_to_i(%s)", getx); buf_puts(b, " : "); if (is_fetch && argc == 2) { char dn[32]; snprintf(dn, sizeof dn, "_t%d", atmp[1]); if (ret == TY_POLY) emit_boxed_text(c, infer_type(c, argv[1]), dn, b); else buf_puts(b, dn); } else if (is_fetch) { buf_puts(b, "(sp_raise_cls(\"KeyError\", \"key not found\"), "); buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, ")"); } else buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, "; break;"); } buf_printf(b, " } _t%d; })", tr); free(atmp); return; else if (!strcmp(name, "<=>") && argc == 1) { int tt = ++g_tmp, tu = ++g_tmp; buf_puts(b, "({ sp_Time _t"); buf_printf(b, "%d = %s; sp_Time _t%d = ", tt, r, tu); emit_expr(c, argv[0], b); buf_printf(b, "; (mrb_int)sp_time_cmp(_t%d, _t%d); })", tt, tu); } else done = 0; free(rs.p); if (done) return; } /* string-range literal methods: the int-only sp_Range struct can't hold string bounds, so inline strcmp / char-iteration for a literal `("a".."z")` receiver. */ if (recv >= 0 && rt == TY_RANGE && nt_type(nt, unwrap_parens(c, recv)) && !strcmp(nt_type(nt, unwrap_parens(c, recv)), "RangeNode")) { int rnode = unwrap_parens(c, recv); int lo = nt_ref(nt, rnode, "left"), hi = nt_ref(nt, rnode, "right"); if (lo >= 0 && hi >= 0 && comp_ntype(c, lo) == TY_STRING && comp_ntype(c, hi) == TY_STRING) { int excl = (int)(nt_int(nt, rnode, "flags", 0) & 4) ? 1 : 0; if ((!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "cover?") || !strcmp(name, "===")) && argc == 1) { if (a0 != TY_STRING) { /* a non-string can't be in a string range: false (eval arg) */ buf_puts(b, "((void)("); emit_expr(c, argv[0], b); buf_puts(b, "), 0)"); } else { int ta = ++g_tmp; buf_printf(b, "({ const char *_t%d = ", ta); emit_expr(c, argv[0], b); buf_puts(b, "; (strcmp("); emit_expr(c, lo, b); buf_printf(b, ", _t%d) <= 0 && strcmp(_t%d, ", ta, ta); emit_expr(c, hi, b); buf_printf(b, ") %s 0); })", excl ? "<" : "<="); } return; } if (!strcmp(name, "to_a") && argc == 0) { /* succ-based string range (handles multi-char: "aa".."ac" etc.) */ buf_puts(b, "sp_StrArray_from_string_range("); emit_expr(c, lo, b); buf_puts(b, ", "); emit_expr(c, hi, b); buf_printf(b, ", %d)", excl); return; } /* StringScanner instance methods. String-returning methods may yield NULL (nil) on a miss; the NULL-aware string output operators render that. */ if (recv >= 0 && rt == TY_STRINGSCANNER) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if ((!strcmp(name, "scan") || !strcmp(name, "check") || !strcmp(name, "scan_until")) && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_StringScanner_%s(%s, sp_re_pat_%d)", name, r, re_lit_index(c, argv[0])); } else if (!strcmp(name, "matched")) buf_printf(b, "sp_StringScanner_matched(%s)", r); else if (!strcmp(name, "matched?")) buf_printf(b, "sp_StringScanner_matched_p(%s)", r); else if (!strcmp(name, "pre_match")) buf_printf(b, "sp_StringScanner_pre_match(%s)", r); else if (!strcmp(name, "post_match")) buf_printf(b, "sp_StringScanner_post_match(%s)", r); else if (!strcmp(name, "pos") || !strcmp(name, "charpos")) buf_printf(b, "sp_StringScanner_pos(%s)", r); else if (!strcmp(name, "pos=") && argc == 1) { buf_printf(b, "sp_StringScanner_pos_set(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rest")) buf_printf(b, "sp_StringScanner_rest(%s)", r); else if (!strcmp(name, "rest?")) buf_printf(b, "sp_StringScanner_rest_p(%s)", r); else if (!strcmp(name, "rest_size")) buf_printf(b, "sp_StringScanner_rest_size(%s)", r); else if (!strcmp(name, "string")) buf_printf(b, "sp_StringScanner_string(%s)", r); else if (!strcmp(name, "eos?")) buf_printf(b, "sp_StringScanner_eos_p(%s)", r); else if (!strcmp(name, "getch")) buf_printf(b, "sp_StringScanner_getch(%s)", r); else if (!strcmp(name, "peek") && argc == 1) { buf_printf(b, "sp_StringScanner_peek(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "sp_StringScanner_aref(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "reset")) buf_printf(b, "(sp_StringScanner_reset(%s), %s)", r, r); else if (!strcmp(name, "terminate")) buf_printf(b, "(sp_StringScanner_terminate(%s), %s)", r, r); else if (!strcmp(name, "unscan")) buf_printf(b, "(sp_StringScanner_unscan(%s), %s)", r, r); else done = 0; free(rs.p); if (done) return; } /* range value methods (evaluate the range once into a temp) */ if (recv >= 0 && rt == TY_RANGE) { int block = nt_ref(nt, id, "block"); if (!strcmp(name, "step") && argc == 1) { int t = ++g_tmp, ar = ++g_tmp, ii = ++g_tmp, st = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); Buf sb; memset(&sb, 0, sizeof sb); emit_expr(c, argv[0], &sb); buf_printf(b, "({ sp_Range _t%d = %s; mrb_int _t%d = %s; sp_IntArray *_t%d = sp_IntArray_new();" " for (mrb_int _t%d = _t%d.first; _t%d <= _t%d.last - _t%d.excl; _t%d += _t%d)" " sp_IntArray_push(_t%d, _t%d); _t%d; })", t, rb.p ? rb.p : "", st, sb.p ? sb.p : "", ar, ii, t, ii, t, t, ii, st, ar, ii, ar); free(rb.p); free(sb.p); return; /* MatchData instance methods (sp_MatchData *, nullable on no-match). */ if (recv >= 0 && rt == TY_MATCHDATA) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "sp_MatchData_aref(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pre_match")) buf_printf(b, "sp_MatchData_pre_match(%s)", r); else if (!strcmp(name, "post_match")) buf_printf(b, "sp_MatchData_post_match(%s)", r); else if (!strcmp(name, "to_s")) buf_printf(b, "sp_MatchData_to_s(%s)", r); else if ((!strcmp(name, "length") || !strcmp(name, "size")) && argc == 0) buf_printf(b, "sp_MatchData_length(%s)", r); else if (!strcmp(name, "begin") && argc == 1) { buf_printf(b, "sp_MatchData_begin(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "end") && argc == 1) { buf_printf(b, "sp_MatchData_end(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "offset") && argc == 1) { buf_printf(b, "sp_MatchData_offset(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } if (!strcmp(name, "each") && block < 0) { /* enumerator: materialize to_a */ int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_Range _t%d = %s; sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl); })", t, rb.p ? rb.p : "", t, t, t); free(rb.p); return; else if (!strcmp(name, "captures")) buf_printf(b, "sp_MatchData_captures(%s)", r); else if (!strcmp(name, "to_a")) buf_printf(b, "sp_MatchData_to_a(%s)", r); else if (!strcmp(name, "nil?")) buf_printf(b, "(%s == 0)", r); else unsupported(c, id, "MatchData method"); free(rs.p); return; } /* StringIO instance methods (a non-GC heap buffer behind sp_StringIO *). */ if (recv >= 0 && rt == TY_STRINGIO) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; int done = 1; if (!strcmp(name, "string")) buf_printf(b, "sp_StringIO_string(%s)", r); else if (!strcmp(name, "pos") || !strcmp(name, "tell")) buf_printf(b, "sp_StringIO_pos(%s)", r); else if (!strcmp(name, "size") || !strcmp(name, "length")) buf_printf(b, "sp_StringIO_size(%s)", r); else if (!strcmp(name, "lineno")) buf_printf(b, "(%s)->lineno", r); else if (!strcmp(name, "puts") && argc == 0) buf_printf(b, "sp_StringIO_puts_empty(%s)", r); else if (!strcmp(name, "puts") && argc == 1) { buf_printf(b, "sp_StringIO_puts(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "print") && argc == 1) { buf_printf(b, "sp_StringIO_print(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "write") || !strcmp(name, "<<")) && argc == 1) { buf_printf(b, "sp_StringIO_write(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "putc") && argc == 1) { if (comp_ntype(c, argv[0]) == TY_STRING) { buf_printf(b, "sp_StringIO_putc(%s, (mrb_int)(unsigned char)(", r); emit_expr(c, argv[0], b); buf_puts(b, ")[0])"); } else { buf_printf(b, "sp_StringIO_putc(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } } static const char *const rmeths[] = { "to_a", "include?", "member?", "cover?", "===", "sum", "min", "max", "first", "last", "size", "count", "begin", "end", "exclude_end?", "eql?", "minmax", "overlap?", NULL }; int known = 0; for (int i = 0; rmeths[i]; i++) if (!strcmp(name, rmeths[i])) known = 1; if (known) { /* size/count on a string-literal range: no integer size -> nil, skip creating sp_Range */ if ((!strcmp(name, "size") || !strcmp(name, "count")) && argc == 0) { int rn = unwrap_parens(c, recv); if (rn >= 0 && nt_type(nt, rn) && !strcmp(nt_type(nt, rn), "RangeNode")) { int lo = nt_ref(nt, rn, "left"); if (lo >= 0 && comp_ntype(c, lo) == TY_STRING) { buf_puts(b, "SP_INT_NIL"); return; } } } int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); buf_printf(g_pre, "sp_Range _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); if (!strcmp(name, "to_a")) buf_printf(b, "sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl)", t, t, t); else if (!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "cover?") || !strcmp(name, "===")) { /* cover?(range) checks that both endpoints of the arg fit inside self */ if (!strcmp(name, "cover?") && argc == 1 && comp_ntype(c, argv[0]) == TY_RANGE) { int t2 = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", t2); emit_expr(c, argv[0], b); buf_printf(b, "; _t%d.first >= _t%d.first && (_t%d.last - _t%d.excl) <= (_t%d.last - _t%d.excl); })", t2, t, t2, t2, t, t); } else { /* sp_range_include takes mrb_int; a float arg (`(1..).include?(2.4)`) needs an explicit cast, else clang -Werror flags the implicit float-literal->int conversion (gcc truncates silently). */ int arg_is_float = comp_ntype(c, argv[0]) == TY_FLOAT; buf_printf(b, "sp_range_include(&_t%d, ", t); if (arg_is_float) buf_puts(b, "(mrb_int)("); emit_expr(c, argv[0], b); if (arg_is_float) buf_puts(b, ")"); buf_puts(b, ")"); } } else if (!strcmp(name, "first") || !strcmp(name, "min") || !strcmp(name, "begin")) { if (argc == 1) { /* first(n): collect up to n elements starting at first */ int tf = ++g_tmp, tn = ++g_tmp, ti = ++g_tmp; buf_printf(b, "({ sp_IntArray *_t%d = sp_IntArray_new(); mrb_int _t%d = ", tf, tn); emit_expr(c, argv[0], b); buf_printf(b, "; for (mrb_int _t%d = _t%d.first; _t%d <= _t%d.last - _t%d.excl && _t%d - _t%d.first < _t%d; _t%d++)" " sp_IntArray_push(_t%d, _t%d); _t%d; })", ti, t, ti, t, t, ti, t, tn, ti, tf, ti, tf); } else buf_printf(b, "(_t%d.first)", t); } else if (!strcmp(name, "max")) /* max element: end minus the exclusive bound */ buf_printf(b, "(_t%d.last - _t%d.excl)", t, t); else if (!strcmp(name, "last") || !strcmp(name, "end")) { if (argc == 1 && !strcmp(name, "last")) { /* last(n): collect up to n elements ending at last */ int tf = ++g_tmp, tn = ++g_tmp, ts = ++g_tmp, te = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", tn); emit_expr(c, argv[0], b); buf_printf(b, "; mrb_int _t%d = _t%d.last - _t%d.excl;", te, t, t); buf_printf(b, " mrb_int _t%d = _t%d - _t%d + 1; if (_t%d < _t%d.first) _t%d = _t%d.first;", ts, te, tn, ts, t, ts, t); buf_printf(b, " sp_IntArray *_t%d = sp_IntArray_new(); for (mrb_int _i%d = _t%d; _i%d <= _t%d; _i%d++)" " sp_IntArray_push(_t%d, _i%d); _t%d; })", tf, tf, ts, tf, te, tf, tf, tf, tf); } else buf_printf(b, "(_t%d.last)", t); } else if (!strcmp(name, "size") || !strcmp(name, "count")) buf_printf(b, "(_t%d.last - _t%d.excl - _t%d.first + 1)", t, t, t); else if (!strcmp(name, "sum")) buf_printf(b, "sp_IntArray_sum(sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl), 0)", t, t, t); else if (!strcmp(name, "exclude_end?")) buf_printf(b, "(_t%d.excl != 0)", t); else if (!strcmp(name, "eql?")) { buf_printf(b, "sp_range_eq(_t%d, ", t); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "overlap?")) { int t2 = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", t2); emit_expr(c, argv[0], b); buf_printf(b, "; (_t%d.first <= _t%d.last - _t%d.excl && _t%d.first <= _t%d.last - _t%d.excl); })", t, t2, t2, t2, t, t, t); } else if (!strcmp(name, "minmax")) { int ma = ++g_tmp; buf_printf(b, "({ sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, _t%d.first);" " sp_IntArray_push(_t%d, _t%d.last - _t%d.excl); _t%d; })", ma, ma, t, ma, t, t, ma); else if (!strcmp(name, "fsync") || !strcmp(name, "fileno") || !strcmp(name, "pid")) buf_printf(b, "((void)(%s), 0)", r); else if (!strcmp(name, "read") && argc == 0) buf_printf(b, "sp_StringIO_read(%s)", r); else if (!strcmp(name, "read") && argc == 1) { buf_printf(b, "sp_StringIO_read_n(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "gets")) buf_printf(b, "sp_box_nullable_str(sp_StringIO_gets(%s))", r); else if (!strcmp(name, "getc")) buf_printf(b, "sp_box_nullable_str(sp_StringIO_getc(%s))", r); else if (!strcmp(name, "getbyte")) buf_printf(b, "sp_StringIO_getbyte(%s)", r); else if (!strcmp(name, "rewind")) buf_printf(b, "sp_StringIO_rewind(%s)", r); else if (!strcmp(name, "seek") && argc >= 1) { buf_printf(b, "sp_StringIO_seek(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "truncate") && argc == 1) { buf_printf(b, "sp_StringIO_truncate(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "eof?") || !strcmp(name, "eof")) buf_printf(b, "sp_StringIO_eof_p(%s)", r); else if (!strcmp(name, "close")) buf_printf(b, "sp_StringIO_close(%s)", r); else if (!strcmp(name, "closed?")) buf_printf(b, "sp_StringIO_closed_p(%s)", r); else if (!strcmp(name, "flush")) buf_printf(b, "sp_StringIO_flush(%s)", r); else if (!strcmp(name, "sync")) buf_printf(b, "sp_StringIO_sync(%s)", r); else if (!strcmp(name, "isatty") || !strcmp(name, "tty?")) buf_printf(b, "sp_StringIO_isatty(%s)", r); else done = 0; free(rs.p); if (done) return; } /* Array-reduction methods on a boxed array element of a poly array (e.g. `runs.map { |r| r.sum }` over chunk_while runs). The runtime helper switches on the element's cls_id. Skipped when a user class defines the same method (it falls through to the general poly dispatch below). */ if (recv >= 0 && rt == TY_POLY && argc == 0 && nt_ref(nt, id, "block") < 0) { const char *pm = NULL; if (!strcmp(name, "sum")) pm = "sp_poly_sum"; else if (!strcmp(name, "min")) pm = "sp_poly_min"; else if (!strcmp(name, "max")) pm = "sp_poly_max"; else if (!strcmp(name, "first")) pm = "sp_poly_first"; else if (!strcmp(name, "last")) pm = "sp_poly_last"; /* a Thread (Fiber-modelled) carried through a poly slot: #value/#resume/#join dispatch on the boxed Fiber when no user class defines the name (#1261). */ else if (!strcmp(name, "value") || !strcmp(name, "resume")) pm = "sp_poly_fiber_value"; else if (!strcmp(name, "join")) pm = "sp_poly_fiber_join"; if (pm) { int ncand = 0; for (int k = 0; k < c->nclasses; k++) if (comp_method_in_chain(c, k, name, NULL) >= 0) ncand++; if (ncand == 0) { buf_printf(b, "%s(", pm); emit_expr(c, recv, b); buf_puts(b, ")"); return; } return; } } /* hash value methods */ /* {}.default (empty hash literal with unknown type) always returns nil */ if (recv >= 0 && !strcmp(name, "default") && argc == 0 && !ty_is_hash(rt)) { buf_puts(b, "sp_box_nil()"); return; } if (emit_hash_call(c, id, b)) return; /* `arr[i] = v` in expression position: do the store, evaluate to the rhs (Ruby []= returns the assigned value). The statement form is emitted elsewhere; this covers rvalue chains like `b = arr[i] = v`. */ /* a[i, n] = src — slice assignment */ if (recv >= 0 && ty_is_array(rt) && !strcmp(name, "[]=") && argc == 3) { const char *k = (rt == TY_POLY_ARRAY) ? "Poly" : array_kind(rt); TyKind rhs_ty = comp_ntype(c, argv[2]); if (k && ty_is_array(rhs_ty)) { /* src is an array: copy elements from src into arr starting at i */ int ta = ++g_tmp, ti = ++g_tmp, ts = ++g_tmp, tj = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); buf_printf(b, "sp_%sArray *_t%d = ", k, ts); emit_expr(c, argv[2], b); buf_puts(b, "; "); buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_%sArray_length(_t%d); _t%d++)", tj, tj, k, ts, tj); buf_printf(b, " sp_%sArray_set(_t%d, _t%d + _t%d, sp_%sArray_get(_t%d, _t%d));", k, ta, ti, tj, k, ts, tj); buf_printf(b, " _t%d; })", ts); return; } if (k && rhs_ty == TY_POLY && rt != TY_POLY_ARRAY) { /* poly RHS wrapping a same-kind array (e.g. PolyArray element is IntArray): unbox via v.p cast and copy elements */ int ta3 = ++g_tmp, ti3 = ++g_tmp, ts3 = ++g_tmp, tj3 = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta3); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti3); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); buf_printf(b, "sp_RbVal _tv%d = ", ts3); emit_expr(c, argv[2], b); buf_puts(b, "; "); buf_printf(b, "sp_%sArray *_t%d = (sp_%sArray *)_tv%d.v.p; ", k, ts3, k, ts3); buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_%sArray_length(_t%d); _t%d++)", tj3, tj3, k, ts3, tj3); buf_printf(b, " sp_%sArray_set(_t%d, _t%d + _t%d, sp_%sArray_get(_t%d, _t%d));", k, ta3, ti3, tj3, k, ts3, tj3); buf_printf(b, " _tv%d; })", ts3); return; } if (k && rhs_ty == TY_POLY && rt == TY_POLY_ARRAY) { /* poly_array recv + poly src (array at runtime): copy src elements to recv[start..] */ int ta4 = ++g_tmp, tst4 = ++g_tmp, tsrc4 = ++g_tmp, tlen4 = ++g_tmp, tj4 = ++g_tmp; buf_printf(b, "({ sp_PolyArray *_t%d = ", ta4); emit_expr(c, recv, b); buf_puts(b, ";"); buf_printf(b, " mrb_int _t%d = ", tst4); emit_int_expr(c, argv[0], b); buf_puts(b, ";"); buf_printf(b, " sp_RbVal _t%d = ", tsrc4); emit_expr(c, argv[2], b); buf_puts(b, ";"); buf_printf(b, " mrb_int _t%d = sp_poly_arr_len(_t%d);", tlen4, tsrc4); buf_printf(b, " for (mrb_int _t%d = 0; _t%d < _t%d; _t%d++)", tj4, tj4, tlen4, tj4); buf_printf(b, " sp_PolyArray_set(_t%d, _t%d + _t%d, sp_poly_arr_get(_t%d, _t%d));", ta4, tst4, tj4, tsrc4, tj4); buf_printf(b, " _t%d; })", tsrc4); return; } if (k && !ty_is_array(rhs_ty)) { /* scalar RHS: set element at start index and return the scalar value */ int ta2 = ++g_tmp, ti2 = ++g_tmp, tv2 = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta2); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti2); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); if (rt == TY_POLY_ARRAY) { buf_printf(b, "sp_RbVal _t%d = ", tv2); emit_boxed(c, argv[2], b); /* poly method dispatch: switch on the boxed object's cls_id and call the matching class's method (walking the chain for inherited methods), unboxing the pointer. */ if (recv >= 0 && rt == TY_POLY && argc == 0) { int is_lengthlike = !strcmp(name, "length") || !strcmp(name, "size") || !strcmp(name, "count"); int is_empty = !strcmp(name, "empty?"); int ncand = 0; for (int k = 0; k < c->nclasses; k++) if (comp_method_in_chain(c, k, name, NULL) >= 0 || comp_reader_in_chain(c, k, name, NULL)) ncand++; if (ncand > 0 || is_lengthlike) { TyKind ret = comp_ntype(c, id); int tv = ++g_tmp, tr = ++g_tmp; buf_printf(b, "({ sp_RbVal _t%d = ", tv); emit_expr(c, recv, b); buf_puts(b, "; "); emit_ctype(c, is_scalar_ret(ret) ? ret : TY_INT, b); buf_printf(b, " _t%d = %s; ", tr, is_scalar_ret(ret) ? default_value(ret) : "0"); /* When the dispatch result feeds a poly context, tr is sp_RbVal, so the length-like int branches must box their integer result. */ const char *bopen = (ret == TY_POLY) ? "sp_box_int(" : ""; const char *bclose = (ret == TY_POLY) ? ")" : ""; /* empty? answers a bool; box it (not an int) when the result feeds poly */ const char *ebopen = (ret == TY_POLY) ? "sp_box_bool(" : ""; const char *ebclose = (ret == TY_POLY) ? ")" : ""; /* string/symbol-tagged poly values answer length/size directly */ if (is_lengthlike) { buf_printf(b, "if (_t%d.tag == SP_TAG_SYM) _t%d = %s(mrb_int)strlen(sp_sym_to_s((sp_sym)_t%d.v.i))%s; else ", tv, tr, bopen, tv, bclose); buf_printf(b, "if (_t%d.tag == SP_TAG_STR) _t%d = %s(mrb_int)sp_str_length(_t%d.v.s)%s; else ", tv, tr, bopen, tv, bclose); } /* a string/symbol-tagged poly value answers empty? directly (#1438) */ if (is_empty) { buf_printf(b, "if (_t%d.tag == SP_TAG_STR) _t%d = %ssp_str_length(_t%d.v.s) == 0%s; else ", tv, tr, ebopen, tv, ebclose); buf_printf(b, "if (_t%d.tag == SP_TAG_SYM) _t%d = %sstrlen(sp_sym_to_s((sp_sym)_t%d.v.i)) == 0%s; else ", tv, tr, ebopen, tv, ebclose); } else { TyKind et2 = ty_array_elem(rt); emit_ctype(c, et2, b); buf_printf(b, " _t%d = ", tv2); if (rhs_ty == TY_POLY && et2 == TY_INT) { buf_puts(b, "sp_poly_to_i("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else if (rhs_ty == TY_POLY && et2 == TY_STRING) { buf_puts(b, "sp_poly_to_s("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else if (rhs_ty == TY_POLY && et2 == TY_FLOAT) { buf_puts(b, "sp_poly_to_f("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else emit_expr(c, argv[2], b); buf_printf(b, "switch (_t%d.cls_id) {", tv); for (int k = 0; k < c->nclasses; k++) { int defcls = -1; int mi = comp_method_in_chain(c, k, name, &defcls); if (mi >= 0 && c->scopes[mi].nrequired == 0) { /* Build the call; append default values for any optional params not provided by the (zero-arg) call site. */ Buf cb; memset(&cb, 0, sizeof cb); buf_printf(&cb, "sp_%s_%s((sp_%s *)_t%d.v.p", c->classes[defcls].name, mc(c->scopes[mi].name), c->classes[defcls].name, tv); if (c->scopes[mi].nparams > 0) { const char *saved_self = g_self; static char selfpbuf[64]; snprintf(selfpbuf, sizeof selfpbuf, "(sp_%s *)_t%d.v.p", c->classes[defcls].name, tv); g_self = selfpbuf; for (int a = 0; a < c->scopes[mi].nparams; a++) { buf_puts(&cb, ", "); emit_arg_or_default(c, &c->scopes[mi], a, -1, &cb); } g_self = saved_self; } buf_puts(&cb, ")"); const char *call = cb.p ? cb.p : ""; buf_printf(b, " case %d: ", k); if (method_is_void(&c->scopes[mi])) buf_puts(b, call); /* void: no usable value */ else { buf_printf(b, "_t%d = ", tr); if (ret == TY_POLY && c->scopes[mi].ret != TY_POLY) emit_boxed_text(c, c->scopes[mi].ret, call, b); else buf_puts(b, call); } buf_puts(b, "; break;"); free(cb.p); continue; } int rdcls = -1; if (comp_reader_in_chain(c, k, name, &rdcls)) { const char *rn3 = comp_resolve_alias(c, k, name); char fld[600]; snprintf(fld, sizeof fld, "((sp_%s *)_t%d.v.p)->iv_%s", c->classes[rdcls].name, tv, rn3); char ivn[256]; snprintf(ivn, sizeof ivn, "@%s", rn3); int ivx = comp_ivar_index(&c->classes[rdcls], ivn); TyKind ivt = ivx >= 0 ? c->classes[rdcls].ivar_types[ivx] : TY_INT; buf_printf(b, " case %d: _t%d = ", k, tr); if (ret == TY_POLY && ivt != TY_POLY) emit_boxed_text(c, ivt, fld, b); else buf_puts(b, fld); buf_puts(b, "; break;"); } } buf_printf(b, "; sp_%sArray_set(_t%d, _t%d, _t%d); _t%d; })", k, ta2, ti2, tv2, tv2); return; } } if (recv >= 0 && ty_is_array(rt) && !strcmp(name, "[]=") && argc == 2) { const char *k = (rt == TY_POLY_ARRAY) ? "Poly" : array_kind(rt); if (k) { int t = ++g_tmp, ti = ++g_tmp, tv = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, t); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); if (rt == TY_POLY_ARRAY) { buf_printf(b, "sp_RbVal _t%d = ", tv); emit_boxed(c, argv[1], b); /* built-in array receivers reaching a length-like poly dispatch */ if (!strcmp(name, "length") || !strcmp(name, "size") || !strcmp(name, "count")) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: case SP_BUILTIN_SYM_ARRAY: _t%d = %ssp_IntArray_length((sp_IntArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = %ssp_StrArray_length((sp_StrArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = %ssp_FloatArray_length((sp_FloatArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = %ssp_PolyArray_length((sp_PolyArray *)_t%d.v.p)%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: _t%d = %s((sp_PolyPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = %s((sp_SymPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = %s((sp_StrPolyHash *)_t%d.v.p)->len%s; break;", tr, bopen, tv, bclose); } else { TyKind et = ty_array_elem(rt); TyKind vt = comp_ntype(c, argv[1]); emit_ctype(c, et, b); buf_printf(b, " _t%d = ", tv); if (vt == TY_POLY && et == TY_INT) { buf_puts(b, "sp_poly_to_i("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (vt == TY_POLY && et == TY_STRING) { buf_puts(b, "sp_poly_to_s("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (vt == TY_POLY && et == TY_FLOAT) { buf_puts(b, "sp_poly_to_f("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else emit_expr(c, argv[1], b); /* built-in array / hash receivers reaching a poly empty? dispatch (#1438) */ if (is_empty) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: case SP_BUILTIN_SYM_ARRAY: _t%d = %ssp_IntArray_length((sp_IntArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = %ssp_StrArray_length((sp_StrArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = %ssp_FloatArray_length((sp_FloatArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = %ssp_PolyArray_length((sp_PolyArray *)_t%d.v.p) == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: _t%d = %s((sp_PolyPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = %s((sp_SymPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = %s((sp_StrPolyHash *)_t%d.v.p)->len == 0%s; break;", tr, ebopen, tv, ebclose); } buf_printf(b, "; sp_%sArray_set(_t%d, _t%d, _t%d); _t%d; })", k, t, ti, tv, tv); buf_printf(b, " } _t%d; })", tr); return; } } /* array value methods */ /* empty array literal [] has TY_UNKNOWN; sum returns init or 0 */ if (recv >= 0 && rt == TY_UNKNOWN && !strcmp(name, "sum") && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ArrayNode")) { int en = 0; nt_arr(nt, recv, "elements", &en); if (en == 0) { TyKind call_t = comp_ntype(c, id); if (argc == 1) { if (call_t == TY_POLY) emit_boxed(c, argv[0], b); else emit_expr(c, argv[0], b); /* poly method dispatch with arguments: switch on the boxed object's cls_id and call the matching user method (or a builtin array `[]`), passing the arguments evaluated once into temps. */ if (recv >= 0 && rt == TY_POLY && argc > 0) { /* the builtin-array `[]` arm only applies to an integer index */ int is_index = !strcmp(name, "[]") && argc == 1 && comp_ntype(c, argv[0]) == TY_INT; int is_include = (!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "has_key?") || !strcmp(name, "key?")) && argc == 1; int ncand = 0; for (int k = 0; k < c->nclasses; k++) { int mi = comp_method_in_chain(c, k, name, NULL); /* Include if call supplies all required params (pad defaults / truncate extras) */ if (mi >= 0 && argc >= c->scopes[mi].nrequired) ncand++; } if (ncand > 0 || is_index || is_include) { TyKind ret = comp_ntype(c, id); int tv = ++g_tmp, tr = ++g_tmp; int *atmp = malloc(sizeof(int) * argc); buf_printf(b, "({ sp_RbVal _t%d = ", tv); emit_expr(c, recv, b); buf_puts(b, "; "); for (int a = 0; a < argc; a++) { atmp[a] = ++g_tmp; emit_ctype(c, infer_type(c, argv[a]), b); buf_printf(b, " _t%d = ", atmp[a]); emit_expr(c, argv[a], b); buf_puts(b, "; "); } else { if (call_t == TY_POLY) buf_puts(b, "sp_box_int(0)"); else buf_puts(b, "0"); } return; } } /* take_while/drop_while/each_index/set-ops on empty array literal [] (TY_UNKNOWN receiver) */ if (recv >= 0 && rt == TY_UNKNOWN && (!strcmp(name, "take_while") || !strcmp(name, "drop_while") || !strcmp(name, "each_index") || !strcmp(name, "difference") || !strcmp(name, "-") || !strcmp(name, "&") || !strcmp(name, "|") || !strcmp(name, "intersection") || !strcmp(name, "union") || !strcmp(name, "+") || !strcmp(name, "zip") || !strcmp(name, "flatten") || !strcmp(name, "compact") || !strcmp(name, "uniq") || !strcmp(name, "sort") || !strcmp(name, "reverse") || !strcmp(name, "shuffle")) && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ArrayNode")) { int en = 0; nt_arr(nt, recv, "elements", &en); if (en == 0) { if (!strcmp(name, "each_index")) { /* each_index on [] is a no-op; evaluate receiver for side-effects */ emit_expr(c, recv, b); emit_ctype(c, is_scalar_ret(ret) ? ret : TY_INT, b); buf_printf(b, " _t%d = %s; ", tr, is_scalar_ret(ret) ? default_value(ret) : "0"); /* include? on a TAG_STR receiver: check tag before entering cls_id switch */ if (is_include && infer_type(c, argv[0]) == TY_STRING) buf_printf(b, "if (_t%d.tag == SP_TAG_STR) { _t%d = sp_str_include(_t%d.v.s, _t%d); } else ", tv, tr, tv, atmp[0]); /* Integer#[N] bit-extraction: poly recv may hold a tagged int */ if (is_index) { if (ret == TY_POLY) buf_printf(b, "if (_t%d.tag == SP_TAG_INT) { _t%d = sp_box_int((_t%d.v.i >> _t%d) & 1); } else ", tv, tr, tv, atmp[0]); else buf_printf(b, "if (_t%d.tag == SP_TAG_INT) { _t%d = (_t%d.v.i >> _t%d) & 1; } else ", tv, tr, tv, atmp[0]); } else if (!strcmp(name, "take_while") || !strcmp(name, "drop_while")) { buf_puts(b, "sp_PolyArray_new()"); buf_printf(b, "switch (_t%d.cls_id) {", tv); for (int k = 0; k < c->nclasses; k++) { int defcls = -1; int mi = comp_method_in_chain(c, k, name, &defcls); if (mi < 0 || argc < c->scopes[mi].nrequired) continue; TyKind mret = c->scopes[mi].ret; int mnp = c->scopes[mi].nparams; Buf cb; memset(&cb, 0, sizeof cb); buf_printf(&cb, "sp_%s_%s((sp_%s *)_t%d.v.p", c->classes[defcls].name, mc(c->scopes[mi].name), c->classes[defcls].name, tv); const char *saved_self = g_self; static char selfpbuf2[64]; snprintf(selfpbuf2, sizeof selfpbuf2, "(sp_%s *)_t%d.v.p", c->classes[defcls].name, tv); for (int a = 0; a < mnp; a++) { /* box the call-site arg if this candidate's parameter is poly; emit default for args beyond the call-site count (padding) */ TyKind pt = TY_UNKNOWN; LocalVar *pv = scope_local(&c->scopes[mi], c->scopes[mi].pnames[a]); if (pv) pt = pv->type; buf_puts(&cb, ", "); if (a < argc) { TyKind at = infer_type(c, argv[a]); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[a]); if (pt == TY_POLY && at != TY_POLY) emit_boxed_text(c, at, tn, &cb); else buf_puts(&cb, tn); }else { g_self = selfpbuf2; emit_arg_or_default(c, &c->scopes[mi], a, -1, &cb); g_self = saved_self; } } g_self = saved_self; buf_puts(&cb, ")"); buf_printf(b, " case %d: ", k); if (mret == TY_VOID || mret == TY_NIL || method_is_void(&c->scopes[mi])) buf_puts(b, cb.p); /* no usable value */ else { buf_printf(b, "_t%d = ", tr); if (ret == TY_POLY && mret != TY_POLY) emit_boxed_text(c, mret, cb.p, b); else buf_puts(b, cb.p); } buf_puts(b, "; break;"); free(cb.p); } else { /* set/transform ops on [] receiver: call the runtime with NULL first arg */ TyKind akt = argc > 0 ? comp_ntype(c, argv[0]) : TY_UNKNOWN; const char *ek = ty_is_array(akt) ? ((akt == TY_POLY_ARRAY) ? "Poly" : array_kind(akt)) : NULL; if (!ek) ek = "Poly"; if (argc > 0 && akt != TY_UNKNOWN && (!strcmp(name, "union") || !strcmp(name, "|") || !strcmp(name, "difference") || !strcmp(name, "-") || !strcmp(name, "intersection") || !strcmp(name, "&") || !strcmp(name, "+") || !strcmp(name, "zip"))) { /* call the real function with NULL receiver (handles empty-self case) */ const char *fn = (!strcmp(name, "&") || !strcmp(name, "intersection")) ? "intersect" : (!strcmp(name, "|") || !strcmp(name, "union")) ? "union" : (!strcmp(name, "+")) ? "concat" : "difference"; buf_printf(b, "sp_%sArray_%s(NULL, ", ek, fn); emit_expr(c, argv[0], b); buf_puts(b, ")"); if (is_index) { if (ret == TY_POLY) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_box_int(sp_IntArray_get((sp_IntArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = sp_box_str(sp_StrArray_get((sp_StrArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_FLT_ARRAY: _t%d = sp_box_float(sp_FloatArray_get((sp_FloatArray *)_t%d.v.p, _t%d)); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: _t%d = sp_PolyArray_get((sp_PolyArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else { buf_printf(b, "sp_%sArray_new()", ek); buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_IntArray_get((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } } return; } } if (emit_array_call(c, id, b)) return; /* symbol receiver methods */ if (recv >= 0 && rt == TY_SYMBOL) { if (!strcmp(name, "to_s") || !strcmp(name, "id2name") || !strcmp(name, "name")) { buf_puts(b, "sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if (!strcmp(name, "inspect")) { buf_puts(b, "sp_str_concat(SPL(\":\"), sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, "))"); return; } if (!strcmp(name, "to_sym") || !strcmp(name, "itself")) { emit_expr(c, recv, b); return; } /* case-folding methods return a (re-interned) symbol */ if (!strcmp(name, "upcase") || !strcmp(name, "downcase") || !strcmp(name, "capitalize") || !strcmp(name, "swapcase")) { buf_printf(b, "sp_sym_intern(sp_str_%s(sp_sym_to_s(", name); emit_expr(c, recv, b); buf_puts(b, ")))"); return; } if (!strcmp(name, "length") || !strcmp(name, "size")) { buf_puts(b, "((mrb_int)strlen(sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")))"); return; } if (!strcmp(name, "empty?")) { buf_puts(b, "(strlen(sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")) == 0)"); return; } if (!strcmp(name, "==") || !strcmp(name, "!=")) { buf_puts(b, name[0] == '=' ? "(" : "(!("); emit_expr(c, recv, b); buf_puts(b, " == "); emit_expr(c, argv[0], b); buf_puts(b, name[0] == '=' ? ")" : "))"); return; } } /* boolean receiver methods */ if (recv >= 0 && rt == TY_BOOL) { if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "(("); emit_expr(c, recv, b); buf_puts(b, ") ? SPL(\"true\") : SPL(\"false\"))"); return; } if (!strcmp(name, "&") || !strcmp(name, "|") || !strcmp(name, "^")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_printf(b, " %s ", name); emit_expr(c, argv[0], b); buf_puts(b, ")"); return; } } /* str.each_char / each_line / chars / lines / bytes / codepoints { |x| ... } -> iterate, return self. */ if (recv >= 0 && rt == TY_STRING && nt_ref(nt, id, "block") >= 0 && (!strcmp(name, "each_char") || !strcmp(name, "each_line") || !strcmp(name, "each_byte") || !strcmp(name, "chars") || !strcmp(name, "lines") || !strcmp(name, "bytes") || !strcmp(name, "codepoints"))) { int block = nt_ref(nt, id, "block"); int body = nt_ref(nt, block, "body"); const char *p0 = block_param_name(c, block, 0); if (p0) p0 = rename_local(p0); int ts = ++g_tmp, ti = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); int is_line = !strcmp(name, "each_line") || !strcmp(name, "lines"); int is_byte = !strcmp(name, "each_byte") || !strcmp(name, "bytes") || !strcmp(name, "codepoints"); Scope *cs_ech = p0 ? comp_scope_of(c, id) : NULL; LocalVar *clv_ech = (p0 && cs_ech) ? scope_local(cs_ech, p0) : NULL; int p0_box_poly_ech = clv_ech && clv_ech->type == TY_POLY; buf_printf(b, "({ const char *_t%d = %s; ", ts, rb.p ? rb.p : ""); free(rb.p); /* Save outer variable before loop to restore it afterward */ int tsv_ech = 0; if (p0 && clv_ech) { tsv_ech = ++g_tmp; Buf sv_ech; memset(&sv_ech, 0, sizeof sv_ech); emit_ctype(c, clv_ech->type, &sv_ech); buf_printf(b, "%s _t%d = lv_%s; ", sv_ech.p ? sv_ech.p : "sp_RbVal", tsv_ech, p0); free(sv_ech.p); } if (is_line) { int tl = ++g_tmp; /* chomp: true keyword arg uses the _chomp variant */ int eline_chomp = 0; if (argc == 1 && argv && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "KeywordHashNode")) { int cv = struct_kwarg_value(c, argv[0], "chomp"); eline_chomp = (cv >= 0 && nt_type(nt, cv) && !strcmp(nt_type(nt, cv), "TrueNode")); if (is_include) { TyKind at = infer_type(c, argv[0]); if (at == TY_INT) { buf_printf(b, " case SP_BUILTIN_INT_ARRAY: _t%d = sp_IntArray_include((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_RANGE: _t%d = sp_range_include((sp_Range *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else if (at == TY_STRING) { buf_printf(b, " case SP_BUILTIN_STR_ARRAY: _t%d = sp_StrArray_include((sp_StrArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_INT_HASH: _t%d = sp_StrIntHash_has_key((sp_StrIntHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_STR_HASH: _t%d = sp_StrStrHash_has_key((sp_StrStrHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_STR_POLY_HASH: _t%d = sp_StrPolyHash_has_key((sp_StrPolyHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } else if (at == TY_SYMBOL) { /* sym array is stored as IntArray (sp_sym == mrb_int) */ buf_printf(b, " case SP_BUILTIN_SYM_ARRAY: _t%d = sp_IntArray_include((sp_IntArray *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = sp_SymPolyHash_has_key((sp_SymPolyHash *)_t%d.v.p, _t%d); break;", tr, tv, atmp[0]); } /* PolyArray: box the arg for runtime comparison */ { int tbox = ++g_tmp; buf_printf(b, " case SP_BUILTIN_POLY_ARRAY: { sp_RbVal _t%d = ", tbox); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[0]); emit_boxed_text(c, at, tn, b); buf_printf(b, "; _t%d = sp_PolyArray_include((sp_PolyArray *)_t%d.v.p, _t%d); break; }", tr, tv, tbox); } /* PolyPolyHash: keys are boxed sp_RbVal */ { int tbox = ++g_tmp; buf_printf(b, " case SP_BUILTIN_POLY_POLY_HASH: { sp_RbVal _t%d = ", tbox); char tn[32]; snprintf(tn, sizeof tn, "_t%d", atmp[0]); emit_boxed_text(c, at, tn, b); buf_printf(b, "; _t%d = sp_PolyPolyHash_has_key((sp_PolyPolyHash *)_t%d.v.p, _t%d); break; }", tr, tv, tbox); } } buf_printf(b, "sp_StrArray *_t%d = %s(_t%d); for (mrb_int _t%d = 0; _t%d < sp_StrArray_length(_t%d); _t%d++) { ", tl, eline_chomp ? "sp_str_lines_chomp" : "sp_str_lines", ts, ti, ti, tl, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_str(sp_StrArray_get(_t%d, _t%d)); ", p0, tl, ti); else buf_printf(b, "lv_%s = sp_StrArray_get(_t%d, _t%d); ", p0, tl, ti); /* the poly value may actually be a string-keyed hash: dispatch `[]` / `fetch` to the matching hash storage, boxing the value into the poly result. */ int is_aref = !strcmp(name, "[]") && argc == 1; int is_fetch = !strcmp(name, "fetch") && (argc == 1 || argc == 2); if ((is_aref || is_fetch) && infer_type(c, argv[0]) == TY_STRING) { TyKind trt = is_scalar_ret(ret) ? ret : TY_INT; /* the result temp's type */ static const struct { const char *cls, *hn; TyKind vt; } HV[] = { {"SP_BUILTIN_STR_STR_HASH", "StrStr", TY_STRING}, {"SP_BUILTIN_STR_INT_HASH", "StrInt", TY_INT}, {"SP_BUILTIN_STR_POLY_HASH", "StrPoly", TY_POLY}, }; for (unsigned hvi = 0; hvi < sizeof HV / sizeof HV[0]; hvi++) { /* only a variant whose value fits the result temp can be emitted */ if (ret != TY_POLY && HV[hvi].vt != trt) continue; char getx[200]; snprintf(getx, sizeof getx, "sp_%sHash_get((sp_%sHash *)_t%d.v.p, _t%d)", HV[hvi].hn, HV[hvi].hn, tv, atmp[0]); buf_printf(b, " case %s: _t%d = sp_%sHash_has_key((sp_%sHash *)_t%d.v.p, _t%d) ? ", HV[hvi].cls, tr, HV[hvi].hn, HV[hvi].hn, tv, atmp[0]); if (ret == TY_POLY) emit_boxed_text(c, HV[hvi].vt, getx, b); else buf_puts(b, getx); buf_puts(b, " : "); if (is_fetch && argc == 2) { char dn[32]; snprintf(dn, sizeof dn, "_t%d", atmp[1]); if (ret == TY_POLY) emit_boxed_text(c, infer_type(c, argv[1]), dn, b); else buf_puts(b, dn); } else if (is_fetch) { buf_puts(b, "(sp_raise_cls(\"KeyError\", \"key not found\"), "); buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, ")"); } else buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, "; break;"); } } } else if (is_byte) { buf_printf(b, "for (mrb_int _t%d = 0; _t%d < (mrb_int)sp_str_byte_len(_t%d); _t%d++) { ", ti, ti, ts, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_int((unsigned char)_t%d[_t%d]); ", p0, ts, ti); else buf_printf(b, "lv_%s = (unsigned char)_t%d[_t%d]; ", p0, ts, ti); /* a symbol-keyed hash (`{ name: ... }`) reaches here as SymPolyHash; add its `[]` / `fetch` arm so a Hash receiver indexed by a symbol is not dropped when a user class also defines an instance `[]` (#1437). */ if ((is_aref || is_fetch) && infer_type(c, argv[0]) == TY_SYMBOL) { TyKind trt = is_scalar_ret(ret) ? ret : TY_INT; char getx[200]; snprintf(getx, sizeof getx, "sp_SymPolyHash_get((sp_SymPolyHash *)_t%d.v.p, _t%d)", tv, atmp[0]); buf_printf(b, " case SP_BUILTIN_SYM_POLY_HASH: _t%d = sp_SymPolyHash_has_key((sp_SymPolyHash *)_t%d.v.p, _t%d) ? ", tr, tv, atmp[0]); if (ret == TY_POLY) buf_puts(b, getx); else if (trt == TY_STRING) buf_printf(b, "sp_poly_to_s(%s)", getx); else if (trt == TY_FLOAT) buf_printf(b, "sp_poly_to_f(%s)", getx); else buf_printf(b, "sp_poly_to_i(%s)", getx); buf_puts(b, " : "); if (is_fetch && argc == 2) { char dn[32]; snprintf(dn, sizeof dn, "_t%d", atmp[1]); if (ret == TY_POLY) emit_boxed_text(c, infer_type(c, argv[1]), dn, b); else buf_puts(b, dn); } else if (is_fetch) { buf_puts(b, "(sp_raise_cls(\"KeyError\", \"key not found\"), "); buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, ")"); } else buf_puts(b, ret == TY_POLY ? "sp_box_nil()" : default_value(trt)); buf_puts(b, "; break;"); } buf_printf(b, " } _t%d; })", tr); free(atmp); return; } else { buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_str_length(_t%d); _t%d++) { ", ti, ti, ts, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_str(sp_str_char_at_or_nil(_t%d, _t%d)); ", p0, ts, ti); else buf_printf(b, "lv_%s = sp_str_char_at_or_nil(_t%d, _t%d); ", p0, ts, ti); } } int sv = g_nren; g_nren = 0; emit_stmts(c, body, b, 0); g_nren = sv; if (p0 && tsv_ech > 0) buf_printf(b, " lv_%s = _t%d;", p0, tsv_ech); buf_printf(b, " } _t%d; })", ts); return; } /* scalar receiver methods: evaluate the receiver once into rs, then splice its text (so a literal/complex receiver isn't rebuilt). */ if (recv >= 0 && (rt == TY_STRING || rt == TY_INT || rt == TY_FLOAT)) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs); const char *r = rs.p ? rs.p : ""; /* A String-typed receiver that resolved to a poly nil -- e.g. an unresolvable chain like `Rails.application.class.to_s` in a method that is compiled but never called -- emits sp_box_nil(); coerce it to a const char* (yields "" at runtime) so the string ops below type-check. */ if (rt == TY_STRING && !strcmp(r, "sp_box_nil()")) r = "sp_poly_to_s(sp_box_nil())"; int handled = 1; if (rt == TY_STRING) { /* blockless "a".upto("c") materializes the succ-sequence as an array */ if (!strcmp(name, "upto") && argc == 1 && nt_ref(nt, id, "block") < 0) { buf_printf(b, "sp_StrArray_from_string_range(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", 0)"); } /* string methods taking a regex-literal argument route to the engine */ else if ((!strcmp(name, "gsub") || !strcmp(name, "sub")) && argc == 2 && re_lit_index(c, argv[0]) >= 0) { const char *suf = comp_ntype(c, argv[1]) == TY_STR_STR_HASH ? "_str_str_hash" : ""; buf_printf(b, "sp_re_%s%s(sp_re_pat_%d, %s, ", name, suf, re_lit_index(c, argv[0]), r); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if ((!strcmp(name, "gsub") || !strcmp(name, "sub")) && argc == 2 && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "InterpolatedRegularExpressionNode")) { Buf rp; memset(&rp, 0, sizeof rp); emit_regex_pat_to_buf(c, argv[0], &rp); buf_printf(b, "sp_re_%s(%s, %s, ", name, rp.p ? rp.p : "NULL", r); emit_expr(c, argv[1], b); buf_puts(b, ")"); free(rp.p); } else if (!strcmp(name, "split") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_split(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "scan") && argc == 1 && re_lit_index(c, argv[0]) >= 0 && !re_has_captures(re_lit_src(c, argv[0]))) { buf_printf(b, "sp_re_scan(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "scan") && argc == 1 && re_lit_index(c, argv[0]) >= 0 && re_has_captures(re_lit_src(c, argv[0]))) { buf_printf(b, "sp_re_scan_poly(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "to_sym") || !strcmp(name, "intern")) buf_printf(b, "sp_sym_intern(%s)", r); else if (!strcmp(name, "length") || !strcmp(name, "size")) { if (g_hoist_len_var && g_hoist_len_recv && recv >= 0 && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "LocalVariableReadNode") && nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), g_hoist_len_recv)) buf_puts(b, g_hoist_len_var); else buf_printf(b, "sp_str_length(%s)", r); } else if (!strcmp(name, "bytesize")) buf_printf(b, "(mrb_int)sp_str_byte_len(%s)", r); else if (!strcmp(name, "upcase")) buf_printf(b, "sp_str_upcase(%s)", r); else if (!strcmp(name, "downcase")) buf_printf(b, "sp_str_downcase(%s)", r); else if (!strcmp(name, "capitalize")) buf_printf(b, "sp_str_capitalize(%s)", r); else if (!strcmp(name, "reverse")) buf_printf(b, "sp_str_reverse(%s)", r); else if (!strcmp(name, "strip")) buf_printf(b, "sp_str_strip(%s)", r); else if (!strcmp(name, "lstrip")) buf_printf(b, "sp_str_lstrip(%s)", r); else if (!strcmp(name, "rstrip")) buf_printf(b, "sp_str_rstrip(%s)", r); else if (!strcmp(name, "chomp") && argc == 1) { const char *a0ty = nt_type(nt, argv[0]); if (a0ty && !strcmp(a0ty, "NilNode")) { /* chomp(nil) returns the string unchanged */ buf_puts(b, r); /* string-range literal methods: the int-only sp_Range struct can't hold string bounds, so inline strcmp / char-iteration for a literal `("a".."z")` receiver. */ if (recv >= 0 && rt == TY_RANGE && nt_type(nt, unwrap_parens(c, recv)) && !strcmp(nt_type(nt, unwrap_parens(c, recv)), "RangeNode")) { int rnode = unwrap_parens(c, recv); int lo = nt_ref(nt, rnode, "left"), hi = nt_ref(nt, rnode, "right"); if (lo >= 0 && hi >= 0 && comp_ntype(c, lo) == TY_STRING && comp_ntype(c, hi) == TY_STRING) { int excl = (int)(nt_int(nt, rnode, "flags", 0) & 4) ? 1 : 0; if ((!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "cover?") || !strcmp(name, "===")) && argc == 1) { if (a0 != TY_STRING) { /* a non-string can't be in a string range: false (eval arg) */ buf_puts(b, "((void)("); emit_expr(c, argv[0], b); buf_puts(b, "), 0)"); } else { buf_printf(b, "sp_str_chomp_sep(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); int ta = ++g_tmp; buf_printf(b, "({ const char *_t%d = ", ta); emit_expr(c, argv[0], b); buf_puts(b, "; (strcmp("); emit_expr(c, lo, b); buf_printf(b, ", _t%d) <= 0 && strcmp(_t%d, ", ta, ta); emit_expr(c, hi, b); buf_printf(b, ") %s 0); })", excl ? "<" : "<="); } return; } else if (!strcmp(name, "chomp")) buf_printf(b, "sp_str_chomp(%s)", r); else if (!strcmp(name, "chop")) buf_printf(b, "sp_str_chop(%s)", r); else if (!strcmp(name, "to_s") || !strcmp(name, "to_str")) buf_puts(b, r); else if ((!strcmp(name, "dup") || !strcmp(name, "clone")) && argc == 0) buf_printf(b, "sp_str_dup_external(%s)", r); else if (!strcmp(name, "inspect")) { int tv = ++g_tmp; buf_printf(b, "({ const char *_t%d = %s; _t%d ? sp_str_inspect(_t%d) : SPL(\"nil\"); })", tv, r, tv, tv); } else if (!strcmp(name, "empty?")) buf_printf(b, "(sp_str_length(%s) == 0)", r); else if (!strcmp(name, "include?") && argc == 1) { buf_printf(b, "sp_str_include(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); if (!strcmp(name, "to_a") && argc == 0) { /* succ-based string range (handles multi-char: "aa".."ac" etc.) */ buf_puts(b, "sp_StrArray_from_string_range("); emit_expr(c, lo, b); buf_puts(b, ", "); emit_expr(c, hi, b); buf_printf(b, ", %d)", excl); return; } else if (!strcmp(name, "start_with?") && argc == 1) { buf_printf(b, "sp_str_start_with(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "end_with?") && argc == 1) { buf_printf(b, "sp_str_end_with(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "ascii_only?") && argc == 0) buf_printf(b, "sp_str_ascii_only(%s)", r); else if (!strcmp(name, "valid_encoding?") && argc == 0) buf_printf(b, "sp_str_valid_encoding(%s)", r); else if (!strcmp(name, "index") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_index_poly(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "index") && argc == 1) { /* nil-on-miss carried as the SP_INT_NIL sentinel (a nullable int) */ buf_printf(b, "sp_str_index_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "index") && argc == 2) { buf_printf(b, "sp_str_index_from_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if ((!strcmp(name, "partition") || !strcmp(name, "rpartition")) && argc == 1 && re_lit_index(c, argv[0]) < 0) { buf_printf(b, "sp_str_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "partition") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { /* [before, match, after] from the first regex match, else [s, "", ""] */ int tr = ++g_tmp; buf_printf(b, "({ sp_StrArray *_t%d = sp_StrArray_new();" " if (sp_re_match(sp_re_pat_%d, %s) >= 0) {" " sp_StrArray_push(_t%d, sp_re_match_pre); sp_StrArray_push(_t%d, sp_re_match_str);" " sp_StrArray_push(_t%d, sp_re_match_post); } else {" " sp_StrArray_push(_t%d, %s); sp_StrArray_push(_t%d, SPL(\"\")); sp_StrArray_push(_t%d, SPL(\"\")); }" " _t%d; })", tr, re_lit_index(c, argv[0]), r, tr, tr, tr, tr, r, tr, tr, tr); } else if (!strcmp(name, "rpartition") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_rpartition(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "rindex") && argc == 1 && re_lit_index(c, argv[0]) >= 0) { buf_printf(b, "sp_re_rindex_opt(sp_re_pat_%d, %s)", re_lit_index(c, argv[0]), r); } else if (!strcmp(name, "rindex") && argc == 1) { buf_printf(b, "sp_str_rindex_opt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rindex") && argc == 2) { buf_printf(b, "sp_str_rindex_from(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "crypt") && argc == 1) { buf_printf(b, "sp_str_crypt(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "scrub") && argc == 0) buf_printf(b, "sp_str_scrub(%s, 0)", r); else if (!strcmp(name, "scrub") && argc == 1) { buf_printf(b, "sp_str_scrub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && re_lit_index(c, argv[0]) >= 0) { /* s[/re/] -> the matched substring, or nil (NULL) on no match */ buf_printf(b, "(sp_re_match(sp_re_pat_%d, %s) >= 0 ? sp_re_match_str : NULL)", re_lit_index(c, argv[0]), r); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")) { /* s[a..b] / s[a...b]; beginless/endless ranges use 0 / length */ int rn = argv[0]; int excl = (int)(nt_int(c->nt, rn, "flags", 0) & 4) ? 1 : 0; int lo = nt_ref(c->nt, rn, "left"), hi = nt_ref(c->nt, rn, "right"); buf_printf(b, "sp_str_sub_range_r(%s, ", r); if (lo >= 0) emit_expr(c, lo, b); else buf_puts(b, "0"); buf_puts(b, ", "); if (hi >= 0) { emit_expr(c, hi, b); buf_printf(b, ", %d)", excl); } else buf_printf(b, "(mrb_int)sp_str_length(%s), 0)", r); /* endless: to the end */ } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 2) { /* s[start, len] */ buf_printf(b, "sp_str_sub_range(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if ((!strcmp(name, "[]") || !strcmp(name, "slice")) && argc == 1) { buf_printf(b, "sp_str_char_at_or_nil(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "split") && argc == 0) buf_printf(b, "sp_str_split_ws(%s)", r); else if (!strcmp(name, "split") && argc == 1) { /* split(nil) and split(" ") are whitespace-mode; split(sep) drops trailing empties */ const char *aty = nt_type(c->nt, argv[0]); int nil_arg = aty && !strcmp(aty, "NilNode"); int ws = nil_arg || (aty && !strcmp(aty, "StringNode") && nt_str(c->nt, argv[0], "content") && !strcmp(nt_str(c->nt, argv[0], "content"), " ")); if (ws) buf_printf(b, "sp_str_split_ws(%s)", r); else { buf_printf(b, "sp_str_split_drop_trailing(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } } else if (!strcmp(name, "split") && argc == 2) { buf_printf(b, "sp_str_split_limit(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "clamp") && (argc == 2 || (argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")))) { int lo_n, hi_n; if (argc == 2) { lo_n = argv[0]; hi_n = argv[1]; } else { int rn = argv[0]; lo_n = nt_ref(c->nt, rn, "left"); hi_n = nt_ref(c->nt, rn, "right"); } int tc = ++g_tmp, tlo = ++g_tmp, thi = ++g_tmp; buf_printf(b, "({ const char *_t%d = %s; const char *_t%d = ", tc, r, tlo); emit_expr(c, lo_n, b); buf_printf(b, "; const char *_t%d = ", thi); emit_expr(c, hi_n, b); buf_printf(b, "; strcmp(_t%d, _t%d) < 0 ? _t%d : (strcmp(_t%d, _t%d) > 0 ? _t%d : _t%d); })", tc, tlo, tlo, tc, thi, thi, tc); } else if (!strcmp(name, "oct") && argc == 0) buf_printf(b, "sp_str_oct(%s)", r); else if (!strcmp(name, "hex") && argc == 0) buf_printf(b, "sp_str_to_i_base(%s, 16)", r); else if (!strcmp(name, "ord") && argc == 0) buf_printf(b, "sp_str_ord(%s)", r); else if ((!strcmp(name, "force_encoding") || !strcmp(name, "b") || !strcmp(name, "encode")) && argc <= 1) buf_printf(b, "(%s)", r); else if (!strcmp(name, "encoding") && argc == 0) buf_printf(b, "((void)(%s), sp_box_encoding(sp_encoding_utf8()))", r); else if (!strcmp(name, "dump") && argc == 0) buf_printf(b, "sp_str_dump(%s)", r); else if (!strcmp(name, "undump") && argc == 0) buf_printf(b, "sp_str_undump(%s)", r); else if (!strcmp(name, "casecmp") && argc == 1) { buf_printf(b, "sp_str_casecmp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "casecmp?") && argc == 1) { buf_printf(b, "(sp_str_casecmp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ") == 0)"); } else if (!strcmp(name, "byteslice") && argc == 2) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "byteslice") && argc == 1) { buf_printf(b, "sp_str_byteslice(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", 1)"); } else if (!strcmp(name, "setbyte") && argc == 2) { buf_printf(b, "sp_str_setbyte(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "getbyte") && argc == 1) { /* inline to a direct byte load (matches the legacy generator): the per-byte sp_str_getbyte call recomputes the string length and bounds every iteration, which the C compiler can't hoist across an aliasing setbyte. An out-of-range index reads adjacent bytes (as in legacy). */ buf_printf(b, "((mrb_int)(unsigned char)(%s)[", r); emit_int_expr(c, argv[0], b); buf_puts(b, "])"); } } /* range value methods (evaluate the range once into a temp) */ if (recv >= 0 && rt == TY_RANGE) { int block = nt_ref(nt, id, "block"); if (!strcmp(name, "step") && argc == 1) { int t = ++g_tmp, ar = ++g_tmp, ii = ++g_tmp, st = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); Buf sb; memset(&sb, 0, sizeof sb); emit_expr(c, argv[0], &sb); buf_printf(b, "({ sp_Range _t%d = %s; mrb_int _t%d = %s; sp_IntArray *_t%d = sp_IntArray_new();" " for (mrb_int _t%d = _t%d.first; _t%d <= _t%d.last - _t%d.excl; _t%d += _t%d)" " sp_IntArray_push(_t%d, _t%d); _t%d; })", t, rb.p ? rb.p : "", st, sb.p ? sb.p : "", ar, ii, t, ii, t, t, ii, st, ar, ii, ar); free(rb.p); free(sb.p); return; } if (!strcmp(name, "each") && block < 0) { /* enumerator: materialize to_a */ int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); buf_printf(b, "({ sp_Range _t%d = %s; sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl); })", t, rb.p ? rb.p : "", t, t, t); free(rb.p); return; } static const char *const rmeths[] = { "to_a", "include?", "member?", "cover?", "===", "sum", "min", "max", "first", "last", "size", "count", "begin", "end", "exclude_end?", "eql?", "minmax", "overlap?", NULL }; int known = 0; for (int i = 0; rmeths[i]; i++) if (!strcmp(name, rmeths[i])) known = 1; if (known) { /* size/count on a string-literal range: no integer size -> nil, skip creating sp_Range */ if ((!strcmp(name, "size") || !strcmp(name, "count")) && argc == 0) { int rn = unwrap_parens(c, recv); if (rn >= 0 && nt_type(nt, rn) && !strcmp(nt_type(nt, rn), "RangeNode")) { int lo = nt_ref(nt, rn, "left"); if (lo >= 0 && comp_ntype(c, lo) == TY_STRING) { buf_puts(b, "SP_INT_NIL"); return; } } } else if (!strcmp(name, "squeeze") && argc == 0) buf_printf(b, "sp_str_squeeze(%s)", r); else if (!strcmp(name, "squeeze") && argc == 1) { buf_printf(b, "sp_str_squeeze_chars(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "squeeze") && argc >= 2) { buf_printf(b, "sp_str_squeeze_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); int t = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); emit_indent(g_pre, g_indent); buf_printf(g_pre, "sp_Range _t%d = ", t); buf_puts(g_pre, rb.p ? rb.p : ""); buf_puts(g_pre, ";\n"); free(rb.p); if (!strcmp(name, "to_a")) buf_printf(b, "sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl)", t, t, t); else if (!strcmp(name, "include?") || !strcmp(name, "member?") || !strcmp(name, "cover?") || !strcmp(name, "===")) { /* cover?(range) checks that both endpoints of the arg fit inside self */ if (!strcmp(name, "cover?") && argc == 1 && comp_ntype(c, argv[0]) == TY_RANGE) { int t2 = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", t2); emit_expr(c, argv[0], b); buf_printf(b, "; _t%d.first >= _t%d.first && (_t%d.last - _t%d.excl) <= (_t%d.last - _t%d.excl); })", t2, t, t2, t2, t, t); } else { /* sp_range_include takes mrb_int; a float arg (`(1..).include?(2.4)`) needs an explicit cast, else clang -Werror flags the implicit float-literal->int conversion (gcc truncates silently). */ int arg_is_float = comp_ntype(c, argv[0]) == TY_FLOAT; buf_printf(b, "sp_range_include(&_t%d, ", t); if (arg_is_float) buf_puts(b, "(mrb_int)("); emit_expr(c, argv[0], b); if (arg_is_float) buf_puts(b, ")"); buf_puts(b, ")"); } } else if ((!strcmp(name, "tr") || !strcmp(name, "tr_s")) && argc == 2) { buf_printf(b, "sp_str_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); else if (!strcmp(name, "first") || !strcmp(name, "min") || !strcmp(name, "begin")) { if (argc == 1) { /* first(n): collect up to n elements starting at first */ int tf = ++g_tmp, tn = ++g_tmp, ti = ++g_tmp; buf_printf(b, "({ sp_IntArray *_t%d = sp_IntArray_new(); mrb_int _t%d = ", tf, tn); emit_expr(c, argv[0], b); buf_printf(b, "; for (mrb_int _t%d = _t%d.first; _t%d <= _t%d.last - _t%d.excl && _t%d - _t%d.first < _t%d; _t%d++)" " sp_IntArray_push(_t%d, _t%d); _t%d; })", ti, t, ti, t, t, ti, t, tn, ti, tf, ti, tf); } else buf_printf(b, "(_t%d.first)", t); } else if (!strcmp(name, "delete") && argc == 0) { buf_printf(b, "(%s)", r); return; } else if (!strcmp(name, "delete") && argc == 1) { buf_printf(b, "sp_str_delete(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "delete") && argc >= 2) { buf_printf(b, "sp_str_delete_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); else if (!strcmp(name, "max")) /* max element: end minus the exclusive bound */ buf_printf(b, "(_t%d.last - _t%d.excl)", t, t); else if (!strcmp(name, "last") || !strcmp(name, "end")) { if (argc == 1 && !strcmp(name, "last")) { /* last(n): collect up to n elements ending at last */ int tf = ++g_tmp, tn = ++g_tmp, ts = ++g_tmp, te = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", tn); emit_expr(c, argv[0], b); buf_printf(b, "; mrb_int _t%d = _t%d.last - _t%d.excl;", te, t, t); buf_printf(b, " mrb_int _t%d = _t%d - _t%d + 1; if (_t%d < _t%d.first) _t%d = _t%d.first;", ts, te, tn, ts, t, ts, t); buf_printf(b, " sp_IntArray *_t%d = sp_IntArray_new(); for (mrb_int _i%d = _t%d; _i%d <= _t%d; _i%d++)" " sp_IntArray_push(_t%d, _i%d); _t%d; })", tf, tf, ts, tf, te, tf, tf, tf, tf); } else buf_printf(b, "(_t%d.last)", t); } else if (!strcmp(name, "count") && argc == 0) { buf_printf(b, "(sp_raise_cls(\"TypeError\", \"no implicit conversion of nil into String\"), 0LL)"); return; } else if (!strcmp(name, "count") && argc == 1) { buf_printf(b, "sp_str_count(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "count") && argc >= 2) { buf_printf(b, "sp_str_count_n(%s, (const char *[]){", r); for (int a = 0; a < argc; a++) { if (a) buf_puts(b, ", "); emit_expr(c, argv[a], b); } buf_printf(b, "}, %d)", argc); else if (!strcmp(name, "size") || !strcmp(name, "count")) buf_printf(b, "(_t%d.last - _t%d.excl - _t%d.first + 1)", t, t, t); else if (!strcmp(name, "sum")) buf_printf(b, "sp_IntArray_sum(sp_IntArray_from_range(_t%d.first, _t%d.last - _t%d.excl), 0)", t, t, t); else if (!strcmp(name, "exclude_end?")) buf_printf(b, "(_t%d.excl != 0)", t); else if (!strcmp(name, "eql?")) { buf_printf(b, "sp_range_eq(_t%d, ", t); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "lines") && argc == 0) buf_printf(b, "sp_str_lines(%s)", r); else if (!strcmp(name, "lines") && argc == 1 && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "KeywordHashNode")) { int chomp_v = struct_kwarg_value(c, argv[0], "chomp"); int is_chomp = (chomp_v >= 0 && nt_type(nt, chomp_v) && !strcmp(nt_type(nt, chomp_v), "TrueNode")); buf_printf(b, "%s(%s)", is_chomp ? "sp_str_lines_chomp" : "sp_str_lines", r); else if (!strcmp(name, "overlap?")) { int t2 = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", t2); emit_expr(c, argv[0], b); buf_printf(b, "; (_t%d.first <= _t%d.last - _t%d.excl && _t%d.first <= _t%d.last - _t%d.excl); })", t, t2, t2, t2, t, t, t); } else if (!strcmp(name, "bytes") && argc == 0) buf_printf(b, "sp_str_bytes(%s)", r); else if (!strcmp(name, "codepoints") && argc == 0) buf_printf(b, "sp_str_codepoints(%s)", r); else if (!strcmp(name, "unpack") && argc == 1) { buf_printf(b, "sp_str_unpack(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "chars") && argc == 0) buf_printf(b, "sp_str_chars(%s)", r); else if ((!strcmp(name, "succ") || !strcmp(name, "next")) && argc == 0) buf_printf(b, "sp_str_succ(%s)", r); else if (!strcmp(name, "to_i") && argc == 0) buf_printf(b, "sp_str_to_i_cruby(%s)", r); else if (!strcmp(name, "to_i") && argc == 1) { buf_printf(b, "sp_str_to_i_base(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "to_f") && argc == 0) buf_printf(b, "atof(%s)", r); else if (!strcmp(name, "gsub") && argc == 2) { buf_printf(b, "sp_str_gsub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); else if (!strcmp(name, "minmax")) { int ma = ++g_tmp; buf_printf(b, "({ sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, _t%d.first);" " sp_IntArray_push(_t%d, _t%d.last - _t%d.excl); _t%d; })", ma, ma, t, ma, t, t, ma); } else if (!strcmp(name, "sub") && argc == 2 && comp_ntype(c, argv[1]) == TY_STR_STR_HASH) { buf_printf(b, "sp_str_sub_str_str_hash(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); return; } } /* hash value methods */ /* {}.default (empty hash literal with unknown type) always returns nil */ if (recv >= 0 && !strcmp(name, "default") && argc == 0 && !ty_is_hash(rt)) { buf_puts(b, "sp_box_nil()"); return; } if (emit_hash_call(c, id, b)) return; /* `arr[i] = v` in expression position: do the store, evaluate to the rhs (Ruby []= returns the assigned value). The statement form is emitted elsewhere; this covers rvalue chains like `b = arr[i] = v`. */ /* a[i, n] = src — slice assignment */ if (recv >= 0 && ty_is_array(rt) && !strcmp(name, "[]=") && argc == 3) { const char *k = (rt == TY_POLY_ARRAY) ? "Poly" : array_kind(rt); TyKind rhs_ty = comp_ntype(c, argv[2]); if (k && ty_is_array(rhs_ty)) { /* src is an array: copy elements from src into arr starting at i */ int ta = ++g_tmp, ti = ++g_tmp, ts = ++g_tmp, tj = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); buf_printf(b, "sp_%sArray *_t%d = ", k, ts); emit_expr(c, argv[2], b); buf_puts(b, "; "); buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_%sArray_length(_t%d); _t%d++)", tj, tj, k, ts, tj); buf_printf(b, " sp_%sArray_set(_t%d, _t%d + _t%d, sp_%sArray_get(_t%d, _t%d));", k, ta, ti, tj, k, ts, tj); buf_printf(b, " _t%d; })", ts); return; } if (k && rhs_ty == TY_POLY && rt != TY_POLY_ARRAY) { /* poly RHS wrapping a same-kind array (e.g. PolyArray element is IntArray): unbox via v.p cast and copy elements */ int ta3 = ++g_tmp, ti3 = ++g_tmp, ts3 = ++g_tmp, tj3 = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta3); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti3); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); buf_printf(b, "sp_RbVal _tv%d = ", ts3); emit_expr(c, argv[2], b); buf_puts(b, "; "); buf_printf(b, "sp_%sArray *_t%d = (sp_%sArray *)_tv%d.v.p; ", k, ts3, k, ts3); buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_%sArray_length(_t%d); _t%d++)", tj3, tj3, k, ts3, tj3); buf_printf(b, " sp_%sArray_set(_t%d, _t%d + _t%d, sp_%sArray_get(_t%d, _t%d));", k, ta3, ti3, tj3, k, ts3, tj3); buf_printf(b, " _tv%d; })", ts3); return; } if (k && rhs_ty == TY_POLY && rt == TY_POLY_ARRAY) { /* poly_array recv + poly src (array at runtime): copy src elements to recv[start..] */ int ta4 = ++g_tmp, tst4 = ++g_tmp, tsrc4 = ++g_tmp, tlen4 = ++g_tmp, tj4 = ++g_tmp; buf_printf(b, "({ sp_PolyArray *_t%d = ", ta4); emit_expr(c, recv, b); buf_puts(b, ";"); buf_printf(b, " mrb_int _t%d = ", tst4); emit_int_expr(c, argv[0], b); buf_puts(b, ";"); buf_printf(b, " sp_RbVal _t%d = ", tsrc4); emit_expr(c, argv[2], b); buf_puts(b, ";"); buf_printf(b, " mrb_int _t%d = sp_poly_arr_len(_t%d);", tlen4, tsrc4); buf_printf(b, " for (mrb_int _t%d = 0; _t%d < _t%d; _t%d++)", tj4, tj4, tlen4, tj4); buf_printf(b, " sp_PolyArray_set(_t%d, _t%d + _t%d, sp_poly_arr_get(_t%d, _t%d));", ta4, tst4, tj4, tsrc4, tj4); buf_printf(b, " _t%d; })", tsrc4); return; } if (k && !ty_is_array(rhs_ty)) { /* scalar RHS: set element at start index and return the scalar value */ int ta2 = ++g_tmp, ti2 = ++g_tmp, tv2 = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, ta2); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti2); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); if (rt == TY_POLY_ARRAY) { buf_printf(b, "sp_RbVal _t%d = ", tv2); emit_boxed(c, argv[2], b); } else if (!strcmp(name, "sub") && argc == 2) { buf_printf(b, "sp_str_sub(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); else { TyKind et2 = ty_array_elem(rt); emit_ctype(c, et2, b); buf_printf(b, " _t%d = ", tv2); if (rhs_ty == TY_POLY && et2 == TY_INT) { buf_puts(b, "sp_poly_to_i("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else if (rhs_ty == TY_POLY && et2 == TY_STRING) { buf_puts(b, "sp_poly_to_s("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else if (rhs_ty == TY_POLY && et2 == TY_FLOAT) { buf_puts(b, "sp_poly_to_f("); emit_expr(c, argv[2], b); buf_puts(b, ")"); } else emit_expr(c, argv[2], b); } else if (!strcmp(name, "tr") && argc == 2) { buf_printf(b, "sp_str_tr(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); buf_printf(b, "; sp_%sArray_set(_t%d, _t%d, _t%d); _t%d; })", k, ta2, ti2, tv2, tv2); return; } } if (recv >= 0 && ty_is_array(rt) && !strcmp(name, "[]=") && argc == 2) { const char *k = (rt == TY_POLY_ARRAY) ? "Poly" : array_kind(rt); if (k) { int t = ++g_tmp, ti = ++g_tmp, tv = ++g_tmp; buf_printf(b, "({ sp_%sArray *_t%d = ", k, t); emit_expr(c, recv, b); buf_printf(b, "; mrb_int _t%d = ", ti); emit_int_expr(c, argv[0], b); buf_puts(b, "; "); if (rt == TY_POLY_ARRAY) { buf_printf(b, "sp_RbVal _t%d = ", tv); emit_boxed(c, argv[1], b); } else if (!strcmp(name, "center") && argc == 1) { buf_printf(b, "sp_str_center(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); else { TyKind et = ty_array_elem(rt); TyKind vt = comp_ntype(c, argv[1]); emit_ctype(c, et, b); buf_printf(b, " _t%d = ", tv); if (vt == TY_POLY && et == TY_INT) { buf_puts(b, "sp_poly_to_i("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (vt == TY_POLY && et == TY_STRING) { buf_puts(b, "sp_poly_to_s("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (vt == TY_POLY && et == TY_FLOAT) { buf_puts(b, "sp_poly_to_f("); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else emit_expr(c, argv[1], b); } else if (!strcmp(name, "center") && argc == 2) { buf_printf(b, "sp_str_center2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "ljust") && argc == 1) { buf_printf(b, "sp_str_ljust(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "ljust") && argc == 2) { buf_printf(b, "sp_str_ljust2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "rjust") && argc == 1) { buf_printf(b, "sp_str_rjust(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "rjust") && argc == 2) { buf_printf(b, "sp_str_rjust2(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else handled = 0; buf_printf(b, "; sp_%sArray_set(_t%d, _t%d, _t%d); _t%d; })", k, t, ti, tv, tv); return; } else if (rt == TY_INT) { /* a nullable int's to_s/inspect tests the value and converts it -- bind the receiver to a temp first so a side-effecting `r` (e.g. ARGF.read, a method call) is evaluated exactly once, not twice. */ if (!strcmp(name, "to_s") && argc == 0) { int _tn = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn); } /* array value methods */ /* empty array literal [] has TY_UNKNOWN; sum returns init or 0 */ if (recv >= 0 && rt == TY_UNKNOWN && !strcmp(name, "sum") && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ArrayNode")) { int en = 0; nt_arr(nt, recv, "elements", &en); if (en == 0) { TyKind call_t = comp_ntype(c, id); if (argc == 1) { if (call_t == TY_POLY) emit_boxed(c, argv[0], b); else emit_expr(c, argv[0], b); } else if (!strcmp(name, "inspect")) { int _tn = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = (%s); _t%d == SP_INT_NIL ? SPL(\"nil\") : sp_int_to_s(_t%d); })", _tn, r, _tn, _tn); } else if (!strcmp(name, "to_f")) buf_printf(b, "((mrb_float)(%s))", r); else if ((!strcmp(name, "to_i") || !strcmp(name, "to_int") || !strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 0) buf_printf(b, "(%s)", r); else if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 1) { buf_printf(b, "sp_int_%s(%s, ", name, r); emit_expr(c, argv[0], b); buf_puts(b, ")"); else { if (call_t == TY_POLY) buf_puts(b, "sp_box_int(0)"); else buf_puts(b, "0"); } else if (!strcmp(name, "abs")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "chr")) buf_printf(b, "sp_int_chr(%s)", r); else if (!strcmp(name, "[]") && argc == 1) { buf_printf(b, "(((%s) >> (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) & 1)"); } else if (!strcmp(name, "even?")) buf_printf(b, "((%s) %% 2 == 0)", r); else if (!strcmp(name, "odd?")) buf_printf(b, "((%s) %% 2 != 0)", r); else if (!strcmp(name, "zero?")) buf_printf(b, "((%s) == 0)", r); else if (!strcmp(name, "nonzero?")) buf_printf(b, "((%s) == 0 ? SP_INT_NIL : (%s))", r, r); else if (!strcmp(name, "positive?")) buf_printf(b, "((%s) > 0)", r); else if (!strcmp(name, "negative?")) buf_printf(b, "((%s) < 0)", r); else if (!strcmp(name, "divmod") && argc == 1) { int tb = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", tb); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, sp_idiv(%s, _t%d));" " sp_IntArray_push(_t%d, sp_imod(%s, _t%d)); _t%d; })", o, o, r, tb, o, r, tb, o); return; } } /* take_while/drop_while/each_index/set-ops on empty array literal [] (TY_UNKNOWN receiver) */ if (recv >= 0 && rt == TY_UNKNOWN && (!strcmp(name, "take_while") || !strcmp(name, "drop_while") || !strcmp(name, "each_index") || !strcmp(name, "difference") || !strcmp(name, "-") || !strcmp(name, "&") || !strcmp(name, "|") || !strcmp(name, "intersection") || !strcmp(name, "union") || !strcmp(name, "+") || !strcmp(name, "zip") || !strcmp(name, "flatten") || !strcmp(name, "compact") || !strcmp(name, "uniq") || !strcmp(name, "sort") || !strcmp(name, "reverse") || !strcmp(name, "shuffle")) && nt_type(nt, recv) && !strcmp(nt_type(nt, recv), "ArrayNode")) { int en = 0; nt_arr(nt, recv, "elements", &en); if (en == 0) { if (!strcmp(name, "each_index")) { /* each_index on [] is a no-op; evaluate receiver for side-effects */ emit_expr(c, recv, b); } else if (!strcmp(name, "div") && argc == 1) { buf_printf(b, "sp_idiv(%s, ", r); emit_int_divisor(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "gcd") && argc == 1) { buf_printf(b, "sp_gcd(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "lcm") && argc == 1) { buf_printf(b, "sp_lcm(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "magnitude") && argc == 0) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "modulo") && argc == 1) { buf_printf(b, "sp_imod(%s, ", r); emit_int_divisor(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "remainder") && argc == 1) { buf_printf(b, "((%s) %% (", r); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if (!strcmp(name, "size") && argc == 0) buf_puts(b, "((mrb_int)sizeof(mrb_int))"); else if (!strcmp(name, "gcdlcm") && argc == 1) { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new(); sp_IntArray_push(_t%d, sp_gcd(%s, _t%d));" " sp_IntArray_push(_t%d, sp_lcm(%s, _t%d)); _t%d; })", o, o, r, ta, o, r, ta, o); else if (!strcmp(name, "take_while") || !strcmp(name, "drop_while")) { buf_puts(b, "sp_PolyArray_new()"); } else if (!strcmp(name, "clamp") && argc == 2) { buf_printf(b, "sp_int_clamp(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "clamp") && argc == 1 && nt_type(c->nt, argv[0]) && !strcmp(nt_type(c->nt, argv[0]), "RangeNode")) { int rn = argv[0]; int tcr = ++g_tmp; buf_printf(b, "({ sp_Range _t%d = ", tcr); emit_expr(c, argv[0], b); buf_printf(b, "; sp_int_clamp(%s, _t%d.first, _t%d.last - _t%d.excl); })", r, tcr, tcr, tcr); (void)rn; } else if (!strcmp(name, "digits") && argc == 0) buf_printf(b, "sp_int_digits(%s, 10)", r); else if (!strcmp(name, "allbits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_printf(b, ")) == ("); emit_expr(c, argv[0], b); buf_puts(b, "))"); } else if (!strcmp(name, "anybits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) != 0)"); } else if (!strcmp(name, "nobits?") && argc == 1) { buf_printf(b, "(((%s) & (", r); emit_expr(c, argv[0], b); buf_puts(b, ")) == 0)"); } else if (!strcmp(name, "ceildiv") && argc == 1) { buf_printf(b, "sp_ceildiv(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pow") && argc == 2) { buf_printf(b, "sp_powmod(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ", "); emit_expr(c, argv[1], b); buf_puts(b, ")"); } else if (!strcmp(name, "pow") && argc == 1) { buf_printf(b, "sp_int_pow(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "pred") && argc == 0) buf_printf(b, "((%s) - 1)", r); else if ((!strcmp(name, "succ") || !strcmp(name, "next")) && argc == 0) buf_printf(b, "((%s) + 1)", r); else if (!strcmp(name, "to_s") && argc == 1) { buf_printf(b, "sp_int_to_s_base(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "coerce") && argc == 1) { TyKind a0 = comp_ntype(c, argv[0]); if (a0 == TY_FLOAT) { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_float _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, _t%d);" " sp_FloatArray_push(_t%d, (mrb_float)(%s)); _t%d; })", o, o, ta, o, r, o); else { /* set/transform ops on [] receiver: call the runtime with NULL first arg */ TyKind akt = argc > 0 ? comp_ntype(c, argv[0]) : TY_UNKNOWN; const char *ek = ty_is_array(akt) ? ((akt == TY_POLY_ARRAY) ? "Poly" : array_kind(akt)) : NULL; if (!ek) ek = "Poly"; if (argc > 0 && akt != TY_UNKNOWN && (!strcmp(name, "union") || !strcmp(name, "|") || !strcmp(name, "difference") || !strcmp(name, "-") || !strcmp(name, "intersection") || !strcmp(name, "&") || !strcmp(name, "+") || !strcmp(name, "zip"))) { /* call the real function with NULL receiver (handles empty-self case) */ const char *fn = (!strcmp(name, "&") || !strcmp(name, "intersection")) ? "intersect" : (!strcmp(name, "|") || !strcmp(name, "union")) ? "union" : (!strcmp(name, "+")) ? "concat" : "difference"; buf_printf(b, "sp_%sArray_%s(NULL, ", ek, fn); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else { int ta = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_IntArray *_t%d = sp_IntArray_new();" " sp_IntArray_push(_t%d, _t%d);" " sp_IntArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); buf_printf(b, "sp_%sArray_new()", ek); } } else handled = 0; return; } } if (emit_array_call(c, id, b)) return; /* symbol receiver methods */ if (recv >= 0 && rt == TY_SYMBOL) { if (!strcmp(name, "to_s") || !strcmp(name, "id2name") || !strcmp(name, "name")) { buf_puts(b, "sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")"); return; } if (!strcmp(name, "inspect")) { buf_puts(b, "sp_str_concat(SPL(\":\"), sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, "))"); return; } if (!strcmp(name, "to_sym") || !strcmp(name, "itself")) { emit_expr(c, recv, b); return; } /* case-folding methods return a (re-interned) symbol */ if (!strcmp(name, "upcase") || !strcmp(name, "downcase") || !strcmp(name, "capitalize") || !strcmp(name, "swapcase")) { buf_printf(b, "sp_sym_intern(sp_str_%s(sp_sym_to_s(", name); emit_expr(c, recv, b); buf_puts(b, ")))"); return; } if (!strcmp(name, "length") || !strcmp(name, "size")) { buf_puts(b, "((mrb_int)strlen(sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")))"); return; } if (!strcmp(name, "empty?")) { buf_puts(b, "(strlen(sp_sym_to_s("); emit_expr(c, recv, b); buf_puts(b, ")) == 0)"); return; } if (!strcmp(name, "==") || !strcmp(name, "!=")) { buf_puts(b, name[0] == '=' ? "(" : "(!("); emit_expr(c, recv, b); buf_puts(b, " == "); emit_expr(c, argv[0], b); buf_puts(b, name[0] == '=' ? ")" : "))"); return; } } /* boolean receiver methods */ if (recv >= 0 && rt == TY_BOOL) { if (!strcmp(name, "to_s") || !strcmp(name, "inspect")) { buf_puts(b, "(("); emit_expr(c, recv, b); buf_puts(b, ") ? SPL(\"true\") : SPL(\"false\"))"); return; } if (!strcmp(name, "&") || !strcmp(name, "|") || !strcmp(name, "^")) { buf_puts(b, "("); emit_expr(c, recv, b); buf_printf(b, " %s ", name); emit_expr(c, argv[0], b); buf_puts(b, ")"); return; } } /* str.each_char / each_line / chars / lines / bytes / codepoints { |x| ... } -> iterate, return self. */ if (recv >= 0 && rt == TY_STRING && nt_ref(nt, id, "block") >= 0 && (!strcmp(name, "each_char") || !strcmp(name, "each_line") || !strcmp(name, "each_byte") || !strcmp(name, "chars") || !strcmp(name, "lines") || !strcmp(name, "bytes") || !strcmp(name, "codepoints"))) { int block = nt_ref(nt, id, "block"); int body = nt_ref(nt, block, "body"); const char *p0 = block_param_name(c, block, 0); if (p0) p0 = rename_local(p0); int ts = ++g_tmp, ti = ++g_tmp; Buf rb; memset(&rb, 0, sizeof rb); emit_expr(c, recv, &rb); int is_line = !strcmp(name, "each_line") || !strcmp(name, "lines"); int is_byte = !strcmp(name, "each_byte") || !strcmp(name, "bytes") || !strcmp(name, "codepoints"); Scope *cs_ech = p0 ? comp_scope_of(c, id) : NULL; LocalVar *clv_ech = (p0 && cs_ech) ? scope_local(cs_ech, p0) : NULL; int p0_box_poly_ech = clv_ech && clv_ech->type == TY_POLY; buf_printf(b, "({ const char *_t%d = %s; ", ts, rb.p ? rb.p : ""); free(rb.p); /* Save outer variable before loop to restore it afterward */ int tsv_ech = 0; if (p0 && clv_ech) { tsv_ech = ++g_tmp; Buf sv_ech; memset(&sv_ech, 0, sizeof sv_ech); emit_ctype(c, clv_ech->type, &sv_ech); buf_printf(b, "%s _t%d = lv_%s; ", sv_ech.p ? sv_ech.p : "sp_RbVal", tsv_ech, p0); free(sv_ech.p); } else { /* TY_FLOAT */ /* round/ceil/floor/truncate(n>0) -> Float to n decimals; else Integer */ int ndig = 0; if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate")) && argc == 1) { const char *aty = nt_type(c->nt, argv[0]); if (aty && !strcmp(aty, "IntegerNode")) ndig = (int)nt_int(c->nt, argv[0], "value", 0); if (is_line) { int tl = ++g_tmp; /* chomp: true keyword arg uses the _chomp variant */ int eline_chomp = 0; if (argc == 1 && argv && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "KeywordHashNode")) { int cv = struct_kwarg_value(c, argv[0], "chomp"); eline_chomp = (cv >= 0 && nt_type(nt, cv) && !strcmp(nt_type(nt, cv), "TrueNode")); } const char *cfn = !strcmp(name, "floor") ? "floor" : !strcmp(name, "ceil") ? "ceil" : !strcmp(name, "truncate") ? "trunc" : "round"; if ((!strcmp(name, "floor") || !strcmp(name, "ceil") || !strcmp(name, "round") || !strcmp(name, "truncate"))) { if (ndig > 0) buf_printf(b, "({ double _f = pow(10, %d); %s((%s) * _f) / _f; })", ndig, cfn, r); else if (ndig < 0) /* round to a power of ten left of the decimal -> Integer */ buf_printf(b, "({ double _f = pow(10, %d); (mrb_int)(%s((%s) / _f) * _f); })", -ndig, cfn, r); else buf_printf(b, "((mrb_int)%s(%s))", cfn, r); buf_printf(b, "sp_StrArray *_t%d = %s(_t%d); for (mrb_int _t%d = 0; _t%d < sp_StrArray_length(_t%d); _t%d++) { ", tl, eline_chomp ? "sp_str_lines_chomp" : "sp_str_lines", ts, ti, ti, tl, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_str(sp_StrArray_get(_t%d, _t%d)); ", p0, tl, ti); else buf_printf(b, "lv_%s = sp_StrArray_get(_t%d, _t%d); ", p0, tl, ti); } else if (!strcmp(name, "to_i")) buf_printf(b, "((mrb_int)(%s))", r); else if (!strcmp(name, "to_f")) buf_printf(b, "(%s)", r); else if (!strcmp(name, "divmod") && argc == 1) { /* Float#divmod(n) -> [floor(x/n) (Integer), x - q*n (Float)] */ int tx = ++g_tmp, tn = ++g_tmp, tq = ++g_tmp, o = ++g_tmp; buf_printf(b, "({ mrb_float _t%d = (%s); mrb_float _t%d = ", tx, r, tn); emit_expr(c, argv[0], b); buf_printf(b, "; if (isnan(_t%d) || isnan(_t%d)) sp_raise_cls(\"FloatDomainError\", \"NaN\");" " if (_t%d == 0.0) sp_raise_cls(\"ZeroDivisionError\", \"divided by 0\");" " mrb_int _t%d = (mrb_int)floor(_t%d / _t%d); sp_PolyArray *_t%d = sp_PolyArray_new();" " sp_PolyArray_push(_t%d, sp_box_int(_t%d));" " sp_PolyArray_push(_t%d, sp_box_float(_t%d - (mrb_float)_t%d * _t%d)); _t%d; })", tx, tn, tn, tq, tx, tn, o, o, tq, o, tx, tq, tn, o); } else if (is_byte) { buf_printf(b, "for (mrb_int _t%d = 0; _t%d < (mrb_int)sp_str_byte_len(_t%d); _t%d++) { ", ti, ti, ts, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_int((unsigned char)_t%d[_t%d]); ", p0, ts, ti); else buf_printf(b, "lv_%s = (unsigned char)_t%d[_t%d]; ", p0, ts, ti); } else if (!strcmp(name, "to_s")) buf_printf(b, "sp_float_opt_to_s(%s)", r); else if (!strcmp(name, "inspect")) buf_printf(b, "sp_float_opt_inspect(%s)", r); else if (!strcmp(name, "abs")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "zero?")) buf_printf(b, "((%s) == 0.0)", r); else if (!strcmp(name, "nan?")) buf_printf(b, "(isnan(%s) != 0)", r); else if (!strcmp(name, "finite?")) buf_printf(b, "(isfinite(%s) != 0)", r); else if (!strcmp(name, "infinite?")) buf_printf(b, "(isinf(%s) ? ((%s) > 0 ? 1LL : -1LL) : SP_INT_NIL)", r, r); else if (!strcmp(name, "positive?")) buf_printf(b, "((%s) > 0)", r); else if (!strcmp(name, "negative?")) buf_printf(b, "((%s) < 0)", r); else if (!strcmp(name, "next_float")) buf_printf(b, "nextafter(%s, INFINITY)", r); else if (!strcmp(name, "prev_float")) buf_printf(b, "nextafter(%s, -INFINITY)", r); else if (!strcmp(name, "magnitude")) buf_printf(b, "((%s) < 0 ? -(%s) : (%s))", r, r, r); else if (!strcmp(name, "modulo") && argc == 1) { buf_printf(b, "fmod(%s, ", r); emit_expr(c, argv[0], b); buf_puts(b, ")"); } else if (!strcmp(name, "coerce") && argc == 1) { TyKind a0 = comp_ntype(c, argv[0]); int ta = ++g_tmp, o = ++g_tmp; if (a0 == TY_INT) { buf_printf(b, "({ mrb_int _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, (mrb_float)_t%d);" " sp_FloatArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); } else { buf_printf(b, "({ mrb_float _t%d = ", ta); emit_expr(c, argv[0], b); buf_printf(b, "; sp_FloatArray *_t%d = sp_FloatArray_new();" " sp_FloatArray_push(_t%d, _t%d);" " sp_FloatArray_push(_t%d, (%s)); _t%d; })", o, o, ta, o, r, o); } } else { buf_printf(b, "for (mrb_int _t%d = 0; _t%d < sp_str_length(_t%d); _t%d++) { ", ti, ti, ts, ti); if (p0) { if (p0_box_poly_ech) buf_printf(b, "lv_%s = sp_box_str(sp_str_char_at_or_nil(_t%d, _t%d)); ", p0, ts, ti); else buf_printf(b, "lv_%s = sp_str_char_at_or_nil(_t%d, _t%d); ", p0, ts, ti); } else handled = 0; } free(rs.p); if (handled) return; int sv = g_nren; g_nren = 0; emit_stmts(c, body, b, 0); g_nren = sv; if (p0 && tsv_ech > 0) buf_printf(b, " lv_%s = _t%d;", p0, tsv_ech); buf_printf(b, " } _t%d; })", ts); return; } if (emit_scalar_call(c, id, b)) return; /* bigint methods */ if (recv >= 0 && rt == TY_BIGINT) { Buf rs; memset(&rs, 0, sizeof rs); emit_expr(c, recv, &rs);