Skip to content

Commit

Permalink
Lecture 178 - Generating unions
Browse files Browse the repository at this point in the history
  • Loading branch information
dragonzapeducation committed Sep 1, 2022
1 parent 72a9921 commit 0435a04
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
29 changes: 29 additions & 0 deletions codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,19 @@ void codegen_generate_global_variable_for_struct(struct node* node)
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_for_union(struct node* node)
{
if (node->var.val != NULL)
{
compiler_error(current_process, "We dont yet support values for unions");
return;
}

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);
Expand All @@ -581,6 +594,10 @@ void codegen_generate_global_variable(struct node *node)
case DATA_TYPE_STRUCT:
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, "Doubles and floats are not supported in our subset of C\n");
Expand All @@ -596,6 +613,14 @@ 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)
Expand All @@ -608,6 +633,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
Binary file modified test
Binary file not shown.
11 changes: 9 additions & 2 deletions test.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@

union abc
{
int x;
int y;
};

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

0 comments on commit 0435a04

Please sign in to comment.