Commit b0ba3d43

b0ba3d43fddbMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

fix(codegen): detect circular inheritance instead of hanging

class A < B; class B < A; end; end (and the trivial self form class A < A) hung spinel_codegen at 100% CPU. Every parent-walking helper — cls_find_method, cls_method_return, cls_ivar_type, is_class_or_ancestor — recurses through @cls_parents, and a cycle makes that recursion run forever instead of erroring out the way CRuby does (NameError at parse).

Add a detect_circular_inheritance pass right after class collection. For each class, walk the parent chain via @cls_parents / find_class_idx, and bail with Error: circular inheritance ... if the same name reappears. An unresolved parent stops the walk cleanly (it's a separate diagnostic handled elsewhere).

Closes #106

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

Details

Commit
b0ba3d43fddb
Parent
305e2f6539f2

spinel_codegen.rbmodifiedView file

@@ -3988,6 +3988,34 @@
39883988 end
39893989
39903990 # ---- Collection pass ----
3991+ # Walk every class's parent chain. A cycle anywhere on the chain is
3992+ # a fatal program error: bail with a clear message instead of letting
3993+ # the recursive helpers loop forever. Self-inheritance (`class A < A`)
3994+ # is detected as the trivial 1-step cycle.
3995+ def detect_circular_inheritance
3996+ i = 0
3997+ while i < @cls_names.length
3998+ visited = "".split(",")
3999+ visited.push(@cls_names[i])
4000+ cur = @cls_parents[i]
4001+ while cur != ""
4002+ if not_in(cur, visited) == 0
4003+ $stderr.puts "Error: circular inheritance involving '" + @cls_names[i] + "' via '" + cur + "'"
4004+ exit(1)
4005+ end
4006+ visited.push(cur)
4007+ pi = find_class_idx(cur)
4008+ if pi < 0
4009+ # Unresolved parent — stop walking; this is a separate issue
4010+ # (the parent lookup falls through cleanly elsewhere).
4011+ break
4012+ end
4013+ cur = @cls_parents[pi]
4014+ end
4015+ i = i + 1
4016+ end
4017+ end
4018+
39914019 def collect_all
39924020 root = @root_id
39934021 if @nd_type[root] != "ProgramNode"
@@ -4008,6 +4036,12 @@
40084036 collect_class(sid)
40094037 end
40104038 }
4039+ # Pass 1.5: reject circular inheritance (`class A < B; class B < A`).
4040+ # Every parent-walking helper (cls_find_method, cls_ivar_type,
4041+ # is_class_or_ancestor, …) recurses through @cls_parents; a cycle
4042+ # would loop forever and hang the codegen instead of erroring out
4043+ # like CRuby. Issue #106.
4044+ detect_circular_inheritance
40114045
40124046 # Pass 2: top-level methods, constants, define_method
40134047 stmts.each { |sid|