Commit a74fc490

a74fc490802eMerged

Ryan Seys <[email protected]> · 5 months ago · 4 files · +2 added · ~2 modified

Description

analyze,codegen: support define_singleton_method with a literal name

define_singleton_method(:name) { ... } was unsupported. Extend the define_method registration to handle it: register the block body as a class-method scope on the resolved target -- a class-constant or namespaced-class (M::C) receiver, self in a class body, or no receiver (the enclosing class). The call itself emits no runtime code, like define_method.

A singleton method on an arbitrary instance has no compile-time class and no per-instance method storage, so it is left unregistered. The codegen no-op gate mirrors exactly the receivers analyze registers, so an instance receiver is not silently dropped -- it falls through to the unresolved-call reject at the define site.

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

Details

Commit
a74fc490802e
Parent
913a83318df6

src/analyze_scope.cmodifiedView file

@@ -653,7 +653,24 @@
653653 function (class_id stays -1), matching `def`. */
654654 const char *dm_cn = nt_str(c->nt, id, "name");
655655 int dm_recv = nt_ref(c->nt, id, "receiver");
656- if (dm_cn && !strcmp(dm_cn, "define_method") && dm_recv < 0) {
656+ int dm_is_dm = dm_cn && !strcmp(dm_cn, "define_method") && dm_recv < 0;
657+ int dm_is_dsm = dm_cn && !strcmp(dm_cn, "define_singleton_method");
658+ /* define_singleton_method registers a class method on the resolved target:
659+ a class constant receiver, `self` in a class body, or no receiver (the
660+ enclosing class). An arbitrary-instance singleton has no compile-time
661+ class, so it is not registered (the later call rejects). */
662+ int dm_cmethod = 0, dm_cls = class_id, dm_ok = dm_is_dm;
663+ if (dm_is_dsm) {
664+ dm_cmethod = 1;
665+ const char *dsm_rty = dm_recv >= 0 ? nt_type(c->nt, dm_recv) : NULL;
666+ if (dm_recv < 0) dm_cls = class_id;
667+ else if (dsm_rty && (!strcmp(dsm_rty, "ConstantReadNode") || !strcmp(dsm_rty, "ConstantPathNode")))
668+ dm_cls = comp_class_index(c, nt_str(c->nt, dm_recv, "name"));
669+ else if (dsm_rty && !strcmp(dsm_rty, "SelfNode")) dm_cls = class_id;
670+ else dm_cls = -1;
671+ dm_ok = dm_cls >= 0;
672+ }
673+ if (dm_ok) {
657674 int dm_args = nt_ref(c->nt, id, "arguments");
658675 int dm_na = 0;
659676 const int *dm_argv = dm_args >= 0 ? nt_arr(c->nt, dm_args, "arguments", &dm_na) : NULL;
@@ -669,7 +686,8 @@
669686 Scope *dm_s = comp_scope_new(c, dm_mname, id);
670687 int dm_new_idx = c->nscopes - 1;
671688 dm_s->body = nt_ref(c->nt, dm_blk, "body");
672- dm_s->class_id = class_id;
689+ dm_s->class_id = dm_cls;
690+ dm_s->is_cmethod = dm_cmethod;
673691 /* the block's params are the defined method's params (e.g. the
674692 `&:to_s`-rewritten `{ |_spx| _spx.to_s }`'s _spx). */
675693 int dm_pn = nt_ref(c->nt, dm_blk, "parameters");