implemented variable parsing
This commit is contained in:
parent
9302e4710d
commit
d0d750f059
4 changed files with 36 additions and 5 deletions
3
lc.c
3
lc.c
|
|
@ -138,7 +138,8 @@ void print_ast(ast_node *node, int depth) {
|
|||
printf("IfStmt (Fields missing in struct)\n");
|
||||
break;
|
||||
case NODE_VAR_DECL:
|
||||
printf("VarDecl (Fields missing in struct)\n");
|
||||
printf("VarDecl: %.*s: %.*s\n", (int)node->expr.var_decl.name_len, node->expr.var_decl.name, (int)node->expr.var_decl.type_len, node->expr.var_decl.type);
|
||||
print_ast(node->expr.var_decl.value, depth + 1);
|
||||
break;
|
||||
case NODE_FUNCTION:
|
||||
printf("FunctionDef (Fields missing in struct)\n");
|
||||
|
|
|
|||
27
parser.c
27
parser.c
|
|
@ -448,7 +448,7 @@ ast_node *parse_expression(parser *p)
|
|||
return node;
|
||||
}
|
||||
|
||||
if ((p->tokens->type >= TOKEN_DOUBLE_EQ && p->tokens->type <= TOKEN_NOT_EQ) || (p->tokens->type >= TOKEN_LSHIFT_EQ && p->tokens->type <= TOKEN_DOUBLE_AND))
|
||||
if (p->tokens && ((p->tokens->type >= TOKEN_DOUBLE_EQ && p->tokens->type <= TOKEN_NOT_EQ) || (p->tokens->type >= TOKEN_LSHIFT_EQ && p->tokens->type <= TOKEN_DOUBLE_AND)))
|
||||
{
|
||||
binary_op op;
|
||||
switch (p->tokens->type)
|
||||
|
|
@ -777,6 +777,31 @@ static ast_node *parse_statement(parser *p)
|
|||
return parse_while(p);
|
||||
}
|
||||
}
|
||||
else if (match_peek(p, TOKEN_IDENTIFIER) && p->tokens->next && p->tokens->next->type == TOKEN_IDENTIFIER)
|
||||
{
|
||||
/* Variable declaration. */
|
||||
ast_node *node = arena_alloc(p->allocator, sizeof(ast_node));
|
||||
node->type = NODE_VAR_DECL;
|
||||
node->expr.var_decl.type = p->tokens->lexeme;
|
||||
node->expr.var_decl.type_len = p->tokens->lexeme_len;
|
||||
advance(p);
|
||||
node->expr.var_decl.name = p->tokens->lexeme;
|
||||
node->expr.var_decl.name_len = p->tokens->lexeme_len;
|
||||
advance(p);
|
||||
if (match(p, TOKEN_EQ)) {
|
||||
node->expr.var_decl.value = parse_expression(p);
|
||||
} else {
|
||||
node->expr.var_decl.value = NULL;
|
||||
}
|
||||
|
||||
if (!match(p, TOKEN_SEMICOLON))
|
||||
{
|
||||
error(p, "expected `;` after statement.");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
else
|
||||
{
|
||||
ast_node *expr = parse_expression(p);
|
||||
|
|
|
|||
7
parser.h
7
parser.h
|
|
@ -170,6 +170,13 @@ typedef struct _ast_node {
|
|||
struct _ast_node **statements;
|
||||
usize stmt_len;
|
||||
} compound;
|
||||
struct {
|
||||
struct _ast_node *value;
|
||||
char *name;
|
||||
usize name_len;
|
||||
char *type;
|
||||
usize type_len;
|
||||
} var_decl;
|
||||
} expr;
|
||||
} ast_node;
|
||||
|
||||
|
|
|
|||
4
test.c
4
test.c
|
|
@ -1,3 +1 @@
|
|||
loop i != 0 {
|
||||
printf("%d\n", i);
|
||||
}
|
||||
u32 a = 3;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue