Commit f0499e53

f0499e539cbcMerged

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

Description

Support alias / alias_method for instance methods and attrs

Register alias new old (AliasMethodNode) and alias_method :new, :old into a per-class alias table, chain-aware. Method/reader/writer lookups resolve the alias to the underlying name, and instance-method dispatch emits the resolved method's real C name (so an alias of an inherited method calls the ancestor implementation).

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

Details

Commit
f0499e539cbc
Parent
dce5a18a51a3

src/analyze.cmodifiedView file

@@ -549,6 +549,40 @@
549549 }
550550 }
551551
552+/* Collect `alias new old` (AliasMethodNode) and `alias_method :new, :old`
553+ (CallNode) statements in class bodies into the class alias table. */
554+static void register_aliases(Compiler *c) {
555+ const NodeTable *nt = c->nt;
556+ for (int ci = 0; ci < c->nclasses; ci++) {
557+ ClassInfo *cls = &c->classes[ci];
558+ int body = nt_ref(nt, cls->def_node, "body");
559+ int n = 0;
560+ const int *stmts = body >= 0 ? nt_arr(nt, body, "body", &n) : NULL;
561+ for (int k = 0; k < n; k++) {
562+ int s = stmts[k];
563+ const char *sty = nt_type(nt, s);
564+ if (!sty) continue;
565+ if (!strcmp(sty, "AliasMethodNode")) {
566+ int nn = nt_ref(nt, s, "new_name");
567+ int on = nt_ref(nt, s, "old_name");
568+ const char *nw = nn >= 0 ? nt_str(nt, nn, "value") : NULL;
569+ const char *od = on >= 0 ? nt_str(nt, on, "value") : NULL;
570+ comp_add_alias(cls, nw, od);
571+ }
572+ else if (!strcmp(sty, "CallNode")) {
573+ const char *nm = nt_str(nt, s, "name");
574+ if (!nm || strcmp(nm, "alias_method")) continue;
575+ int args = nt_ref(nt, s, "arguments");
576+ int an = 0;
577+ const int *argv = args >= 0 ? nt_arr(nt, args, "arguments", &an) : NULL;
578+ if (an >= 2 && nt_type(nt, argv[0]) && !strcmp(nt_type(nt, argv[0]), "SymbolNode") &&
579+ nt_type(nt, argv[1]) && !strcmp(nt_type(nt, argv[1]), "SymbolNode"))
580+ comp_add_alias(cls, nt_str(nt, argv[0], "value"), nt_str(nt, argv[1], "value"));
581+ }
582+ }
583+ }
584+}
585+
552586 static int is_c_ident(const char *s) {
553587 if (!s || !*s) return 0;
554588 for (const char *p = s; *p; p++)
@@ -931,7 +965,7 @@
931965 /* obj.method -> instance method params */
932966 TyKind rt = infer_type(c, recv);
933967 if (ty_is_object(rt))
934- changed |= bind_call_params(c, id, comp_method_in_class(c, ty_object_class(rt), name));
968+ changed |= bind_call_params(c, id, comp_method_in_chain(c, ty_object_class(rt), name, NULL));
935969 }
936970 return changed;
937971 }
@@ -1092,6 +1126,7 @@
10921126 walk_scope(c, c->nt->root_id, 0, -1);
10931127 register_locals(c);
10941128 register_attrs(c);
1129+ register_aliases(c);
10951130 register_globals_consts(c);
10961131
10971132 /* rescue variables (`rescue => e`) are typed as exception objects */