Add static local variables

This commit is contained in:
Rui Ueyama 2019-08-21 21:05:01 +09:00
parent 1fb5091f75
commit a4a0a84848
2 changed files with 24 additions and 1 deletions

15
parse.c
View File

@ -1074,6 +1074,19 @@ static Node *declaration(void) {
if (ty->kind == TY_VOID)
error_tok(tok, "variable declared void");
if (sclass == STATIC) {
// static local variable
Var *var = new_gvar(new_label(), ty, true);
push_scope(name)->var = var;
if (consume("="))
var->initializer = gvar_initializer(ty);
else if (ty->is_incomplete)
error_tok(tok, "incomplete type");
consume(";");
return new_node(ND_NULL, tok);
}
Var *var = new_lvar(name, ty);
if (consume(";")) {
@ -1336,7 +1349,7 @@ static long eval2(Node *node, Var **var) {
case ND_NUM:
return node->val;
case ND_ADDR:
if (!var || *var || node->lhs->kind != ND_VAR)
if (!var || *var || node->lhs->kind != ND_VAR || node->lhs->var->is_local)
error_tok(node->tok, "invalid initializer");
*var = node->lhs->var;
return 0;

10
tests
View File

@ -107,6 +107,12 @@ int param_decay(int x[]) { return x[0]; }
void voidfn(void) {}
int counter() {
static int i;
static int j = 1+1;
return i++ + j++;
}
int main() {
assert(8, ({ int a=3; int z=5; a+z; }), "int a=3; int z=5; a+z;");
@ -642,6 +648,10 @@ int main() {
assert(1, _Alignof(struct {char a; char b;}[2]), "_Alignof(struct {char a; char b;}[2])");
assert(8, _Alignof(struct {char a; long b;}[2]), "_Alignof(struct {char a; long b;}[2])");
assert(2, counter(), "counter()");
assert(4, counter(), "counter()");
assert(6, counter(), "counter()");
printf("OK\n");
return 0;
}