Pass indication of an error back up to avoid confusing EOFs and errors in some corner cases

This commit is contained in:
icst 2024-06-21 20:21:42 -04:00
parent 0ab9807349
commit ab8568dcb1

34
lapis.c
View file

@ -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);