Commit 970a80a9

970a80a9fc3dMerged

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

Description

analyze,codegen: Struct#[] member access + block-defined methods

Two gaps in Struct support:

  1. p[:name] / p["name"] / p[0] weren't dispatched on a struct instance (emitted 0 / raised undefined-method). Resolve the index against the class's attr_reader list (members in declaration order) and read the matching ivar. Gated on the class not defining its own [] so a user bracket method still wins. analyze types the result as the member's ivar type.

  2. Struct.new(:x, :y) do def to_s; ...; end end dropped the block's method definitions, so pt.to_s raised. collect_struct_class now walks the block body and registers each DefNode as an instance method, same as a normal class body.

Fixes #994

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

Details

Commit
970a80a9fc3d
Parent
42215659e109

spinel_analyze.rbmodifiedView file

@@ -6026,6 +6026,36 @@
60266026 if mr != "" && mr != "int"
60276027 return mr
60286028 end
6029+ # Struct#[] member access: when the class has no user `[]` but
6030+ # the index names/positions an attr_reader field, the result is
6031+ # that field's ivar type.
6032+ if cls_find_method(ci, "[]") < 0
6033+ args_id_st = @nd_arguments[nid]
6034+ if args_id_st >= 0
6035+ a_st = get_args(args_id_st)
6036+ if a_st.length >= 1
6037+ readers_st = @cls_attr_readers[ci].split(";", -1)
6038+ fld_st = ""
6039+ if @nd_type[a_st[0]] == "SymbolNode" || @nd_type[a_st[0]] == "StringNode"
6040+ fld_st = @nd_content[a_st[0]]
6041+ elsif @nd_type[a_st[0]] == "IntegerNode"
6042+ idx_st = @nd_value[a_st[0]].to_i
6043+ if idx_st < 0
6044+ idx_st = idx_st + readers_st.length
6045+ end
6046+ if idx_st >= 0 && idx_st < readers_st.length
6047+ fld_st = readers_st[idx_st]
6048+ end
6049+ end
6050+ if fld_st != ""
6051+ ft_st = cls_ivar_type(ci, "@" + fld_st)
6052+ if ft_st != ""
6053+ return ft_st
6054+ end
6055+ end
6056+ end
6057+ end
6058+ end
60296059 end
60306060 end
60316061 end
@@ -12754,6 +12784,27 @@
1275412784 bodies[0] = "-2"
1275512785 @cls_meth_bodies[ci] = bodies.join(";")
1275612786 end
12787+
12788+ # `Struct.new(:x, :y) do def to_s; ...; end end` — the block body
12789+ # adds instance methods to the struct class. Register each DefNode
12790+ # the same way a normal class body does so `pt.to_s` dispatches.
12791+ blk_st = @nd_block[call_nid]
12792+ if blk_st >= 0
12793+ bbody_st = @nd_body[blk_st]
12794+ if bbody_st >= 0
12795+ saved_ci_st = @current_class_idx
12796+ @current_class_idx = ci
12797+ blk_stmts_st = get_stmts(bbody_st)
12798+ bsi_st = 0
12799+ while bsi_st < blk_stmts_st.length
12800+ if @nd_type[blk_stmts_st[bsi_st]] == "DefNode"
12801+ collect_class_method(ci, blk_stmts_st[bsi_st])
12802+ end
12803+ bsi_st = bsi_st + 1
12804+ end
12805+ @current_class_idx = saved_ci_st
12806+ end
12807+ end
1275712808 end
1275812809
1275912810 # ---- Yield detection ----