Skip to content

Commit 4b90177

Browse files
committed
Add support for constructing variables in conditions
This change allows to initialize variables in `if` and `else if` conditions. It make possible to process the following code: ```cpp main: (args) = { p : *int; a := 1; b := 2; c := 3; d := 4; if args.cout == 3 { p = a&; } else if args.cout == 2 { p = c&; } else if p = b& { p = a&; } else { p = d&; } std::cout << p* << std::endl; } ``` And gets generated: ```cpp auto main(int const argc_, char const* const* const argv_) -> int{ auto args = cpp2::make_args(argc_, argv_); #line 2 "tests/else_if.cpp2" cpp2::deferred_init<int*> p; auto a {1}; auto b {2}; auto c {3}; auto d {4}; if (args.cout==3) { p.construct(&a); } else if (args.cout==2) { p.construct(&c); } else if (p.construct(&b)) { p.value() = &a; } else { p.value() = &d; } std::cout << *cpp2::assert_not_null(std::move(p.value())) << std::endl; } ```
1 parent c41e5d1 commit 4b90177

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

source/sema.h

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -695,6 +695,7 @@ class sema
695695
}
696696
};
697697
std::vector<stack_entry> selection_stack;
698+
bool in_branch = false;
698699

699700
for (
700701
;
@@ -795,12 +796,17 @@ class sema
795796
"local variable " + name
796797
+ " is used in a branch before it was initialized");
797798
}
799+
800+
if (!in_branch) {
801+
return sym.assignment_to;
802+
}
803+
798804
selection_stack.back().branches.back().result = sym.assignment_to;
799805

800806
// The depth of this branch should always be the depth of
801807
// the current selection statement + 1
802808
int branch_depth = symbols[selection_stack.back().pos].depth + 1;
803-
while (symbols[pos + 1].depth > branch_depth) {
809+
while (symbols[pos + 1].depth > branch_depth && symbols[pos + 1].start) {
804810
++pos;
805811
}
806812
}
@@ -906,6 +912,11 @@ class sema
906912
)
907913
{
908914
selection_stack.back().branches.emplace_back( pos, false );
915+
in_branch = true;
916+
}
917+
918+
if ( !sym.start ) {
919+
in_branch = false;
909920
}
910921
}
911922
}

0 commit comments

Comments
 (0)