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_parentsfrom the current class. At each ancestor we try the<Parent>_<name>namespace, fall back to that ancestor's own include chain (soParent include Mixin; CONST in Mixinis visible fromChild#m), then recurse to the grand-parent. Caps at depth 16 to bail on pathological inheritance loops. resolve_const_read_namecalls 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_inc935935
end936+
found_par = resolve_const_via_parent_chain(@current_class_idx, name)937+
if found_par != ""938+
return found_par939+
end936940
end937941
name938942
end939943
944+
# Walk @cls_parents (superclass chain) from `class_idx`, trying each945+
# ancestor's namespace plus each ancestor's includes. Mirrors CRuby's946+
# 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 <= 0950+
return ""951+
end952+
if class_idx < 0 || class_idx >= @cls_parents.length953+
return ""954+
end955+
pname = @cls_parents[class_idx]956+
if pname == ""957+
return ""958+
end959+
cand = pname + "_" + name960+
if const_namespace_exists(cand) == 1961+
return cand962+
end963+
pi = find_class_idx(pname)964+
if pi >= 0965+
sub_inc = resolve_const_via_include_chain(pi, name, depth - 1)966+
if sub_inc != ""967+
return sub_inc968+
end969+
return resolve_const_via_parent_chain(pi, name, depth - 1)970+
end971+
""972+
end973+
940974
# Recursively walk @cls_includes from `class_idx`, trying each941975
# included module's namespace for a constant named `name`. Caps at942976
# depth 16 so a pathological include cycle bails instead of looping.spinel_codegen.rbmodifiedView file
Loading diff…
test/const_inheritance_lookup.rbaddedView file
Loading diff…