Skip to content

Commit

Permalink
Disallow initializing structs with lists
Browse files Browse the repository at this point in the history
Summary:
The following code
```
struct S {}

const S s = [1, 2, 3];
```
currently compiles in Thrift (the list content is ignored, at least in cpp2) which is obviously broken. Turn it into an error as we do for other incompatible initializers.

Add more test cases for struct initialization.

Reviewed By: avalonalex

Differential Revision: D50476253

fbshipit-source-id: 2608e3fdcf655ab8142194729e70e5590b893c22
  • Loading branch information
vitaut authored and facebook-github-bot committed Oct 23, 2023
1 parent fb35564 commit e4a4675
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 13 deletions.
11 changes: 1 addition & 10 deletions thrift/compiler/sema/const_checker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -278,16 +278,7 @@ class const_checker {
check_fields(type, value->get_map());
return;
}
// Only warn on initialization from [] for legacy reasons.
auto level = value->get_type() == t_const_value::CV_LIST
? diagnostic_level::warning
: diagnostic_level::error;
diags_.report(
node_,
level,
"{} is incompatible with `{}`",
get_category(value),
type->name());
error("{} is incompatible with `{}`", get_category(value), type->name());
}

void check_exception(const t_exception* type, const t_const_value* value) {
Expand Down
10 changes: 7 additions & 3 deletions thrift/compiler/test/compiler_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -467,11 +467,15 @@ TEST(CompilerTest, const_double_value) {
)");
}

TEST(CompilerTest, invalid_struct_initializer) {
TEST(CompilerTest, struct_initializer) {
check_compile(R"(
struct S {}
const S s1 = ""; # expected-error: string is incompatible with `S`
const S s2 = []; # expected-warning: list is incompatible with `S`
const S s1 = {}; # OK
const S s2 = 42; # expected-error: integer is incompatible with `S`
const S s3 = 4.2; # expected-error: floating-point number is incompatible with `S`
const S s4 = ""; # expected-error: string is incompatible with `S`
const S s5 = true; # expected-error: bool is incompatible with `S`
const S s6 = []; # expected-error: list is incompatible with `S`
)");
}

Expand Down

0 comments on commit e4a4675

Please sign in to comment.