Skip to content

Commit

Permalink
implement array constructors. int x[10] = {1, 2, 3}; add test.
Browse files Browse the repository at this point in the history
  • Loading branch information
kjs committed Jun 16, 2012
1 parent a83c607 commit 111b5a1
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 3 deletions.
25 changes: 24 additions & 1 deletion src/gencode.c
Expand Up @@ -1663,7 +1663,7 @@ gencode_switch(M1_compiler *comp, m1_switch *expr) {

static void
gencode_var(M1_compiler *comp, m1_var *v) {
if (v->init) { /* generate code for initializations. */
if (v->num_elems == 1 && v->init) { /* generate code for initializations. */
m1_reg reg;
m1_symbol *sym;

Expand Down Expand Up @@ -1725,6 +1725,29 @@ gencode_var(M1_compiler *comp, m1_var *v) {

fprintf(OUT, "\tgc_alloc\tI%d, I%d, 0\n", sym->regno, memsize.no);
free_reg(comp, memsize);

if (v->init) { /* initialize arrays. */
m1_expression *iter = v->init;
m1_reg index = alloc_reg(comp, VAL_INT);
m1_reg one = alloc_reg(comp, VAL_INT);

fprintf(OUT, "\tset_imm\tI%d, 0, 0\n", index.no); /* index register. */
fprintf(OUT, "\tset_imm\tI%d, 0, 1\n", one.no); /* to hold constant 1. */

while (iter != NULL) {
/* evaluate expression. */
gencode_expr(comp, iter);
/* get register holding result. */
m1_reg res = popreg(comp->regstack);
/* and assign to array. */
fprintf(OUT, "\tset_ref\tI%d, I%d, %c%d\n", sym->regno, index.no, reg_chars[(int)res.type], res.no);
fprintf(OUT, "\tadd_i\tI%d, I%d, I%d\n", index.no, index.no, one.no); /* increment index. */

iter = iter->next;
}
free_reg(comp, index);
free_reg(comp, one);
}
}

}
Expand Down
15 changes: 13 additions & 2 deletions src/m1.y
Expand Up @@ -214,6 +214,8 @@ yyerror(yyscan_t yyscanner, M1_compiler *comp, char *str) {
opt_array_init
opt_ret_expr
expr_list
const_list


%type <blck> open_block

Expand Down Expand Up @@ -936,12 +938,21 @@ nullexpr : "null"
;

arrayconstructor: '{' const_list '}'
{ $$ = NULL; }
{ $$ = $2; }
;


const_list : constexpr
const_list : constexpr
| const_list ',' constexpr
{
m1_expression *iter = $1;
/* need to link in correct order; find end of list. */
while (iter->next != NULL)
iter = iter->next;

iter->next = $3;
$$ = $1;
}
;

unexpr : '-' expression
Expand Down
13 changes: 13 additions & 0 deletions t/arrayconstructor.m1
@@ -0,0 +1,13 @@
void main() {

int x[10] = {1, 2, 3};
print("1..3\n");

print("ok ");
print(x[0]);
print("\nok ");
print(x[1]);
print("\nok ");
print(x[2]);
print("\n");
}

0 comments on commit 111b5a1

Please sign in to comment.