Commit 4258ef5b

4258ef5b0248Merged

Yasuhiro Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified

Description

codegen: implement find-pattern (in [*head, x, *tail]) matching and binding

The FindPatternNode was parsed but never matched: emit_pm_cond had no case for it (so the arm always matched) and no bindings were emitted (so the splat captures stayed nil). Scan for the first window of consecutive elements matching the requireds, record its start, and bind the leading splat, required targets, and trailing splat from that position. Type the bindings in analyze (the two splats -> arrays, requireds -> element).

Co-Authored-By: Claude [email protected]

Details

Commit
4258ef5b0248
Parent
dc27e05b7d53

src/analyze_pass.cmodifiedView file

@@ -778,6 +778,37 @@
778778 /* in [first, *rest] or in Array(head, *tail) */
779779 array_pat = pat; array_scrutinee = scrutinee_t;
780780 }
781+ else if (!strcmp(pty, "FindPatternNode")) {
782+ /* in [*head, a, b, *tail] -- the two splats bind to arrays of the
783+ scrutinee's element type; required LV targets bind to an element. */
784+ TyKind arr_t = ty_is_array(scrutinee_t) ? scrutinee_t : TY_POLY_ARRAY;
785+ TyKind elem_t = ty_is_array(scrutinee_t) ? ty_array_elem(scrutinee_t) : TY_POLY;
786+ int sides[2] = { nt_ref(nt, pat, "left"), nt_ref(nt, pat, "right") };
787+ for (int sidx = 0; sidx < 2; sidx++) {
788+ int sp = sides[sidx];
789+ if (sp < 0 || !nt_type(nt, sp) || strcmp(nt_type(nt, sp), "SplatNode")) continue;
790+ int inner = nt_ref(nt, sp, "expression");
791+ if (inner < 0 || !nt_type(nt, inner) ||
792+ strcmp(nt_type(nt, inner), "LocalVariableTargetNode")) continue;
793+ const char *snm = nt_str(nt, inner, "name");
794+ LocalVar *lv = snm ? scope_local(ms, snm) : NULL;
795+ if (!lv || lv->is_param || lv->is_block_param) continue;
796+ TyKind mg = ty_unify(lv->type, arr_t);
797+ if (mg != lv->type) { lv->type = mg; changed = 1; }
798+ }
799+ int rn = 0;
800+ const int *reqs = nt_arr(nt, pat, "requireds", &rn);
801+ for (int k = 0; k < rn; k++) {
802+ const char *lty2 = nt_type(nt, reqs[k]);
803+ if (!lty2 || strcmp(lty2, "LocalVariableTargetNode")) continue;
804+ const char *lnm = nt_str(nt, reqs[k], "name");
805+ LocalVar *lv = lnm ? scope_local(ms, lnm) : NULL;
806+ if (!lv || lv->is_param || lv->is_block_param) continue;
807+ TyKind et = (elem_t != TY_UNKNOWN) ? elem_t : TY_POLY;
808+ TyKind mg = ty_unify(lv->type, et);
809+ if (mg != lv->type) { lv->type = mg; changed = 1; }
810+ }
811+ }
781812 /* Bind simple LV target to scrutinee type */
782813 if (bind_lv_node >= 0 && scrutinee_t != TY_UNKNOWN) {
783814 const char *lnm = nt_str(nt, bind_lv_node, "name");