Add two new attributes for struct initialization: 'requires_designator' and 'requires_init'. The first attribute attaches to a struct, class, or union and specifies that whenever a new variable of that type is declared, designated initializer syntax must be used. The second attribute attaches to a specific field and requires that that field must be explicitly initialized with a value whenever a new instance of the struct is declared.
requires_designator
For a struct Foo with one integer field x, the following declarations are valid and invalid under the require_designated_init attribute.
Foo foo {.x = 42}; // valid Foo foo {}; // valid Foo foo {42}; // invalid Foo foo; // invalid
For a struct Foo with multiple integer fields, the following declarations are valid and invalid under the requires_designator attribute.
Foo foo {.x = 42, .y = 21, .z = 1}; // valid Foo foo {.z = 1, .x = 42, .y = 21}; // valid Foo foo {.x = 42, .z = 1}; // valid Foo foo {}; // valid Foo foo {42, 21, 1}; // invalid Foo foo; // invalid
When the source code violates the attribute, an error is printed like this:
$ clang TestSingleFieldBad.cpp TestSingleFieldBad.cpp:6:14: error: struct variable declaration does not use designated initializer syntax Foo foo {10}; TestSingleFieldBad.cpp:1:23: note: required by 'requires_designator' attribute here struct [[clang::requires_designator]] Foo { 1 error generated.
requires_init
For each field that is marked with the required attribute, that field must be explicitly initialized using designated initializer syntax.
For example, if we have the following struct:
struct Foo { [[clang::requires_init]] int x; };
you must initialize the struct like this:
Foo foo {.x = 1};
The following declarations are all invalid:
Foo f1; Foo f2 {}; Foo f3 {1};
When an invalid program is compiled, you'll get an error like this:
$ clang TestSimpleBad.cpp TestSimpleBad.cpp:6:11: error: initializer for variable foo must explicitly initialize field x Foo foo {}; TestSimpleBad.cpp:2:18: note: enforced by 'requires_init' attribute here [[clang::requires_init]] int x; 1 error generated.
This should be RequiresDesignator.