From 6313027d07c510dacf859ed3005a8c48f6edbf44 Mon Sep 17 00:00:00 2001 From: Karma Riuk Date: Tue, 15 Jul 2025 01:43:22 +0200 Subject: [PATCH] reformulated the parsing of the parameters and made it memory safe --- src/parser/parser.cpp | 37 ++++++++++++++++++++++++++++--------- test/parser/function.cpp | 6 +++--- 2 files changed, 31 insertions(+), 12 deletions(-) diff --git a/src/parser/parser.cpp b/src/parser/parser.cpp index b0a831e..984ab2a 100644 --- a/src/parser/parser.cpp +++ b/src/parser/parser.cpp @@ -248,23 +248,42 @@ namespace parser { ); }; + static void free_vec(std::vector v) { + for (auto& e : v) + delete e; + } + std::vector parser::parse_function_parameters() { - std::vector ret; - while (next.type != token::type::RPAREN - && expect_next(token::type::IDENTIFIER)) { - ret.push_back(parse_identifier()); - if (next.type == token::type::RPAREN) - break; - if (!expect_next(token::type::COMMA)) - return {}; + if (next.type == token::type::RPAREN) { + next_token(); + return {}; // no params } + + std::vector ret; + if (!expect_next(token::type::IDENTIFIER)) + return {}; + ret.push_back(parse_identifier()); + + while (next.type == token::type::COMMA) { + next_token(); + if (!expect_next(token::type::IDENTIFIER)) { + free_vec(ret); + return {}; + } + ret.push_back(parse_identifier()); + } + if (current.type == token::type::COMMA && next.type == token::type::RPAREN) { next_error(token::type::IDENTIFIER); + free_vec(ret); return {}; } - if (!expect_next(token::type::RPAREN)) + + if (!expect_next(token::type::RPAREN)) { + free_vec(ret); return {}; + } return ret; } diff --git a/test/parser/function.cpp b/test/parser/function.cpp index 2598cf8..bd0971b 100644 --- a/test/parser/function.cpp +++ b/test/parser/function.cpp @@ -53,13 +53,13 @@ TEST_SUITE("Parser: function") { ); } - SUBCASE("Missing comma with no closing paren one param") { - test_failing_parsing("fn (x { return 2; }", {token::type::COMMA}); + SUBCASE("Missing closing paren one param") { + test_failing_parsing("fn (x { return 2; }", {token::type::RPAREN}); } SUBCASE("Missing closing paren two params") { test_failing_parsing( "fn (x, y { return 2; }", - {token::type::COMMA} + {token::type::RPAREN} ); }