From 8114d04fb9291469ce2c5b6781776ec5c41b6949 Mon Sep 17 00:00:00 2001 From: Yaossg Date: Sat, 30 Nov 2024 11:19:13 +0800 Subject: [PATCH] comma expr --- README.md | 1 + boot.c | 27 ++++++++++++++++++++------- demo/add.c | 2 +- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 2b3abe6..86a2024 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,7 @@ $ sh boot.sh | `&&` | 逻辑与 | 从左到右 | | || | 逻辑或 | 从左到右 | | `=` | 赋值 | 从右到左 | +| `,` | 逗号 | 从左到右 | - 同级表达式的求值顺序与结合性一致。 - 加减号支持整数之间,指针与整数,指针之间的运算。 diff --git a/boot.c b/boot.c index 913acd2..a56a1ac 100644 --- a/boot.c +++ b/boot.c @@ -22,7 +22,7 @@ const int TOKEN_EOF = 0; const int TOKEN_SEMICOLON = 1; const int TOKEN_ADD = 2; const int TOKEN_MINUS = 3; -const int TOKEN_STAR = 4; +const int TOKEN_MUL = 4; const int TOKEN_DIV = 5; const int TOKEN_REM = 6; const int TOKEN_ASSIGN = 7; @@ -277,7 +277,7 @@ void next_token() { token_type = TOKEN_MINUS; } } else if (ch == '*') { - token_type = TOKEN_STAR; + token_type = TOKEN_MUL; } else if (ch == '/') { int ch2 = getchar(); if (ch2 == '/') { @@ -429,7 +429,7 @@ int parse_type() { int type = token_type & ~TYPE_TOKEN_MASK; next_token(); ignore_const(); - if (token_type == TOKEN_STAR) { + if (token_type == TOKEN_MUL) { next_token(); ignore_const(); type = type | TYPE_PTR_MASK; @@ -1011,6 +1011,8 @@ int addressof(int reg) { int parse_expr(); +int parse_assign_expr(); + int parse_function_call(int id) { const char* name = id_table + id_lut[id]; if (global_marker[id] != MARKER_FUNCTION) { @@ -1029,7 +1031,7 @@ int parse_function_call(int id) { eprintf("too many arguments\n"); exit(1); } - args[arg++] = parse_expr(); + args[arg++] = parse_assign_expr(); next_token(); if (token_type == TOKEN_COMMA) { // continue; @@ -1128,7 +1130,7 @@ int parse_prefix_expr() { exit(1); } return addressof(reg); - } else if (token_type == TOKEN_STAR) { + } else if (token_type == TOKEN_MUL) { int reg = parse_postfix_expr(); int type = reg_type[reg]; if (!(type & TYPE_PTR_MASK)) { @@ -1167,7 +1169,7 @@ int parse_mul_expr() { int lhs = parse_prefix_expr(); while (1) { next_token(); - if (token_type == TOKEN_STAR) { + if (token_type == TOKEN_MUL) { int rhs = parse_prefix_expr(); lhs = asm_rr_arith("mul", lhs, rhs); } else if (token_type == TOKEN_DIV) { @@ -1384,7 +1386,18 @@ int parse_assign_expr() { } int parse_expr() { - return parse_assign_expr(); + int lhs = parse_assign_expr(); + while (1) { + next_token(); + if (token_type == TOKEN_COMMA) { + int rhs = parse_assign_expr(); + lhs = rhs; + } else { + unget_token(); + break; + } + } + return lhs; } void parse_local_variable(int type) { diff --git a/demo/add.c b/demo/add.c index 6c54b5f..f42e07e 100644 --- a/demo/add.c +++ b/demo/add.c @@ -12,6 +12,6 @@ int f1() { int main() { int a[15]; p = a; - for (int i = 0; i < 15; ++i) a[i] = i; + for (int i = 0; i < 15; a[i] = i, ++i); return f1(); } \ No newline at end of file