Skip to content

Commit 79838e5

Browse files
Liviarodrigues1BeyondMagic
authored andcommitted
feat(lexer/parser): reconhecer sintaxe de if/else e gerar nós na AST
1 parent def4b8e commit 79838e5

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/lexer.l

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@ static long long yy_parse_char_literal(const char *src)
157157
"return" { return RETURN; }
158158
"while" { return WHILE; }
159159
"for" { return FOR; }
160+
"if" { return IF; }
161+
"else" { return ELSE; }
160162
"true" { return TRUE; }
161163
"false" { return FALSE; }
162164
"\[" { return LBRACKET; }

src/parser.y

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ static void parser_error_cleanup(AstProgram **out_program);
5050
%token KW_INT KW_CHAR KW_FLOAT KW_BOOL KW_VOID
5151
%token RETURN
5252
%token WHILE FOR
53+
%token IF ELSE
5354
%token TRUE FALSE
5455
%token PLUS MINUS TIMES DIVIDE MOD
5556
%token EQ NEQ LT LE GT GE
@@ -74,7 +75,7 @@ static void parser_error_cleanup(AstProgram **out_program);
7475
%type <param> parameter
7576
%type <param_list> parameter_list_nonempty parameter_list_opt
7677
%type <block> block
77-
%type <stmt> statement compound_statement declaration_statement assignment_statement return_statement expression_statement while_statement for_statement for_init_statement_opt for_post_statement_opt
78+
%type <stmt> statement compound_statement declaration_statement assignment_statement return_statement expression_statement while_statement for_statement if_statement for_init_statement_opt for_post_statement_opt
7879
%type <stmt_list> optional_statement_list statement_list
7980
%type <expr> expression logical_or_expression logical_and_expression equality_expression relational_expression additive_expression multiplicative_expression unary_expression postfix_expression primary_expression array_initializer expression_opt
8081
%type <expr_list> argument_expression_list argument_expression_list_opt initializer_list initializer_list_opt
@@ -189,8 +190,9 @@ statement
189190
| assignment_statement
190191
| return_statement
191192
| expression_statement
192-
| while_statement
193-
| for_statement
193+
| while_statement
194+
| for_statement
195+
| if_statement
194196
;
195197

196198
compound_statement
@@ -262,6 +264,17 @@ for_statement
262264
}
263265
;
264266

267+
if_statement
268+
: IF LPAREN expression RPAREN statement
269+
{
270+
$$ = ast_stmt_make_if($3, $5, NULL);
271+
}
272+
| IF LPAREN expression RPAREN statement ELSE statement
273+
{
274+
$$ = ast_stmt_make_if($3, $5, $7);
275+
}
276+
;
277+
265278
for_init_statement_opt
266279
: type_specifier IDENT ASSIGN expression
267280
{
@@ -578,4 +591,4 @@ AstProgram *c2lua_parse(FILE *input)
578591
return NULL;
579592
}
580593
return program;
581-
}
594+
}

0 commit comments

Comments
 (0)