Allow to initialize a struct with other struct

This commit is contained in:
Rui Ueyama 2020-07-09 22:05:46 +09:00
parent e9d2c46ab3
commit aca19dd350
2 changed files with 15 additions and 1 deletions

14
parse.c
View File

@ -715,6 +715,18 @@ static void initializer2(Token **rest, Token *tok, Initializer *init) {
}
if (init->ty->kind == TY_STRUCT) {
// A struct can be initialized with another struct. E.g.
// `struct T x = y;` where y is a variable of type `struct T`.
// Handle that case first.
if (!equal(tok, "{")) {
Node *expr = assign(rest, tok);
add_type(expr);
if (expr->ty->kind == TY_STRUCT) {
init->expr = expr;
return;
}
}
struct_initializer(rest, tok, init);
return;
}
@ -755,7 +767,7 @@ static Node *create_lvar_init(Initializer *init, Type *ty, InitDesg *desg, Token
return node;
}
if (ty->kind == TY_STRUCT) {
if (ty->kind == TY_STRUCT && !init->expr) {
Node *node = new_node(ND_NULL_EXPR, tok);
for (Member *mem = ty->members; mem; mem = mem->next) {

View File

@ -55,6 +55,8 @@ int main() {
ASSERT(5, ({ typedef struct {int a,b,c,d,e,f;} T; T x={1,2,3,4,5,6}; T y; y=x; y.e; }));
ASSERT(2, ({ typedef struct {int a,b;} T; T x={1,2}; T y, z; z=y=x; z.b; }));
ASSERT(1, ({ typedef struct {int a,b;} T; T x={1,2}; T y=x; y.a; }));
printf("OK\n");
return 0;
}