Commit 0caef283

0caef283e0b1Merged

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

Description

feat: support instance_eval { block } via file-scope hoist

recv.instance_eval do ... end now lifts the block into a file-scope static function sp_ieval_<N>(sp_<Class> *self) and rewrites the call site to invoke it directly. The receiver-class flow analysis is the only role the analysis plays — its result types the self parameter. Class metadata is untouched: no synthetic methods registered, no collisions with user names, no entries surfacing in any future method-lookup or respond_to? machinery.

Reuses the same buffer pattern the proc/lambda hoist already uses (deferred emission at file scope), with a typed self parameter instead of sp_Val *self. A new pass infer_ieval_body_call_types walks each lifted body with @current_class_idx = ci set so bare self-calls inside the block (e.g. app.instance_eval { get("/") }) still propagate arg types to the receiver class's methods, the same way infer_class_body_call_types does for regular method bodies.

v1 scope (matches the original draft):

  • Receiver must be a top-level local previously bound to Class.new. Reassignment to a non-Class.new RHS poisons the entry. Method-, lambda-, class-, module-, and block-body locals are out of scope.
  • Block takes no parameters.
  • No closure capture of outer locals.
  • No yield / block_given? inside the block (rewriter bails so the call falls through and is rejected, matching prior behavior).
  • Block return value is discarded; lifted function is void. Expression-context calls evaluate to the receiver via a comma expression so if obj.instance_eval { ... } still type-checks.

Wider receivers, block params, closures, and a real return value are incremental follow-ups.

Bootstrap closes (gen2.c == gen3.c). make test is green.

Details

Commit
0caef283e0b1
Parent
ead35db19644

spinel_codegen.rbmodifiedView file

