Commit 80ba21b83c

Andrew Kelley <andrew@ziglang.org>
2020-02-08 20:59:33
properly spill optional payload capture value
1 parent 884804d
Changed files (3)
src
test
stage1
behavior
src/analyze.cpp
@@ -6104,11 +6104,12 @@ static void mark_suspension_point(Scope *scope) {
                 continue;
             }
             case ScopeIdExpr: {
+                ScopeExpr *parent_expr_scope = reinterpret_cast<ScopeExpr *>(scope);
                 if (!looking_for_exprs) {
+                    parent_expr_scope->need_spill = MemoizedBoolTrue;
                     // Now we're only looking for a block, to see if it's in a loop (see the case ScopeIdBlock)
                     continue;
                 }
-                ScopeExpr *parent_expr_scope = reinterpret_cast<ScopeExpr *>(scope);
                 if (child_expr_scope != nullptr) {
                     for (size_t i = 0; parent_expr_scope->children_ptr[i] != child_expr_scope; i += 1) {
                         assert(i < parent_expr_scope->children_len);
src/ir.cpp
@@ -8874,7 +8874,9 @@ static IrInstSrc *ir_gen_if_optional_expr(IrBuilderSrc *irb, Scope *scope, AstNo
     AstNode *else_node = node->data.test_expr.else_node;
     bool var_is_ptr = node->data.test_expr.var_is_ptr;
 
-    IrInstSrc *maybe_val_ptr = ir_gen_node_extra(irb, expr_node, scope, LValPtr, nullptr);
+    ScopeExpr *spill_scope = create_expr_scope(irb->codegen, expr_node, scope);
+
+    IrInstSrc *maybe_val_ptr = ir_gen_node_extra(irb, expr_node, &spill_scope->base, LValPtr, nullptr);
     if (maybe_val_ptr == irb->codegen->invalid_inst_src)
         return maybe_val_ptr;
 
@@ -8899,7 +8901,7 @@ static IrInstSrc *ir_gen_if_optional_expr(IrBuilderSrc *irb, Scope *scope, AstNo
 
     ir_set_cursor_at_end_and_append_block(irb, then_block);
 
-    Scope *subexpr_scope = create_runtime_scope(irb->codegen, node, scope, is_comptime);
+    Scope *subexpr_scope = create_runtime_scope(irb->codegen, node, &spill_scope->base, is_comptime);
     Scope *var_scope;
     if (var_symbol) {
         bool is_shadowable = false;
test/stage1/behavior/async_fn.zig
@@ -1416,3 +1416,27 @@ test "async function call resolves target fn frame, runtime func" {
     resume S.global_frame;
     expect(S.global_int == 10);
 }
+
+test "properly spill optional payload capture value" {
+    const S = struct {
+        var global_frame: anyframe = undefined;
+        var global_int: usize = 2;
+
+        fn foo() void {
+            var opt: ?usize = 1234;
+            if (opt) |x| {
+                bar();
+                global_int += x;
+            }
+        }
+
+        fn bar() void {
+            global_frame = @frame();
+            suspend;
+            global_int += 1;
+        }
+    };
+    _ = async S.foo();
+    resume S.global_frame;
+    expect(S.global_int == 1237);
+}