Add "while" statement

This commit is contained in:
Rui Ueyama 2019-08-04 17:24:03 +09:00
parent f5d480f139
commit 1f3eb34f63
5 changed files with 16 additions and 3 deletions

View File

@ -73,7 +73,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

View File

@ -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);

10
parse.c
View File

@ -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) {
@ -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);

View File

@ -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

View File

@ -80,7 +80,7 @@ static int read_punct(char *p) {
}
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]))