Skip to content

Commit afa6878

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 3371e96 commit afa6878

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
@@ -698,6 +698,7 @@ class sema
698698
}
699699
};
700700
std::vector<stack_entry> selection_stack;
701+
bool in_branch = false;
701702

702703
for (
703704
;
@@ -798,12 +799,17 @@ class sema
798799
"local variable " + name
799800
+ " is used in a branch before it was initialized");
800801
}
802+
803+
if (!in_branch) {
804+
return sym.assignment_to;
805+
}
806+
801807
selection_stack.back().branches.back().result = sym.assignment_to;
802808

803809
// The depth of this branch should always be the depth of
804810
// the current selection statement + 1
805811
int branch_depth = symbols[selection_stack.back().pos].depth + 1;
806-
while (symbols[pos + 1].depth > branch_depth) {
812+
while (symbols[pos + 1].depth > branch_depth && symbols[pos + 1].start) {
807813
++pos;
808814
}
809815
}
@@ -909,6 +915,11 @@ class sema
909915
)
910916
{
911917
selection_stack.back().branches.emplace_back( pos, false );
918+
in_branch = true;
919+
}
920+
921+
if ( !sym.start ) {
922+
in_branch = false;
912923
}
913924
}
914925
}

0 commit comments

Comments
 (0)