diff --git a/src/tinyexpr.c b/src/tinyexpr.c index 259ed1bc8..a2ef44a77 100755 --- a/src/tinyexpr.c +++ b/src/tinyexpr.c @@ -50,7 +50,7 @@ typedef struct state { const te_variable *lookup; int lookup_len; - int error; + te_error_type_t error; } state; @@ -502,6 +502,7 @@ te_expr *te_compile(const char *expression, const te_variable *variables, int va s.start = s.next = expression; s.lookup = variables; s.lookup_len = var_count; + s.error = TE_ERROR_NONE; next_token(&s); te_expr *root = expr(&s); @@ -510,7 +511,17 @@ te_expr *te_compile(const char *expression, const te_variable *variables, int va te_free(root); if (error) { error->position = (s.next - s.start) + 1; - error->type = s.error; + if (s.error != TE_ERROR_NONE) { + error->type = s.error; + } else { + // If we're not at the end but there's no error, then that means we have a superfluous + // token that we have no idea what to do with. + // This occurs in e.g. `2 + 2 4` - the "4" is just not part of the expression. + // We can report either "too many arguments" or "expected operator", but the operator + // should be reported between the "2" and the "4". + // So we report TOO_MANY_ARGS on the "4". + error->type = TE_ERROR_TOO_MANY_ARGS; + } } return 0; } else { diff --git a/src/tinyexpr.h b/src/tinyexpr.h index 92319d595..06d324379 100644 --- a/src/tinyexpr.h +++ b/src/tinyexpr.h @@ -33,7 +33,7 @@ extern "C" { #endif - enum { + typedef enum { TE_ERROR_NONE = 0, TE_ERROR_UNKNOWN_VARIABLE = 1, TE_ERROR_MISSING_CLOSING_PAREN = 2, @@ -42,9 +42,7 @@ extern "C" { TE_ERROR_TOO_MANY_ARGS = 5, TE_ERROR_MISSING_OPERATOR = 6, TE_ERROR_UNKNOWN = 7 - }; - typedef int te_error_type_t; - + } te_error_type_t; typedef struct te_error_t { diff --git a/tests/math.err b/tests/math.err index 323287cb6..1d529b43d 100644 --- a/tests/math.err +++ b/tests/math.err @@ -19,3 +19,6 @@ math: Error: Expression is bogus math: Error: Too few arguments 'sin()' ^ +math: Error: Too many arguments +'2 + 2 4' + ^ diff --git a/tests/math.in b/tests/math.in index e3d92c212..ff63cc0a5 100644 --- a/tests/math.in +++ b/tests/math.in @@ -28,3 +28,4 @@ not math '2 - ' not math 'ncr(1)' not math 'max()' not math 'sin()' +not math '2 + 2 4'