Skip to content

Commit

Permalink
Add [] operator
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Sep 28, 2020
1 parent 5b2d571 commit 75fbd3d
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
20 changes: 18 additions & 2 deletions parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ static Node *equality(Token **rest, Token *tok);
static Node *relational(Token **rest, Token *tok);
static Node *add(Token **rest, Token *tok);
static Node *mul(Token **rest, Token *tok);
static Node *postfix(Token **rest, Token *tok);
static Node *unary(Token **rest, Token *tok);
static Node *primary(Token **rest, Token *tok);

Expand Down Expand Up @@ -446,7 +447,7 @@ static Node *mul(Token **rest, Token *tok) {
}

// unary = ("+" | "-" | "*" | "&") unary
// | primary
// | postfix
static Node *unary(Token **rest, Token *tok) {
if (equal(tok, "+"))
return unary(rest, tok->next);
Expand All @@ -460,7 +461,22 @@ static Node *unary(Token **rest, Token *tok) {
if (equal(tok, "*"))
return new_unary(ND_DEREF, unary(rest, tok->next), tok);

return primary(rest, tok);
return postfix(rest, tok);
}

// postfix = primary ("[" expr "]")*
static Node *postfix(Token **rest, Token *tok) {
Node *node = primary(&tok, tok);

while (equal(tok, "[")) {
// x[y] is short for *(x+y)
Token *start = tok;
Node *idx = expr(&tok, tok->next);
tok = skip(tok, "]");
node = new_unary(ND_DEREF, new_add(node, idx, start), start);
}
*rest = tok;
return node;
}

// funcall = ident "(" (assign ("," assign)*)? ")"
Expand Down
13 changes: 13 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -125,4 +125,17 @@ assert 3 'int main() { int x[2][3]; int *y=x; *(y+3)=3; return **(x+1); }'
assert 4 'int main() { int x[2][3]; int *y=x; *(y+4)=4; return *(*(x+1)+1); }'
assert 5 'int main() { int x[2][3]; int *y=x; *(y+5)=5; return *(*(x+1)+2); }'

assert 3 'int main() { int x[3]; *x=3; x[1]=4; x[2]=5; return *x; }'
assert 4 'int main() { int x[3]; *x=3; x[1]=4; x[2]=5; return *(x+1); }'
assert 5 'int main() { int x[3]; *x=3; x[1]=4; x[2]=5; return *(x+2); }'
assert 5 'int main() { int x[3]; *x=3; x[1]=4; x[2]=5; return *(x+2); }'
assert 5 'int main() { int x[3]; *x=3; x[1]=4; 2[x]=5; return *(x+2); }'

assert 0 'int main() { int x[2][3]; int *y=x; y[0]=0; return x[0][0]; }'
assert 1 'int main() { int x[2][3]; int *y=x; y[1]=1; return x[0][1]; }'
assert 2 'int main() { int x[2][3]; int *y=x; y[2]=2; return x[0][2]; }'
assert 3 'int main() { int x[2][3]; int *y=x; y[3]=3; return x[1][0]; }'
assert 4 'int main() { int x[2][3]; int *y=x; y[4]=4; return x[1][1]; }'
assert 5 'int main() { int x[2][3]; int *y=x; y[5]=5; return x[1][2]; }'

echo OK

0 comments on commit 75fbd3d

Please sign in to comment.