Add paren support to reader
This commit is contained in:
31
lib/reader.c
31
lib/reader.c
@@ -3,11 +3,12 @@
|
||||
#include <ctype.h>
|
||||
#include <stddef.h>
|
||||
|
||||
static int parse_expression(
|
||||
memory_pool_t *pool, const char *input, int len, expression_t **out);
|
||||
|
||||
static int parse_number(
|
||||
memory_pool_t *pool, const char *input, int len, expression_t **out)
|
||||
{
|
||||
(void)pool;
|
||||
|
||||
int value = 0, used = 0;
|
||||
while (used < len && isdigit(input[used])) {
|
||||
value *= 10;
|
||||
@@ -24,13 +25,27 @@ static int parse_number(
|
||||
return used;
|
||||
}
|
||||
|
||||
static int parse_factor(
|
||||
memory_pool_t *pool, const char *input, int len, expression_t **out)
|
||||
{
|
||||
if (len > 1 && input[0] == '(') {
|
||||
const int result = parse_expression(pool, input + 1, len - 1, out);
|
||||
if (0 == result)
|
||||
return 0;
|
||||
const int used = result + 1;
|
||||
return len >= used && input[used] == ')' ? used + 1 : 0;
|
||||
} else {
|
||||
return parse_number(pool, input, len, out);
|
||||
}
|
||||
}
|
||||
|
||||
static int parse_term(
|
||||
memory_pool_t *pool, const char *input, int len, expression_t **out)
|
||||
{
|
||||
int result, used = 0;
|
||||
|
||||
expression_t *expr;
|
||||
result = parse_number(pool, input, len, &expr);
|
||||
result = parse_factor(pool, input, len, &expr);
|
||||
if (0 >= result)
|
||||
return 0;
|
||||
used += result;
|
||||
@@ -40,15 +55,15 @@ static int parse_term(
|
||||
|
||||
operator_t operator;
|
||||
if ('*' == input[used])
|
||||
operator = OPERATOR_MULTIPLY;
|
||||
operator= OPERATOR_MULTIPLY;
|
||||
else if ('/' == input[used])
|
||||
operator = OPERATOR_DIVIDE;
|
||||
operator= OPERATOR_DIVIDE;
|
||||
else
|
||||
break;
|
||||
++used;
|
||||
|
||||
expression_t *term1;
|
||||
result = parse_number(pool, input + used, len - used, &term1);
|
||||
result = parse_factor(pool, input + used, len - used, &term1);
|
||||
if (0 >= result)
|
||||
return 0;
|
||||
used += result;
|
||||
@@ -80,9 +95,9 @@ static int parse_expression(
|
||||
|
||||
operator_t operator;
|
||||
if ('+' == input[used])
|
||||
operator = OPERATOR_ADD;
|
||||
operator= OPERATOR_ADD;
|
||||
else if ('-' == input[used])
|
||||
operator = OPERATOR_SUBTRACT;
|
||||
operator= OPERATOR_SUBTRACT;
|
||||
else
|
||||
break;
|
||||
++used;
|
||||
|
||||
Reference in New Issue
Block a user