Skip to content

Commit ec8021d

Browse files
committed
Support initializing type members with this.name = init (synonym for name = init)
Sometimes programmers like to `this`-qualify, so this adds support for the optional explicit 'this.' qualifier syntax for constructor body's data member initialization
1 parent 8ed2e72 commit ec8021d

File tree

3 files changed

+103
-31
lines changed

3 files changed

+103
-31
lines changed

regression-tests/pure2-types-basics.cpp2

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@ myclass : type = {
1010
}
1111

1212
operator=: (out this, s: std::string) = {
13-
data = 99;
14-
more = "plugh";
13+
this.data = 99;
14+
this.more = "plugh";
1515
std::cout << "myclass: explicit constructor from string\n";
1616
}
1717

source/cppfront.cpp

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3711,22 +3711,47 @@ class cppfront
37113711
return;
37123712
}
37133713

3714+
// Check that this is an assignment to *object
3715+
auto exprs = (*statement)->get_lhs_rhs_if_simple_assignment();
3716+
3717+
assert(!exprs.lhs || exprs.lhs->expr);
3718+
auto is_match = false;
3719+
if (exprs.lhs)
3720+
{
3721+
// First, see if it's an assignment 'name = something'
3722+
is_match = (*object)->has_name(*exprs.lhs->expr->get_token());
3723+
3724+
// Otherwise, check if it's 'this.name = something'
3725+
if (!is_match)
3726+
{
3727+
// If it's of the form 'this.name', get a pointer
3728+
// to the token for 'name'
3729+
auto second_tok = exprs.lhs->get_second_token_if_a_this_qualified_name();
3730+
if (second_tok &&
3731+
(*object)->has_name(*second_tok)
3732+
)
3733+
{
3734+
is_match = true;
3735+
}
3736+
}
3737+
}
3738+
37143739
// If this is not an assignment to *object, complain
3715-
auto toks = (*statement)->get_lhs_rhs_if_simple_assignment();
3716-
if (!toks.lhs || !(*object)->has_name(*toks.lhs)) {
3740+
if (!is_match)
3741+
{
37173742
errors.emplace_back(
37183743
(*statement)->position(),
37193744
"expected '" + (*object)->name()->to_string(true) + " = ...' initialization statement - " + error_msg
37203745
);
37213746
return;
37223747
}
37233748

3724-
assert(toks.rhs);
3749+
assert(exprs.rhs && exprs.rhs->expr);
37253750
current_function_info.back().prolog.mem_inits.push_back(
37263751
separator +
37273752
(*object)->name()->to_string(true) +
37283753
"{ " +
3729-
toks.rhs->to_string(true) +
3754+
exprs.rhs->expr->get_token()->to_string(true) +
37303755
" }"
37313756
);
37323757
(*statement)->emitted = true;

0 commit comments

Comments
 (0)