mirror of
https://github.com/rui314/chibicc
synced 2024-11-21 22:01:40 +03:00
Add "while" statement
This commit is contained in:
parent
f5d480f139
commit
1f3eb34f63
@ -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
|
||||
|
@ -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
10
parse.c
@ -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);
|
||||
|
||||
|
2
test.sh
2
test.sh
@ -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
|
||||
|
@ -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]))
|
||||
|
Loading…
Reference in New Issue
Block a user