[math] Better error for 2 + 2 4

This now reports "TOO_MANY_ARGS" instead of no error (and triggering
an assertion).

We might want to add a new error type or report the missing operator
before, but this is okay for now.
This commit is contained in:
Fabian Homborg 2018-02-26 14:00:29 +01:00
parent 6a38eb4f7d
commit f60e1549a9
4 changed files with 19 additions and 6 deletions

View file

@ -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 {

View file

@ -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 {

View file

@ -19,3 +19,6 @@ math: Error: Expression is bogus
math: Error: Too few arguments
'sin()'
^
math: Error: Too many arguments
'2 + 2 4'
^

View file

@ -28,3 +28,4 @@ not math '2 - '
not math 'ncr(1)'
not math 'max()'
not math 'sin()'
not math '2 + 2 4'