From ab8568dcb105d5c34f42d7587bd649e0cb3563b7 Mon Sep 17 00:00:00 2001 From: icst Date: Fri, 21 Jun 2024 20:21:42 -0400 Subject: [PATCH] Pass indication of an error back up to avoid confusing EOFs and errors in some corner cases --- lapis.c | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/lapis.c b/lapis.c index 8fec0c5..ed9ba26 100644 --- a/lapis.c +++ b/lapis.c @@ -103,9 +103,9 @@ void lapis_token_free(lapis_token_t *token) { } } -lapis_node_t *lapis_parse_expr(size_t *nnodes, FILE *f); +lapis_node_t *lapis_parse_expr(int64_t *nnodes, FILE *f); -lapis_token_t *lapis_parse_tokens(size_t *ntokens, FILE *f) { +lapis_token_t *lapis_parse_tokens(int64_t *ntokens, FILE *f) { size_t num_tokens = 0; lapis_token_t *tokens = NULL; @@ -124,11 +124,12 @@ lapis_token_t *lapis_parse_tokens(size_t *ntokens, FILE *f) { while (1) { //puts("++++++++++"); - size_t nnodes; + int64_t nnodes; lapis_node_t *nodes = lapis_parse_expr(&nnodes, f); //puts("----------"); - if ( nodes == 0 ) break; + if ( nnodes < 0 ) goto ERROR; + if ( nnodes == 0 ) break; //printf("%lu: ", nstmts); //lapis_node_print(nodes, nnodes-1); @@ -321,19 +322,27 @@ ERROR: for (size_t n=0; n < num_tokens; n++) lapis_token_free(&tokens[n]); free(tokens); } + *ntokens = -1; return NULL; } -lapis_node_t *lapis_parse_expr(size_t *nnodes, FILE *f) { +lapis_node_t *lapis_parse_expr(int64_t *nnodes, FILE *f) { lapis_token_t *tokens = NULL; int64_t *oper_priorities = NULL; uint8_t *oper_arg_form = NULL; lapis_node_t *nodes = NULL; - size_t ntokens=0; + int64_t ntokens=0; tokens = lapis_parse_tokens(&ntokens, stdin); - if ( tokens == NULL ) goto ERROR; + + if ( ntokens < 0 ) goto ERROR; + + if ( tokens == NULL ) { + // likely EOF; exit cleanly + *nnodes = 0; + return NULL; + } oper_priorities = malloc( ntokens * sizeof(int64_t) ); if ( oper_priorities == NULL ) goto ERROR; @@ -673,13 +682,13 @@ ERROR: if ( oper_arg_form != NULL ) free( oper_arg_form ); if ( nodes != NULL ) free( nodes ); - *nnodes = 0; + *nnodes = -1; return NULL; } int main() { #if 0 - size_t ntokens=0; + int64_t ntokens=0; lapis_token_t *tokens = lapis_parse_tokens(&ntokens, stdin); printf("Tokens (%lu):\n", ntokens); @@ -704,9 +713,14 @@ int main() { #else while (1) { - size_t nnodes; + int64_t nnodes; lapis_node_t *nodes = lapis_parse_expr(&nnodes, stdin); + if ( nnodes < 0 ) { + fputs("Error occured while parsing expression!\n", stderr); + return 1; + } + if ( nnodes == 0 ) break; lapis_node_print(nodes, nnodes-1);