aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2025-05-04 20:22:36 +0900
committernsfisis <nsfisis@gmail.com>2025-05-04 20:22:39 +0900
commit4d9b8c3aac9c89343e9e80a0ee12c5e4b536baef (patch)
tree6b3f629aab1fced2cc1ef49f7bbda95e43f025d8
parent1412b319ce659ef197d2077df47a7a4c96d416fa (diff)
downloadP4Dcc-4d9b8c3aac9c89343e9e80a0ee12c5e4b536baef.tar.gz
P4Dcc-4d9b8c3aac9c89343e9e80a0ee12c5e4b536baef.tar.zst
P4Dcc-4d9b8c3aac9c89343e9e80a0ee12c5e4b536baef.zip
var decl with initial expr
-rw-r--r--main.c24
-rw-r--r--tests/031.sh14
2 files changed, 34 insertions, 4 deletions
diff --git a/main.c b/main.c
index 633ebdb..d57cac3 100644
--- a/main.c
+++ b/main.c
@@ -1099,10 +1099,13 @@ struct AstNode* parse_var_decl(struct Parser* p) {
fatal_error("parse_var_decl: invalid type for variable");
}
char* name = parse_ident(p);
- struct AstNode* decl = ast_new(AST_VAR_DECL);
+
+ struct AstNode* init = NULL;
+ if (peek_token(p)->kind == TK_ASSIGN) {
+ next_token(p);
+ init = parse_expr(p);
+ }
expect(p, TK_SEMICOLON);
- decl->ty = ty;
- decl->name = name;
if (find_lvar(p, name) != -1) {
char buf[1024];
@@ -1113,7 +1116,20 @@ struct AstNode* parse_var_decl(struct Parser* p) {
p->locals[p->n_locals].ty = ty;
p->n_locals = p->n_locals + 1;
- return decl;
+ struct AstNode* ret;
+ if (init) {
+ struct AstNode* lhs = ast_new(AST_LVAR);
+ lhs->name = name;
+ lhs->var_index = p->n_locals - 1;
+ lhs->ty = ty;
+ struct AstNode* assign = ast_new_assign_expr(TK_ASSIGN, lhs, init);
+ assign->ty = ty;
+ ret = ast_new(AST_EXPR_STMT);
+ ret->expr1 = assign;
+ } else {
+ ret = ast_new(AST_VAR_DECL);
+ }
+ return ret;
}
struct AstNode* parse_expr_stmt(struct Parser* p) {
diff --git a/tests/031.sh b/tests/031.sh
new file mode 100644
index 0000000..7747f84
--- /dev/null
+++ b/tests/031.sh
@@ -0,0 +1,14 @@
+set -e
+
+cat <<'EOF' > expected
+42
+EOF
+bash ../../test_diff.sh <<'EOF'
+int printf();
+
+int main() {
+ int a = 42;
+ printf("%d\n", a);
+ return 0;
+}
+EOF