Commit 5168e358

5168e358a9e1Merged

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

Description

Merge pull request #15 from khasinski/feat/instance-eval-block-form

Support instance_eval { block } in DSL receivers

Details

Commit
5168e358a9e1
Parent
3e89023db62e
Merge parent
a978f22747b6

spinel_codegen.rbmodifiedView file

@@ -271,6 +271,13 @@
271271
272272 # Symbol type Phase 2 Step 1: intern table (infrastructure only; unused yet).
273273 @sym_names = "".split(",")
274+
275+ # instance_eval block hoisting: parallel arrays indexed by synthetic
276+ # function id N. Each lifted block becomes a file-scope static
277+ # function `sp_ieval_<N>` that takes a typed `self` parameter.
278+ @ieval_counter = 0
279+ @ieval_class_idxs = []
280+ @ieval_body_ids = []
274281 end
275282
276283 # Backslash-n for C string literals - bootstrap-safe (avoids escape level issues)
@@ -4010,6 +4017,14 @@
40104017 end
40114018 }
40124019
4020+ # Pass 2.6: hoist `recv.instance_eval do ... end` blocks into
4021+ # file-scope static functions. Receiver-class flow analysis picks the
4022+ # receiver's class, the block body is later compiled as a function
4023+ # with a typed `self` parameter, and the call site is rewritten to
4024+ # invoke that function directly. v1: top-level locals previously
4025+ # assigned `ClassName.new`; no block params; no closures; no yield.
4026+ rewrite_instance_eval_calls
4027+
40134028 # Pass 2.5: infer lambda parameter types from call sites
40144029 infer_lambda_param_types
40154030
@@ -4017,6 +4032,287 @@
40174032 infer_all_returns
40184033 end
40194034
4035+ def rewrite_instance_eval_calls
4036+ @ieval_counter = 0
4037+ local_class = {}
4038+ # Walk the AST recursively from the root, respecting scope boundaries.
4039+ # `local_class` maps `name -> class_idx` for the current scope only.
4040+ # Method/lambda/class/module/block bodies are NOT entered: their
4041+ # locals belong to a different scope, so the top-level map must not
4042+ # apply to them. A reassignment to a non-`Class.new` RHS poisons the
4043+ # mapping for that name.
4044+ ieval_walk(@root_id, local_class)
4045+ end
4046+
4047+ def ieval_walk(nid, local_class)
4048+ if nid < 0
4049+ return
4050+ end
4051+ t = @nd_type[nid]
4052+ if t == "ProgramNode"
4053+ ieval_walk(@nd_body[nid], local_class)
4054+ return
4055+ end
4056+ if t == "StatementsNode"
4057+ stmts = parse_id_list(@nd_stmts[nid])
4058+ k = 0
4059+ while k < stmts.length
4060+ ieval_walk(stmts[k], local_class)
4061+ k = k + 1
4062+ end
4063+ return
4064+ end
4065+ if t == "LocalVariableWriteNode"
4066+ val_nid = @nd_expression[nid]
4067+ vname = @nd_name[nid]
4068+ if val_nid >= 0
4069+ ieval_walk(val_nid, local_class)
4070+ ci = ieval_expr_class_idx(val_nid)
4071+ if ci >= 0
4072+ local_class[vname] = ci
4073+ else
4074+ if local_class.key?(vname)
4075+ local_class.delete(vname)
4076+ end
4077+ end
4078+ end
4079+ return
4080+ end
4081+ if t == "CallNode"
4082+ if @nd_name[nid] == "instance_eval"
4083+ ieval_rewrite_call(nid, local_class)
4084+ # Don't descend into the lifted block body.
4085+ return
4086+ end
4087+ r = @nd_receiver[nid]
4088+ if r >= 0
4089+ ieval_walk(r, local_class)
4090+ end
4091+ a = @nd_arguments[nid]
4092+ if a >= 0
4093+ ieval_walk(a, local_class)
4094+ end
4095+ # Block bodies are a separate scope; don't recurse.
4096+ return
4097+ end
4098+ if t == "ArgumentsNode"
4099+ args = parse_id_list(@nd_args[nid])
4100+ k = 0
4101+ while k < args.length
4102+ ieval_walk(args[k], local_class)
4103+ k = k + 1
4104+ end
4105+ return
4106+ end
4107+ if t == "IfNode"
4108+ ieval_walk(@nd_predicate[nid], local_class)
4109+ ieval_walk(@nd_body[nid], local_class)
4110+ ieval_walk(@nd_subsequent[nid], local_class)
4111+ ieval_walk(@nd_else_clause[nid], local_class)
4112+ return
4113+ end
4114+ if t == "UnlessNode"
4115+ ieval_walk(@nd_predicate[nid], local_class)
4116+ ieval_walk(@nd_body[nid], local_class)
4117+ ieval_walk(@nd_else_clause[nid], local_class)
4118+ return
4119+ end
4120+ if t == "ElseNode"
4121+ ieval_walk(@nd_body[nid], local_class)
4122+ return
4123+ end
4124+ if t == "WhileNode"
4125+ ieval_walk(@nd_predicate[nid], local_class)
4126+ ieval_walk(@nd_body[nid], local_class)
4127+ return
4128+ end
4129+ if t == "UntilNode"
4130+ ieval_walk(@nd_predicate[nid], local_class)
4131+ ieval_walk(@nd_body[nid], local_class)
4132+ return
4133+ end
4134+ if t == "CaseNode"
4135+ ieval_walk(@nd_predicate[nid], local_class)
4136+ conds = parse_id_list(@nd_conditions[nid])
4137+ k = 0
4138+ while k < conds.length
4139+ ieval_walk(conds[k], local_class)
4140+ k = k + 1
4141+ end
4142+ ieval_walk(@nd_else_clause[nid], local_class)
4143+ return
4144+ end
4145+ if t == "WhenNode"
4146+ ieval_walk(@nd_body[nid], local_class)
4147+ return
4148+ end
4149+ if t == "BeginNode"
4150+ ieval_walk(@nd_body[nid], local_class)
4151+ ieval_walk(@nd_rescue_clause[nid], local_class)
4152+ ieval_walk(@nd_ensure_clause[nid], local_class)
4153+ return
4154+ end
4155+ # DefNode, LambdaNode, ClassNode, ModuleNode, BlockNode: not entered.
4156+ # Their bodies introduce new scopes; the top-level map must not leak
4157+ # in. Anything else: stop. Conservative — we won't rewrite.
4158+ end
4159+
4160+ def ieval_expr_class_idx(nid)
4161+ if @nd_type[nid] == "CallNode"
4162+ if @nd_name[nid] == "new"
4163+ recv = @nd_receiver[nid]
4164+ if recv >= 0
4165+ if @nd_type[recv] == "ConstantReadNode"
4166+ return find_class_idx(@nd_name[recv])
4167+ end
4168+ # `Foo::Bar.new`: Spinel's class registry is keyed by the leaf
4169+ # name, matching how `collect_class` records nested classes.
4170+ if @nd_type[recv] == "ConstantPathNode"
4171+ return find_class_idx(@nd_name[recv])
4172+ end
4173+ end
4174+ end
4175+ end
4176+ -1
4177+ end
4178+
4179+ def ieval_rewrite_call(nid, local_class)
4180+ if @nd_name[nid] != "instance_eval"
4181+ return
4182+ end
4183+ recv = @nd_receiver[nid]
4184+ blk = @nd_block[nid]
4185+ if recv < 0
4186+ return
4187+ end
4188+ if blk < 0
4189+ return
4190+ end
4191+ # Skip blocks with parameters: lifted function takes only `self`.
4192+ if @nd_parameters[blk] >= 0
4193+ return
4194+ end
4195+ if @nd_type[recv] != "LocalVariableReadNode"
4196+ return
4197+ end
4198+ vname = @nd_name[recv]
4199+ if local_class.key?(vname) == false
4200+ return
4201+ end
4202+ ci = local_class[vname]
4203+ body_id = @nd_body[blk]
4204+ # v1: bail if the block uses yield/block_given?. Lifting it as a
4205+ # plain function would lose the enclosing method's block plumbing.
4206+ # Spinel rejected such code before — leaving it rejected is no
4207+ # regression, and the support belongs in a follow-up.
4208+ if body_id >= 0 && body_has_yield(body_id) == 1
4209+ return
4210+ end
4211+ n = @ieval_counter
4212+ @ieval_counter = @ieval_counter + 1
4213+ @ieval_class_idxs.push(ci)
4214+ @ieval_body_ids.push(body_id)
4215+ # Mark the call site: the function name doubles as the synthetic id.
4216+ # compile_call_expr / compile_call_stmt recognise the prefix and
4217+ # emit a direct C call to `sp_ieval_<N>`.
4218+ @nd_name[nid] = "__sp_ieval_" + n.to_s
4219+ @nd_block[nid] = -1
4220+ end
4221+
4222+ def emit_ieval_funcs
4223+ n = 0
4224+ while n < @ieval_class_idxs.length
4225+ emit_ieval_func(n, @ieval_class_idxs[n], @ieval_body_ids[n])
4226+ n = n + 1
4227+ end
4228+ end
4229+
4230+ # Type inference: walk each lifted block body with `@current_class_idx`
4231+ # set to the receiver's class so bare self-calls inside the block
4232+ # propagate arg types to the class's methods. Without this pass, a
4233+ # block like `app.instance_eval { get("/") }` would fail to teach
4234+ # `Routes#get(path)` that `path` is a string. Sibling pass to
4235+ # `infer_class_body_call_types` for hoisted blocks.
4236+ def infer_ieval_body_call_types
4237+ n = 0
4238+ while n < @ieval_class_idxs.length
4239+ ci = @ieval_class_idxs[n]
4240+ bid = @ieval_body_ids[n]
4241+ if bid >= 0
4242+ @current_class_idx = ci
4243+ push_scope
4244+ scan_cls_method_calls(ci, bid)
4245+ scan_new_calls(bid)
4246+ pop_scope
4247+ @current_class_idx = -1
4248+ end
4249+ n = n + 1
4250+ end
4251+ end
4252+
4253+ def is_ieval_call_name(mname)
4254+ if mname.length <= 11
4255+ return 0
4256+ end
4257+ if mname[0, 11] == "__sp_ieval_"
4258+ return 1
4259+ end
4260+ 0
4261+ end
4262+
4263+ def compile_ieval_call(nid)
4264+ mname = @nd_name[nid]
4265+ # Synthetic id is the suffix after the 11-char "__sp_ieval_" prefix.
4266+ suffix = mname[11, mname.length - 11]
4267+ "sp_ieval_" + suffix + "(" + compile_expr(@nd_receiver[nid]) + ")"
4268+ end
4269+
4270+ # v1 lifts blocks into void-returning functions (Ruby's
4271+ # instance_eval-as-expression value isn't supported yet). When a
4272+ # call appears in expression position, return the recv pointer as a
4273+ # truthy default via a comma expression so callers like
4274+ # `if obj.instance_eval { ... }` still type-check. Real expression
4275+ # support — return the block's last expression — is a v2 follow-up.
4276+ def compile_ieval_call_expr(nid)
4277+ "(" + compile_ieval_call(nid) + ", " + compile_expr(@nd_receiver[nid]) + ")"
4278+ end
4279+
4280+ def emit_ieval_func(n, ci, bid)
4281+ cname = @cls_names[ci]
4282+ @current_class_idx = ci
4283+ @current_method_name = "__sp_ieval_" + n.to_s
4284+ @current_method_return = "void"
4285+ @indent = 1
4286+ @in_gc_scope = 0
4287+ @in_yield_method = 0
4288+
4289+ if @cls_is_value_type[ci] == 1
4290+ emit_raw("static void sp_ieval_" + n.to_s + "(sp_" + cname + " self) {")
4291+ else
4292+ emit_raw("static void sp_ieval_" + n.to_s + "(sp_" + cname + " *self) {")
4293+ end
4294+
4295+ push_scope
4296+ if bid >= 0
4297+ declare_method_locals(bid, "".split(","))
4298+ if @needs_gc == 1
4299+ emit(" SP_GC_SAVE();")
4300+ @in_gc_scope = 1
4301+ if @cls_is_value_type[ci] == 0
4302+ emit(" SP_GC_ROOT(self);")
4303+ end
4304+ end
4305+ compile_body_return(bid, "void")
4306+ end
4307+ pop_scope
4308+
4309+ @current_class_idx = -1
4310+ @current_method_name = ""
4311+ @indent = 0
4312+ emit_raw("}")
4313+ emit_raw("")
4314+ end
4315+
40204316 def is_builtin_type_name(name)
40214317 if name == "Integer"
40224318 return 1
@@ -8716,6 +9012,7 @@
87169012 infer_main_call_types
87179013 infer_function_body_call_types
87189014 infer_class_body_call_types
9015+ infer_ieval_body_call_types
87199016 detect_poly_locals
87209017 # Iterative type inference: converge param types, return types, ivar types.
87219018 # Stop early when the signature of these three arrays stops changing.
@@ -8790,6 +9087,7 @@
87909087 emit_global_constants
87919088 emit_raw("/*LAMBDA_INSERT_POINT*/")
87929089 emit_class_methods
9090+ emit_ieval_funcs
87939091 emit_toplevel_methods
87949092 # Emit lambda functions before main (they are generated during compilation)
87959093 # We emit them in emit_main after forward declarations
@@ -13761,6 +14059,14 @@
1376114059 mname = @nd_name[nid]
1376214060 recv = @nd_receiver[nid]
1376314061
14062+ # Hoisted instance_eval block: emit a direct C call to the synthetic
14063+ # file-scope function. The receiver is a local variable known to
14064+ # carry a class instance (the rewriter checked this); pass it as the
14065+ # typed `self` argument.
14066+ if is_ieval_call_name(mname) == 1
14067+ return compile_ieval_call_expr(nid)
14068+ end
14069+
1376414070 # Fiber.new { block }
1376514071 if mname == "new" && recv >= 0
1376614072 if constructor_class_name(recv) == "Fiber"
@@ -20043,6 +20349,13 @@
2004320349 return
2004420350 end
2004520351
20352+ # Hoisted instance_eval block (statement context): the lifted
20353+ # function returns void, so emit it as a plain statement.
20354+ if is_ieval_call_name(mname) == 1
20355+ emit(" " + compile_ieval_call(nid) + ";")
20356+ return
20357+ end
20358+
2004620359 # IO: puts, print, printf
2004720360 if compile_io_call_stmt(nid, mname, recv) == 1
2004820361 return