Skip to content

Commit

Permalink
Add "while" statement
Browse files Browse the repository at this point in the history
  • Loading branch information
rui314 committed Sep 27, 2020
1 parent 3493ccc commit 773115a
Show file tree
Hide file tree
Showing 5 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion chibicc.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ typedef enum {
ND_ASSIGN, // =
ND_RETURN, // "return"
ND_IF, // "if"
ND_FOR, // "for"
ND_FOR, // "for" or "while"
ND_BLOCK, // { ... }
ND_EXPR_STMT, // Expression statement
ND_VAR, // Variable
Expand Down
3 changes: 2 additions & 1 deletion codegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ static void gen_stmt(Node *node) {
}
case ND_FOR: {
int c = count();
gen_stmt(node->init);
if (node->init)
gen_stmt(node->init);
printf(".L.begin.%d:\n", c);
if (node->cond) {
gen_expr(node->cond);
Expand Down
10 changes: 10 additions & 0 deletions parse.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ static Obj *new_lvar(char *name) {
// stmt = "return" expr ";"
// | "if" "(" expr ")" stmt ("else" stmt)?
// | "for" "(" expr-stmt expr? ";" expr? ")" stmt
// | "while" "(" expr ")" stmt
// | "{" compound-stmt
// | expr-stmt
static Node *stmt(Token **rest, Token *tok) {
Expand Down Expand Up @@ -104,6 +105,15 @@ static Node *stmt(Token **rest, Token *tok) {
return node;
}

if (equal(tok, "while")) {
Node *node = new_node(ND_FOR);
tok = skip(tok->next, "(");
node->cond = expr(&tok, tok);
tok = skip(tok, ")");
node->then = stmt(rest, tok);
return node;
}

if (equal(tok, "{"))
return compound_stmt(rest, tok->next);

Expand Down
2 changes: 2 additions & 0 deletions test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,6 @@ assert 3 '{ if (1) { 1; 2; return 3; } else { return 4; } }'
assert 55 '{ i=0; j=0; for (i=0; i<=10; i=i+1) j=i+j; return j; }'
assert 3 '{ for (;;) {return 3;} return 5; }'

assert 10 '{ i=0; while(i<10) { i=i+1; } return i; }'

echo OK
2 changes: 1 addition & 1 deletion tokenize.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ static bool is_ident2(char c) {
}

static bool is_keyword(Token *tok) {
static char *kw[] = {"return", "if", "else", "for"};
static char *kw[] = {"return", "if", "else", "for", "while"};

for (int i = 0; i < sizeof(kw) / sizeof(*kw); i++)
if (equal(tok, kw[i]))
Expand Down

0 comments on commit 773115a

Please sign in to comment.