Skip to content

Commit

Permalink
codegen unions
Browse files Browse the repository at this point in the history
  • Loading branch information
omdxp committed Sep 1, 2024
1 parent abdd86b commit 7c648b2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
24 changes: 24 additions & 0 deletions codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -534,6 +534,16 @@ void codegen_generate_global_variable_for_struct(struct node *node) {
asm_keyword_for_size(variable_size(node), tmp_buf));
}

void codegen_generate_global_variable_for_union(struct node *node) {
if (node->var.val != NULL) {
compiler_error(current_process, "Unions with values not supported");
}

char tmp_buf[256];
asm_push("%s: %s 0", node->var.name,
asm_keyword_for_size(variable_size(node), tmp_buf));
}

void codegen_generate_global_variable(struct node *node) {
asm_push("; %s %s", node->var.type.type_str, node->var.name);
switch (node->var.type.type) {
Expand All @@ -549,6 +559,10 @@ void codegen_generate_global_variable(struct node *node) {
codegen_generate_global_variable_for_struct(node);
break;

case DATA_TYPE_UNION:
codegen_generate_global_variable_for_union(node);
break;

case DATA_TYPE_DOUBLE:
case DATA_TYPE_FLOAT:
compiler_error(current_process, "Unsupported data type");
Expand All @@ -562,6 +576,12 @@ void codegen_generate_struct(struct node *node) {
}
}

void codegen_generate_union(struct node *node) {
if (node->flags & NODE_FLAG_HAS_VARIABLE_COMBINED) {
codegen_generate_global_variable(node->_union.var);
}
}

void codegen_generate_data_section_part(struct node *node) {
switch (node->type) {
case NODE_TYPE_VARIABLE:
Expand All @@ -572,6 +592,10 @@ void codegen_generate_data_section_part(struct node *node) {
codegen_generate_struct(node);
break;

case NODE_TYPE_UNION:
codegen_generate_union(node);
break;

default:
break;
}
Expand Down
11 changes: 9 additions & 2 deletions test.c
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
union abc {
int x;
int y;
};

union abc a;

int main() {
int *x;
*x = 50;
a.x = 20;
return a.y;
}

0 comments on commit 7c648b2

Please sign in to comment.