parser: report input read errors

In qmi_parse(), the main loop accepts tokens until it sees one with
id 0.  If an unrecognized (or unexpected) token is encountered, it
reports an error and exits using yyerror().

Normally, input() returns the next character to be processed while
parsing.  If the read() call in input() encounters an error, input()
will return -1 instead (which happens to be EOF).

The only caller of input() is yylex().  It recognizes tokens
comprised of alphanumeric characters and '_'.  If input() returns
any other value, it uses that value as the token identifier.  And in
particular, if input() returns -1, that will be the value stored in
the id field of the token structure yylex() returns.

So, back to the top, qmi_parse() will not consider -1 a valid token
id, and will report the read error as an "unexpected symbol".

Instead, report a read error immediately when it occurs and exit.
Move the definition of yyerror() earlier in the source file so it
can be called from yylex() (and all other functions) without needing
a declaration.

Signed-off-by: Alex Elder <elder@linaro.org>
Message-Id: <20211001232338.769309-8-elder@linaro.org>
Signed-off-by: Bjorn Andersson <bjorn.andersson@linaro.org>
This commit is contained in:
Alex Elder 2021-10-01 18:23:11 -05:00 committed by Bjorn Andersson
parent 53dc3278af
commit 28c48a5e18

View File

@ -1,6 +1,7 @@
#include <assert.h>
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
@ -42,6 +43,21 @@ static unsigned scratch_pos;
static int yyline = 1;
static void yyerror(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf("parse error on line %u:\n\t", yyline);
vprintf(fmt, ap);
printf("\n");
va_end(ap);
exit(1);
}
static int input()
{
static char input_buf[128];
@ -61,8 +77,11 @@ static int input()
}
ret = read(0, input_buf, sizeof(input_buf));
if (ret <= 0)
return ret;
if (ret <= 0) {
if (ret < 0)
yyerror("read error: %s", strerror(errno));
return 0; /* End of input */
}
input_pos = 0;
input_len = ret;
@ -181,21 +200,6 @@ static struct token yylex()
static struct token curr_token;
static void yyerror(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
printf("parse error on line %u:\n\t", yyline);
vprintf(fmt, ap);
printf("\n");
va_end(ap);
exit(1);
}
static void token_init(void)
{
curr_token = yylex();