From 9f54c3552b43f496049963ffd755844d37b39f9c Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Thu, 24 Oct 2024 20:58:08 +0100 Subject: [PATCH] Handle NULL result from read_expression() in REPL --- lib/repl.c | 7 +++++++ tests/repl_tests.c | 22 ++++++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/lib/repl.c b/lib/repl.c index ee21226..18dad2f 100644 --- a/lib/repl.c +++ b/lib/repl.c @@ -1,6 +1,7 @@ #include "repl.h" #include +#include void init_repl(repl_t *repl) { @@ -19,6 +20,12 @@ bool step_repl(repl_t *repl) repl->line_buffer[len] = (char)byte; } const expression_t *e = repl->read(&repl->pool, repl->line_buffer, len); + if (NULL == e) { + const char *msg = "Invalid expression\n"; + repl->print(msg, strlen(msg)); + return true; + } + const int result = repl->evaluate(e); const int result_len = snprintf( repl->result_buffer, REPL_RESULT_BUFFER_SIZE, "%d\n", result); diff --git a/tests/repl_tests.c b/tests/repl_tests.c index 73cdec0..1306ba2 100644 --- a/tests/repl_tests.c +++ b/tests/repl_tests.c @@ -20,6 +20,13 @@ static bool print_called; static const char *print_output; static int print_len; +static void reset_fixtures(void) +{ + read_called = false; + evaluate_called = false; + print_called = false; +} + static int test_get_byte(void) { if (0 == input_len) @@ -72,6 +79,7 @@ static void set_up_valid_state(void) static void read_is_called_on_first_line_line_in_input(void) { + reset_fixtures(); set_up_valid_state(); step_repl(&repl); ASSERT_TRUE(read_called); @@ -81,6 +89,7 @@ static void read_is_called_on_first_line_line_in_input(void) static void read_result_is_passed_to_evaluate(void) { + reset_fixtures(); set_up_valid_state(); step_repl(&repl); ASSERT_TRUE(evaluate_called); @@ -90,6 +99,7 @@ static void read_result_is_passed_to_evaluate(void) static void result_of_evaluation_is_printed_with_a_newline(void) { + reset_fixtures(); set_up_valid_state(); step_repl(&repl); ASSERT_TRUE(print_called); @@ -99,6 +109,7 @@ static void result_of_evaluation_is_printed_with_a_newline(void) static void true_is_returned_on_successful_step(void) { + reset_fixtures(); set_up_valid_state(); const bool result = step_repl(&repl); ASSERT_TRUE(result); @@ -106,12 +117,22 @@ static void true_is_returned_on_successful_step(void) static void false_is_returned_on_end_of_input(void) { + reset_fixtures(); set_up_valid_state(); input_len = 0; const bool result = step_repl(&repl); ASSERT_FALSE(result); } +static void evaluate_is_not_called_if_read_returns_null(void) +{ + reset_fixtures(); + set_up_valid_state(); + read_result = NULL; + step_repl(&repl); + ASSERT_FALSE(evaluate_called); +} + int main(void) { TESTING_BEGIN(); @@ -120,5 +141,6 @@ int main(void) RUN_TEST(result_of_evaluation_is_printed_with_a_newline); RUN_TEST(true_is_returned_on_successful_step); RUN_TEST(false_is_returned_on_end_of_input); + RUN_TEST(evaluate_is_not_called_if_read_returns_null); TESTING_END(); }