Commit b832a313

b832a313791fMerged

Chris Hasiński <[email protected]> · 6 months ago · 2 files · ~2 modified

Description

feat(codegen): instance_eval { } accepts method-param receivers

Second of three planned follow-ups widening PR #15's recv.instance_eval gate (after PR #158 for ivars; method-return receivers come last).

Lifts def configure(app); app.instance_eval { } end so that calling cfg.configure(routes) from top level hoists the block with self rebound to the passed-in routes. Also picks up method-local copies whose RHS is statically classifiable (routes = Routes.new then routes.instance_eval { }).

Two pieces:

  1. propagate_recv_method_arg_types_for_ieval — a narrow pre-pass that widens class-method ptypes through obj-typed receivers. Top-level locals are declared in scope (via scan_locals_first_type) so infer_type(recv) resolves a binding like w = Wire.new to obj_Wire when the walker reaches w.configure(routes). Without the scope, find_var_type returns "" and Wire#configure's routes ptype stays "int".

    This is a surgical fork of scan_new_calls' receiver-method branch. Earlier drafts of this PR called scan_new_calls itself with the scope wrap, but doing so before compile()'s infer_main_call_types reorders inputs to detect_poly_params and demonstrably regressed test/poly_dispatch_builtin_all.rb (lenof's poly param drops to int_array when the early run primes ptypes ahead of the iterative loop). Keeping the constructor and top-level-method branches inside their existing call sites preserves master's poly-detection order.

  2. ieval_walk_class_methods now push_scope + declares each method's params (with the widened ptypes) and body locals (via scan_locals_first_type) before walking the body. ieval_rewrite_call's LocalVariableReadNode branch falls back to find_var_type when the v1 local_class map misses, so a method param or scan_locals-typed local resolves through the scope chain.

Diff evidence on the codegen self-compile (build/codegen.ast): exactly one method ptype changes — Compiler#read_text_ast(data) widens from int -> string. That's correct: the call site is compiler.read_text_ast(data) where data = File.read(ast_file), and the param is genuinely a string. Bootstrap (gen2.c == gen3.c) closes both before and after.

Verified:

  • make bootstrap clean.
  • make test: 229 pass, 0 fail, 0 error.
  • make bench: 56 pass, 0 fail, 0 skip.
  • test/bm_instance_eval.rb gains three sections: param receiver in a void method (§10), param receiver in tail position (§11), and a method-local copy of a class instance (§12).

Disjoint with PR #124's instance_eval(&b) trampoline (different AST shape — receiverless instance_eval inside def m(&b)).

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

Details

Commit
b832a313791f
Parent
4b0620832c21

spinel_codegen.rbmodifiedView file

@@ -4453,6 +4453,12 @@
44534453
44544454 def rewrite_instance_eval_calls
44554455 @ieval_counter = 0
4456+ # Widen class-method ptypes through obj-typed receivers before the
4457+ # walk so a method-param receiver (e.g. `def configure(app);
4458+ # app.instance_eval { } end` invoked as `cfg.configure(routes)`)
4459+ # has `app` typed as obj_<C>. Surgical fork — see the helper for
4460+ # why we don't just call scan_new_calls here.
4461+ propagate_recv_method_arg_types_for_ieval
44564462 local_class = {}
44574463 # Walk the AST recursively from the root, respecting scope boundaries.
44584464 # `local_class` maps `name -> class_idx` for the current scope only.
@@ -4475,17 +4481,60 @@
44754481 # `cls_ivar_type`. Class methods (singleton-side) are intentionally
44764482 # excluded: they don't see the instance's @ivars, and `self` rebinding
44774483 # against a class object would be a different (singleton-class) lift.
4484+ #
4485+ # Per-method scope: declare each method's params (with the ptypes
4486+ # widened by infer_param_types_from_callsites at Pass 2.55) and the
4487+ # body locals from scan_locals_first_type, so a LocalVariableReadNode
4488+ # receiver inside the body can resolve its class via find_var_type.
4489+ # That covers `def configure(app); app.instance_eval { } end` and
4490+ # also method-local copies whose RHS is statically classifiable
4491+ # (e.g., `routes = Routes.new`). Method returns whose call type
4492+ # depends on infer_all_returns having run are still out of reach
4493+ # at this Pass 2.6 timing — that's the next follow-up.
44784494 def ieval_walk_class_methods
44794495 ci = 0
44804496 while ci < @cls_names.length
44814497 @current_class_idx = ci
44824498 bodies = @cls_meth_bodies[ci].split(";")
4499+ all_params = @cls_meth_params[ci].split("|")
4500+ all_ptypes = @cls_meth_ptypes[ci].split("|")
44834501 bj = 0
44844502 while bj < bodies.length
44854503 bid = bodies[bj].to_i
44864504 if bid >= 0
4505+ push_scope
4506+ pnames = "".split(",")
4507+ ptypes = "".split(",")
4508+ if bj < all_params.length
4509+ pnames = all_params[bj].split(",")
4510+ end
4511+ if bj < all_ptypes.length
4512+ ptypes = all_ptypes[bj].split(",")
4513+ end
4514+ k = 0
4515+ while k < pnames.length
4516+ pt = "int"
4517+ if k < ptypes.length
4518+ pt = ptypes[k]
4519+ end
4520+ declare_var(pnames[k], pt)
4521+ k = k + 1
4522+ end
4523+ # Body locals: scan_locals_first_type matches what
4524+ # infer_all_returns does in its class-methods preamble
4525+ # (Pass 3). Pulls in `routes = Routes.new` with type
4526+ # obj_Routes when the RHS is statically classifiable.
4527+ lnames = "".split(",")
4528+ ltypes = "".split(",")
4529+ scan_locals_first_type(bid, lnames, ltypes, pnames)
4530+ lk = 0
4531+ while lk < lnames.length
4532+ declare_var(lnames[lk], ltypes[lk])
4533+ lk = lk + 1
4534+ end
44874535 empty_locals = {}
44884536 ieval_walk(bid, empty_locals)
4537+ pop_scope
44894538 end
44904539 bj = bj + 1
44914540 end
@@ -4647,6 +4696,18 @@
46474696 vname = @nd_name[recv]
46484697 if local_class.key?(vname)
46494698 ci = local_class[vname]
4699+ else
4700+ # Inside a class instance method, the v1 top-level local_class
4701+ # map is intentionally empty. Fall back to find_var_type so a
4702+ # method param (or scan_locals-typed local) resolves through
4703+ # the scope chain that ieval_walk_class_methods sets up. The
4704+ # is_obj_type / base_type strip is the same shape used in the
4705+ # ivar branch and at every other obj_-prefix site in this file.
4706+ vt = find_var_type(vname)
4707+ bt = base_type(vt)
4708+ if is_obj_type(bt) == 1
4709+ ci = find_class_idx(bt[4, bt.length - 4])
4710+ end
46504711 end
46514712 elsif @nd_type[recv] == "InstanceVariableReadNode"
46524713 # `@ivar.instance_eval { }` inside a class method. ieval_walk_class_methods
@@ -6258,6 +6319,133 @@
62586319 scan_new_calls(@root_id)
62596320 end
62606321
6322+ # Narrow pre-pass for `rewrite_instance_eval_calls`: walk top-level
6323+ # CallNodes shaped `recv.method(args)` where recv resolves to an
6324+ # obj_<C> via top-level scope, and let scan_new_calls' receiver-method
6325+ # branch widen the class method's ptypes. Without this, a method-param
6326+ # receiver inside `def configure(app); app.instance_eval { } end`
6327+ # has `app` ptype stuck at "int" at Pass 2.6 time — the existing
6328+ # `infer_main_call_types` does the same scope-wrap but only runs in
6329+ # `compile()` after `collect_all` returns.
6330+ #
6331+ # Why not reuse `infer_main_call_types`: that pass also runs the
6332+ # top-level-method branch and the constructor branch, both of which
6333+ # detect_poly_params later refines via different rules. Running them
6334+ # twice (once at Pass 2.55, once in compile()) re-orders the inputs
6335+ # detect_poly_params sees and demonstrably regresses
6336+ # `test/poly_dispatch_builtin_all.rb` (lenof's poly param drops to
6337+ # int_array when the early run primes ptypes ahead of the iterative
6338+ # loop). This pre-pass scans the same AST but skips both other
6339+ # branches; it only widens class-method ptypes through obj-typed
6340+ # receivers — the exact piece rewrite_instance_eval_calls needs.
6341+ def propagate_recv_method_arg_types_for_ieval
6342+ push_scope
6343+ if @nd_type[@root_id] == "ProgramNode"
6344+ tl_body = @nd_body[@root_id]
6345+ if tl_body >= 0
6346+ empty_params = "".split(",")
6347+ tl_lnames = "".split(",")
6348+ tl_ltypes = "".split(",")
6349+ scan_locals_first_type(tl_body, tl_lnames, tl_ltypes, empty_params)
6350+ ti = 0
6351+ while ti < tl_lnames.length
6352+ declare_var(tl_lnames[ti], tl_ltypes[ti])
6353+ ti = ti + 1
6354+ end
6355+ end
6356+ end
6357+ walk_recv_method_calls(@root_id)
6358+ pop_scope
6359+ end
6360+
6361+ # Surgical fork of scan_new_calls: only the `obj.method(args)` branch,
6362+ # only when `obj`'s static type is obj_<C>. Mirrors the cls_meth_ptypes
6363+ # widening at lines ~6603-6615 of scan_new_calls (the same int->concrete
6364+ # promotion gate) and falls through to recursion. Other branches of
6365+ # scan_new_calls (constructor and top-level method) are deliberately
6366+ # absent — running them earlier than master's compile() pipeline
6367+ # interacts badly with detect_poly_params (see commentary above).
6368+ def walk_recv_method_calls(nid)
6369+ if nid < 0
6370+ return
6371+ end
6372+ if @nd_type[nid] == "CallNode"
6373+ mname = @nd_name[nid]
6374+ recv = @nd_receiver[nid]
6375+ if recv >= 0
6376+ rt = infer_type(recv)
6377+ if is_obj_type(rt) == 1
6378+ cname = rt[4, rt.length - 4]
6379+ ci = find_class_idx(cname)
6380+ if ci >= 0
6381+ owner_ci = ci
6382+ midx = cls_find_method_direct(ci, mname)
6383+ if midx < 0
6384+ owner = find_method_owner(ci, mname)
6385+ if owner != "" && owner != cname
6386+ owner_ci = find_class_idx(owner)
6387+ if owner_ci >= 0
6388+ midx = cls_find_method_direct(owner_ci, mname)
6389+ end
6390+ end
6391+ end
6392+ if midx >= 0
6393+ args_id = @nd_arguments[nid]
6394+ if args_id >= 0
6395+ arg_ids = get_args(args_id)
6396+ all_ptypes = @cls_meth_ptypes[owner_ci].split("|")
6397+ if midx < all_ptypes.length
6398+ ptypes = all_ptypes[midx].split(",")
6399+ kk = 0
6400+ while kk < arg_ids.length
6401+ at = infer_type(arg_ids[kk])
6402+ if kk < ptypes.length
6403+ if ptypes[kk] == "int"
6404+ if at != "int"
6405+ ptypes[kk] = at
6406+ end
6407+ end
6408+ end
6409+ kk = kk + 1
6410+ end
6411+ all_ptypes[midx] = ptypes.join(",")
6412+ @cls_meth_ptypes[owner_ci] = all_ptypes.join("|")
6413+ end
6414+ end
6415+ end
6416+ end
6417+ end
6418+ end
6419+ end
6420+ walk_recv_method_calls(@nd_body[nid])
6421+ stmts = parse_id_list(@nd_stmts[nid])
6422+ k = 0
6423+ while k < stmts.length
6424+ walk_recv_method_calls(stmts[k])
6425+ k = k + 1
6426+ end
6427+ walk_recv_method_calls(@nd_expression[nid])
6428+ walk_recv_method_calls(@nd_arguments[nid])
6429+ args = parse_id_list(@nd_args[nid])
6430+ k = 0
6431+ while k < args.length
6432+ walk_recv_method_calls(args[k])
6433+ k = k + 1
6434+ end
6435+ walk_recv_method_calls(@nd_predicate[nid])
6436+ walk_recv_method_calls(@nd_subsequent[nid])
6437+ walk_recv_method_calls(@nd_else_clause[nid])
6438+ walk_recv_method_calls(@nd_rescue_clause[nid])
6439+ walk_recv_method_calls(@nd_ensure_clause[nid])
6440+ walk_recv_method_calls(@nd_receiver[nid])
6441+ conds = parse_id_list(@nd_conditions[nid])
6442+ k = 0
6443+ while k < conds.length
6444+ walk_recv_method_calls(conds[k])
6445+ k = k + 1
6446+ end
6447+ end
6448+
62616449 # Merge `at` (inferred from a new call-site argument) into the
62626450 # accumulated ctor param type `old_pt`. "int" is normally treated as
62636451 # a fallback/placeholder (many unresolved reads default to it), but a