Commit 3c2129b4
3c2129b4a6ecMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 2 files · ~2 modified
Description
analyze/codegen: bare new in cmethod, self.class.cmeth dispatch
Three related additions for class-method patterns:
-
infer_call: bare
newinside a class method returns TY_OBJ of self's class (was TY_UNKNOWN, causing downstream unknown-type errors for the constructed instance's method calls). -
codegen: bare
newinside a class method emitssp_<ClassName>_new(...)by looking up self's class_id from the enclosing scope. -
analyze + codegen:
obj.class.cmeth(...)pattern (e.g.self.class.label) now:- infers the return type by unifying the class method's return type across all descendant implementations
- emits a cls_id switch that dispatches to the correct subclass class method at runtime
Fixes scan_new_calls_class_scope and self_class_subclass_dispatch tests (bundled in bundle_classd_36).
Co-Authored-By: Claude Sonnet 4.6 [email protected]
Details
- Commit
- 3c2129b4a6ec
- Parent
- f7821ff196b1
src/analyze.cmodifiedView file
@@ -537,6 +537,28 @@
537537
if (mi >= 0) return c->scopes[mi].ret;538538
}539539
}540+
/* obj.class.cmeth(...) -> unify class method return types across hierarchy */541+
if (rty && !strcmp(rty, "CallNode") &&542+
nt_str(nt, recv, "name") && !strcmp(nt_str(nt, recv, "name"), "class")) {543+
int robj = nt_ref(nt, recv, "receiver");544+
TyKind rrt = robj >= 0 ? infer_type(c, robj) : TY_UNKNOWN;545+
if (ty_is_object(rrt)) {546+
int cid = ty_object_class(rrt);547+
int mi = comp_cmethod_in_chain(c, cid, name, NULL);548+
if (mi >= 0) {549+
TyKind r = (TyKind)c->scopes[mi].ret;550+
for (int k = 0; k < c->nclasses; k++) {551+
int _desc = 0;552+
for (int _p = c->classes[k].parent; _p >= 0; _p = c->classes[_p].parent)553+
if (_p == cid) { _desc = 1; break; }554+
if (!_desc) continue;555+
int kmi = comp_cmethod_in_class(c, k, name);556+
if (kmi >= 0) r = ty_unify(r, (TyKind)c->scopes[kmi].ret);557+
}558+
return r;559+
}560+
}561+
}540562
}541563
542564
/* Struct instance methods */@@ -629,6 +651,9 @@
629651
int iv = comp_ivar_index(&c->classes[self->class_id], ivn);630652
if (iv >= 0) return c->classes[self->class_id].ivar_types[iv];631653
}654+
/* bare `new` inside a class method returns an instance of self's class */655+
if (self->is_cmethod && !strcmp(name, "new"))656+
return ty_object(self->class_id);632657
int mi = comp_method_in_chain(c, self->class_id, name, NULL);633658
if (mi < 0 && self->is_cmethod)634659
mi = comp_cmethod_in_chain(c, self->class_id, name, NULL);src/codegen.cmodifiedView file
Loading diff…