Handle nesting and subtraction in reader

This commit is contained in:
2024-10-24 17:35:42 +01:00
parent 79494cd0ba
commit d4855813a2
3 changed files with 76 additions and 7 deletions

View File

@@ -4,10 +4,10 @@
#include <stdbool.h>
typedef enum {
OPERATOR_ADD,
OPERATOR_SUBTRACT,
OPERATOR_MULTIPLY,
OPERATOR_DIVIDE,
OPERATOR_ADD = 0,
OPERATOR_SUBTRACT = 1,
OPERATOR_MULTIPLY = 2,
OPERATOR_DIVIDE = 3,
} operator_t;
struct _expression_t;

View File

@@ -3,6 +3,10 @@
#include <ctype.h>
#include <stddef.h>
static int parse_expression(
memory_pool_t *pool, const char *input, int remaining,
expression_t *out);
static int parse_number(
memory_pool_t *pool, const char *input, int remaining, expression_t *out)
{
@@ -35,14 +39,25 @@ static int parse_application(
remaining -= result;
input += result;
if (remaining <= 0 || *input != '+')
if (remaining <= 0)
return 0;
operator_t operator;
switch (*input) {
case '+':
operator= OPERATOR_ADD;
break;
case '-':
operator= OPERATOR_SUBTRACT;
break;
default:
return 0;
}
++used;
--remaining;
++input;
expression_t *operand1 = allocate_expression(pool);
result = parse_number(pool, input, remaining, operand1);
result = parse_expression(pool, input, remaining, operand1);
if (0 == result)
return 0;
used += result;
@@ -50,7 +65,7 @@ static int parse_application(
input += result;
out->is_number = false;
out->application.operator = OPERATOR_ADD;
out->application.operator= operator;
out->application.operands[0] = operand0;
out->application.operands[1] = operand1;