Commit 6e4ea558

6e4ea5584bd1Merged

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

Description

fix(analyze,codegen): resolve bare const via @cls_parents chain (#668)

class Child < Parent; def m; CONST end end reading a constant defined on Parent previously warned "uninitialized constant CONST" because resolve_const_read_name walked only the lexical-scope chain and the include chain. CRuby's lookup additionally walks the inheritance chain after lexical scope, which is what this patch adds.

Both spinel_analyze and spinel_codegen carry their own copy of the lookup helpers, so the fix has to be mirrored in both:

  • New resolve_const_via_parent_chain(class_idx, name, depth) walks @cls_parents from the current class. At each ancestor we try the <Parent>_<name> namespace, fall back to that ancestor's own include chain (so Parent include Mixin; CONST in Mixin is visible from Child#m), then recurse to the grand-parent. Caps at depth 16 to bail on pathological inheritance loops.
  • resolve_const_read_name calls the new walker after the existing lexical + include walks, so we only fall through to the inheritance chain when neither nearer scope carries the name. This preserves existing behaviour for shadowed names where a nearer lexical-scope constant should win.

Closes #668.

Co-Authored-By: Claude Opus 4.7 [email protected]

Details

Commit
6e4ea5584bd1
Parent
4f42827bc25c

spinel_analyze.rbmodifiedView file

@@ -933,10 +933,44 @@
933933 if found_inc != ""
934934 return found_inc
935935 end
936+ found_par = resolve_const_via_parent_chain(@current_class_idx, name)
937+ if found_par != ""
938+ return found_par
939+ end
936940 end
937941 name
938942 end
939943
944+ # Walk @cls_parents (superclass chain) from `class_idx`, trying each
945+ # ancestor's namespace plus each ancestor's includes. Mirrors CRuby's
946+ # constant lookup which walks the class hierarchy after lexical scope.
947+ # Caps depth at 16 to bail on pathological chains.
948+ def resolve_const_via_parent_chain(class_idx, name, depth = 16)
949+ if depth <= 0
950+ return ""
951+ end
952+ if class_idx < 0 || class_idx >= @cls_parents.length
953+ return ""
954+ end
955+ pname = @cls_parents[class_idx]
956+ if pname == ""
957+ return ""
958+ end
959+ cand = pname + "_" + name
960+ if const_namespace_exists(cand) == 1
961+ return cand
962+ end
963+ pi = find_class_idx(pname)
964+ if pi >= 0
965+ sub_inc = resolve_const_via_include_chain(pi, name, depth - 1)
966+ if sub_inc != ""
967+ return sub_inc
968+ end
969+ return resolve_const_via_parent_chain(pi, name, depth - 1)
970+ end
971+ ""
972+ end
973+
940974 # Recursively walk @cls_includes from `class_idx`, trying each
941975 # included module's namespace for a constant named `name`. Caps at
942976 # depth 16 so a pathological include cycle bails instead of looping.