From 612c680e2ab7e15723a7443e6378e264f7aafc60 Mon Sep 17 00:00:00 2001 From: "Michael D. Lowis" Date: Mon, 25 Jun 2018 14:33:13 -0400 Subject: [PATCH] first attempt at if statement parsing --- example.src | 5 +++++ source/lexer.l | 2 ++ source/parser.c | 31 +++++++++++++++++++++++++++---- source/sclpl.h | 2 +- 4 files changed, 35 insertions(+), 5 deletions(-) diff --git a/example.src b/example.src index c6f51e6..f1885fd 100644 --- a/example.src +++ b/example.src @@ -36,6 +36,11 @@ fun main(args string[]) int { foo(); bar(1); baz(1,2); +# if (123) {} +# if 123 {} +# if (123) {} else {} +# if (123) {} else if {} +# if (123) {} else if {} else {} return bar; } diff --git a/source/lexer.l b/source/lexer.l index 22dc4e9..ce19730 100644 --- a/source/lexer.l +++ b/source/lexer.l @@ -44,6 +44,8 @@ NOSPACE [^ \t\r\n] "struct" { return T_STRUCT; } "union" { return T_UNION; } "return" { return T_RETURN; } +"if" { return T_IF; } +"else" { return T_ELSE; } "(" { return '('; } ")" { return ')'; } diff --git a/source/parser.c b/source/parser.c index ac282d2..16fc84a 100644 --- a/source/parser.c +++ b/source/parser.c @@ -13,6 +13,8 @@ static AST* expression_block(Parser* p); static AST* statement(Parser* p); static AST* expression(Parser* p); static AST* definition(Parser* p, bool constant); +static AST* return_statement(Parser* p); +static AST* if_statement(Parser* p); static AST* func_expr_list(Parser* p); static AST* const_expression(Parser* p); @@ -221,10 +223,10 @@ static AST* statement(Parser* p) { } else { if (matches(p, T_LET) || matches(p, T_VAR)) { definition(p, (peek(p)->type == T_LET)); - } else if (accept(p, T_RETURN)) { - expression(p); - expect(p, ';'); -// } else if (matches(p, T_IF)) { + } else if (matches(p, T_RETURN)) { + return_statement(p); + } else if (matches(p, T_IF)) { + if_statement(p); // } else if (matches(p, T_WHILE)) { // } else if (matches(p, T_FOR)) { // } else if (matches(p, T_DO)) { @@ -264,6 +266,27 @@ static AST* definition(Parser* p, bool constant) { return NULL; } +static AST* return_statement(Parser* p) { + expect(p, T_RETURN); + expression(p); + expect(p, ';'); + return NULL; +} + +static AST* if_statement(Parser* p) { + expect(p, T_IF); + expression(p); + expression_block(p); + if (accept(p, T_ELSE)) { + if (matches(p, T_IF)) { + if_statement(p); + } else { + expression_block(p); + } + } + return NULL; +} + static AST* func_expr_list(Parser* p) { expect(p, '('); if (!matches(p, ')')) { diff --git a/source/sclpl.h b/source/sclpl.h index aa3cea8..069e116 100644 --- a/source/sclpl.h +++ b/source/sclpl.h @@ -42,7 +42,7 @@ void vec_set(vec_t* vec, size_t index, void* data); typedef enum { T_NONE = 0, T_ERROR = 256, T_END_FILE, T_PACKAGE, T_REQUIRES, T_PROVIDES, T_LET, T_VAR, T_FUN, T_TYPE, T_STRUCT, - T_UNION, T_RETURN, + T_UNION, T_RETURN, T_IF, T_ELSE, T_ID, T_CHAR, T_INT, T_FLOAT, T_BOOL, T_STRING, } TokType; -- 2.52.0