Commit 66e9388d

66e9388d2e97Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · +1 added · ~1 modified

Description

fix: merge class reopens into existing class entry, close #5

Spinel was unconditionally pushing a new entry to @cls_names for every ClassNode in the AST, so reopening a class produced duplicate sp_X_s struct definitions and sp_X_new constructors that the C compiler rejected as redefinitions.

When a class name already exists in @cls_names, reuse that index and collect the new body's methods, attrs, includes, and ivars into the existing entry. The append_cls_meth and collect_ivars helpers were already idempotent on existing classes, so only the registration step needed to branch.

Includes a regression test (test/bm_reopen_class.rb) covering empty reopen and reopen that adds attr_accessor, method, and ivar usage that spans the two bodies.

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

Details

Commit
66e9388d2e97
Parent
c636e1d6ace1

spinel_codegen.rbmodifiedView file

@@ -3309,6 +3309,53 @@
33093309 return
33103310 end
33113311
3312+ # Class reopening: if the class was already registered (in an
3313+ # earlier `class Foo ... end` block), reuse the existing entry
3314+ # so methods and attrs from this body get appended rather than
3315+ # producing a duplicate C struct/constructor.
3316+ existing_ci = find_class_idx(cname)
3317+ if existing_ci >= 0
3318+ ci = existing_ci
3319+ body = @nd_body[nid]
3320+ if body < 0
3321+ return
3322+ end
3323+ body_stmts = get_stmts(body)
3324+ body_stmts.each { |sid|
3325+ if @nd_type[sid] == "DefNode"
3326+ collect_class_method(ci, sid)
3327+ end
3328+ if @nd_type[sid] == "CallNode"
3329+ cn = @nd_name[sid]
3330+ if cn != "include"
3331+ if cn != "private"
3332+ collect_attr_call(ci, sid)
3333+ end
3334+ end
3335+ end
3336+ }
3337+ body_stmts.each { |sid|
3338+ if @nd_type[sid] == "CallNode"
3339+ if @nd_name[sid] == "include"
3340+ inc_args = @nd_arguments[sid]
3341+ if inc_args >= 0
3342+ inc_ids = get_args(inc_args)
3343+ ik = 0
3344+ while ik < inc_ids.length
3345+ if @nd_type[inc_ids[ik]] == "ConstantReadNode"
3346+ mod_name = @nd_name[inc_ids[ik]]
3347+ collect_module_methods_into_class(ci, mod_name)
3348+ end
3349+ ik = ik + 1
3350+ end
3351+ end
3352+ end
3353+ end
3354+ }
3355+ collect_ivars(ci)
3356+ return
3357+ end
3358+
33123359 parent = ""
33133360 sp = @nd_superclass[nid]
33143361 struct_fields = "".split(",")