@@ -250,6 +250,13 @@
250250
251251 # Symbol type Phase 2 Step 1: intern table (infrastructure only; unused yet).
252252 @sym_names = "".split(",")
253+
254+ # instance_eval block hoisting: parallel arrays indexed by synthetic
255+ # function id N. Each lifted block becomes a file-scope static
256+ # function `sp_ieval_<N>` that takes a typed `self` parameter.
257+ @ieval_counter = 0
258+ @ieval_class_idxs = []
259+ @ieval_body_ids = []
253260 end
254261
255262 # Backslash-n for C string literals - bootstrap-safe (avoids escape level issues)
@@ -3447,6 +3454,14 @@
34473454 end
34483455 }
34493456
3457+ # Pass 2.6: hoist `recv.instance_eval do ... end` blocks into
3458+ # file-scope static functions. Receiver-class flow analysis picks the
3459+ # receiver's class, the block body is later compiled as a function
3460+ # with a typed `self` parameter, and the call site is rewritten to
3461+ # invoke that function directly. v1: top-level locals previously
3462+ # assigned `ClassName.new`; no block params; no closures; no yield.
3463+ rewrite_instance_eval_calls
3464+
34503465 # Pass 2.5: infer lambda parameter types from call sites
34513466 infer_lambda_param_types
34523467
@@ -3454,6 +3469,287 @@
34543469 infer_all_returns
34553470 end
34563471
3472+ def rewrite_instance_eval_calls
3473+ @ieval_counter = 0
3474+ local_class = {}
3475+ # Walk the AST recursively from the root, respecting scope boundaries.
3476+ # `local_class` maps `name -> class_idx` for the current scope only.
3477+ # Method/lambda/class/module/block bodies are NOT entered: their
3478+ # locals belong to a different scope, so the top-level map must not
3479+ # apply to them. A reassignment to a non-`Class.new` RHS poisons the
3480+ # mapping for that name.
3481+ ieval_walk(@root_id, local_class)
3482+ end
3483+
3484+ def ieval_walk(nid, local_class)
3485+ if nid < 0
3486+ return
3487+ end
3488+ t = @nd_type[nid]
3489+ if t == "ProgramNode"
3490+ ieval_walk(@nd_body[nid], local_class)
3491+ return
3492+ end
3493+ if t == "StatementsNode"
3494+ stmts = parse_id_list(@nd_stmts[nid])
3495+ k = 0
3496+ while k < stmts.length
3497+ ieval_walk(stmts[k], local_class)
3498+ k = k + 1
3499+ end
3500+ return
3501+ end
3502+ if t == "LocalVariableWriteNode"
3503+ val_nid = @nd_expression[nid]
3504+ vname = @nd_name[nid]
3505+ if val_nid >= 0
3506+ ieval_walk(val_nid, local_class)
3507+ ci = ieval_expr_class_idx(val_nid)
3508+ if ci >= 0
3509+ local_class[vname] = ci
3510+ else
3511+ if local_class.key?(vname)
3512+ local_class.delete(vname)
3513+ end
3514+ end
3515+ end
3516+ return
3517+ end
3518+ if t == "CallNode"
3519+ if @nd_name[nid] == "instance_eval"
3520+ ieval_rewrite_call(nid, local_class)
3521+ # Don't descend into the lifted block body.
3522+ return
3523+ end
3524+ r = @nd_receiver[nid]
3525+ if r >= 0
3526+ ieval_walk(r, local_class)
3527+ end
3528+ a = @nd_arguments[nid]
3529+ if a >= 0
3530+ ieval_walk(a, local_class)
3531+ end
3532+ # Block bodies are a separate scope; don't recurse.
3533+ return
3534+ end
3535+ if t == "ArgumentsNode"
3536+ args = parse_id_list(@nd_args[nid])
3537+ k = 0
3538+ while k < args.length
3539+ ieval_walk(args[k], local_class)
3540+ k = k + 1
3541+ end
3542+ return
3543+ end
3544+ if t == "IfNode"
3545+ ieval_walk(@nd_predicate[nid], local_class)
3546+ ieval_walk(@nd_body[nid], local_class)
3547+ ieval_walk(@nd_subsequent[nid], local_class)
3548+ ieval_walk(@nd_else_clause[nid], local_class)
3549+ return
3550+ end
3551+ if t == "UnlessNode"
3552+ ieval_walk(@nd_predicate[nid], local_class)
3553+ ieval_walk(@nd_body[nid], local_class)
3554+ ieval_walk(@nd_else_clause[nid], local_class)
3555+ return
3556+ end
3557+ if t == "ElseNode"
3558+ ieval_walk(@nd_body[nid], local_class)
3559+ return
3560+ end
3561+ if t == "WhileNode"
3562+ ieval_walk(@nd_predicate[nid], local_class)
3563+ ieval_walk(@nd_body[nid], local_class)
3564+ return
3565+ end
3566+ if t == "UntilNode"
3567+ ieval_walk(@nd_predicate[nid], local_class)
3568+ ieval_walk(@nd_body[nid], local_class)
3569+ return
3570+ end
3571+ if t == "CaseNode"
3572+ ieval_walk(@nd_predicate[nid], local_class)
3573+ conds = parse_id_list(@nd_conditions[nid])
3574+ k = 0
3575+ while k < conds.length
3576+ ieval_walk(conds[k], local_class)
3577+ k = k + 1
3578+ end
3579+ ieval_walk(@nd_else_clause[nid], local_class)
3580+ return
3581+ end
3582+ if t == "WhenNode"
3583+ ieval_walk(@nd_body[nid], local_class)
3584+ return
3585+ end
3586+ if t == "BeginNode"
3587+ ieval_walk(@nd_body[nid], local_class)
3588+ ieval_walk(@nd_rescue_clause[nid], local_class)
3589+ ieval_walk(@nd_ensure_clause[nid], local_class)
3590+ return
3591+ end
3592+ # DefNode, LambdaNode, ClassNode, ModuleNode, BlockNode: not entered.
3593+ # Their bodies introduce new scopes; the top-level map must not leak
3594+ # in. Anything else: stop. Conservative — we won't rewrite.
3595+ end
3596+
3597+ def ieval_expr_class_idx(nid)
3598+ if @nd_type[nid] == "CallNode"
3599+ if @nd_name[nid] == "new"
3600+ recv = @nd_receiver[nid]
3601+ if recv >= 0
3602+ if @nd_type[recv] == "ConstantReadNode"
3603+ return find_class_idx(@nd_name[recv])
3604+ end
3605+ # `Foo::Bar.new`: Spinel's class registry is keyed by the leaf
3606+ # name, matching how `collect_class` records nested classes.
3607+ if @nd_type[recv] == "ConstantPathNode"
3608+ return find_class_idx(@nd_name[recv])
3609+ end
3610+ end
3611+ end
3612+ end
3613+ -1
3614+ end
3615+
3616+ def ieval_rewrite_call(nid, local_class)
3617+ if @nd_name[nid] != "instance_eval"
3618+ return
3619+ end
3620+ recv = @nd_receiver[nid]
3621+ blk = @nd_block[nid]
3622+ if recv < 0
3623+ return
3624+ end
3625+ if blk < 0
3626+ return
3627+ end
3628+ # Skip blocks with parameters: lifted function takes only `self`.
3629+ if @nd_parameters[blk] >= 0
3630+ return
3631+ end
3632+ if @nd_type[recv] != "LocalVariableReadNode"
3633+ return
3634+ end
3635+ vname = @nd_name[recv]
3636+ if local_class.key?(vname) == false
3637+ return
3638+ end
3639+ ci = local_class[vname]
3640+ body_id = @nd_body[blk]
3641+ # v1: bail if the block uses yield/block_given?. Lifting it as a
3642+ # plain function would lose the enclosing method's block plumbing.
3643+ # Spinel rejected such code before — leaving it rejected is no
3644+ # regression, and the support belongs in a follow-up.
3645+ if body_id >= 0 && body_has_yield(body_id) == 1
3646+ return
3647+ end
3648+ n = @ieval_counter
3649+ @ieval_counter = @ieval_counter + 1
3650+ @ieval_class_idxs.push(ci)
3651+ @ieval_body_ids.push(body_id)
3652+ # Mark the call site: the function name doubles as the synthetic id.
3653+ # compile_call_expr / compile_call_stmt recognise the prefix and
3654+ # emit a direct C call to `sp_ieval_<N>`.
3655+ @nd_name[nid] = "__sp_ieval_" + n.to_s
3656+ @nd_block[nid] = -1
3657+ end
3658+
3659+ def emit_ieval_funcs
3660+ n = 0
3661+ while n < @ieval_class_idxs.length
3662+ emit_ieval_func(n, @ieval_class_idxs[n], @ieval_body_ids[n])
3663+ n = n + 1
3664+ end
3665+ end
3666+
3667+ # Type inference: walk each lifted block body with `@current_class_idx`
3668+ # set to the receiver's class so bare self-calls inside the block
3669+ # propagate arg types to the class's methods. Without this pass, a
3670+ # block like `app.instance_eval { get("/") }` would fail to teach
3671+ # `Routes#get(path)` that `path` is a string. Sibling pass to
3672+ # `infer_class_body_call_types` for hoisted blocks.
3673+ def infer_ieval_body_call_types
3674+ n = 0
3675+ while n < @ieval_class_idxs.length
3676+ ci = @ieval_class_idxs[n]
3677+ bid = @ieval_body_ids[n]
3678+ if bid >= 0
3679+ @current_class_idx = ci
3680+ push_scope
3681+ scan_cls_method_calls(ci, bid)
3682+ scan_new_calls(bid)
3683+ pop_scope
3684+ @current_class_idx = -1
3685+ end
3686+ n = n + 1
3687+ end
3688+ end
3689+
3690+ def is_ieval_call_name(mname)
3691+ if mname.length <= 11
3692+ return 0
3693+ end
3694+ if mname[0, 11] == "__sp_ieval_"
3695+ return 1
3696+ end
3697+ 0
3698+ end
3699+
3700+ def compile_ieval_call(nid)
3701+ mname = @nd_name[nid]
3702+ # Synthetic id is the suffix after the 11-char "__sp_ieval_" prefix.
3703+ suffix = mname[11, mname.length - 11]
3704+ "sp_ieval_" + suffix + "(" + compile_expr(@nd_receiver[nid]) + ")"
3705+ end
3706+
3707+ # v1 lifts blocks into void-returning functions (Ruby's
3708+ # instance_eval-as-expression value isn't supported yet). When a
3709+ # call appears in expression position, return the recv pointer as a
3710+ # truthy default via a comma expression so callers like
3711+ # `if obj.instance_eval { ... }` still type-check. Real expression
3712+ # support — return the block's last expression — is a v2 follow-up.
3713+ def compile_ieval_call_expr(nid)
3714+ "(" + compile_ieval_call(nid) + ", " + compile_expr(@nd_receiver[nid]) + ")"
3715+ end
3716+
3717+ def emit_ieval_func(n, ci, bid)
3718+ cname = @cls_names[ci]
3719+ @current_class_idx = ci
3720+ @current_method_name = "__sp_ieval_" + n.to_s
3721+ @current_method_return = "void"
3722+ @indent = 1
3723+ @in_gc_scope = 0
3724+ @in_yield_method = 0
3725+
3726+ if @cls_is_value_type[ci] == 1
3727+ emit_raw("static void sp_ieval_" + n.to_s + "(sp_" + cname + " self) {")
3728+ else
3729+ emit_raw("static void sp_ieval_" + n.to_s + "(sp_" + cname + " *self) {")
3730+ end
3731+
3732+ push_scope
3733+ if bid >= 0
3734+ declare_method_locals(bid, "".split(","))
3735+ if @needs_gc == 1
3736+ emit(" SP_GC_SAVE();")
3737+ @in_gc_scope = 1
3738+ if @cls_is_value_type[ci] == 0
3739+ emit(" SP_GC_ROOT(self);")
3740+ end
3741+ end
3742+ compile_body_return(bid, "void")
3743+ end
3744+ pop_scope
3745+
3746+ @current_class_idx = -1
3747+ @current_method_name = ""
3748+ @indent = 0
3749+ emit_raw("}")
3750+ emit_raw("")
3751+ end
3752+
34573753 def is_builtin_type_name(name)
34583754 if name == "Integer"
34593755 return 1
@@ -7538,6 +7834,7 @@
75387834 infer_main_call_types
75397835 infer_function_body_call_types
75407836 infer_class_body_call_types
7837+ infer_ieval_body_call_types
75417838 detect_poly_locals
75427839 # Iterative type inference: converge param types, return types, ivar types.
75437840 # Stop early when the signature of these three arrays stops changing.
@@ -7606,6 +7903,7 @@
76067903 emit_global_constants
76077904 emit_raw("/*LAMBDA_INSERT_POINT*/")
76087905 emit_class_methods
7906+ emit_ieval_funcs
76097907 emit_toplevel_methods
76107908 # Emit lambda functions before main (they are generated during compilation)
76117909 # We emit them in emit_main after forward declarations
@@ -12316,6 +12614,14 @@
1231612614 mname = @nd_name[nid]
1231712615 recv = @nd_receiver[nid]
1231812616
12617+ # Hoisted instance_eval block: emit a direct C call to the synthetic
12618+ # file-scope function. The receiver is a local variable known to
12619+ # carry a class instance (the rewriter checked this); pass it as the
12620+ # typed `self` argument.
12621+ if is_ieval_call_name(mname) == 1
12622+ return compile_ieval_call_expr(nid)
12623+ end
12624+
1231912625 # Fiber.new { block }
1232012626 if mname == "new" && recv >= 0
1232112627 if constructor_class_name(recv) == "Fiber"
@@ -17515,6 +17821,13 @@
1751517821 return
1751617822 end
1751717823
17824+ # Hoisted instance_eval block (statement context): the lifted
17825+ # function returns void, so emit it as a plain statement.
17826+ if is_ieval_call_name(mname) == 1
17827+ emit(" " + compile_ieval_call(nid) + ";")
17828+ return
17829+ end
17830+
1751817831 # IO: puts, print, printf
1751917832 if compile_io_call_stmt(nid, mname, recv) == 1
1752017833 return