Modify grammar slighly to simplify parse tree
This commit is contained in:
41
lib/parser.c
41
lib/parser.c
@@ -10,6 +10,7 @@
|
||||
|
||||
#define CLASS_START_CAPACITY 4
|
||||
#define SEQUENCE_START_CAPACITY 8
|
||||
#define PARSE_TREE_START_CAPACITY 4
|
||||
|
||||
static bool is_special(char c)
|
||||
{
|
||||
@@ -182,23 +183,37 @@ int parse_expr(const char *input, int rem, parse_tree_t *out)
|
||||
{
|
||||
int result, used = 0;
|
||||
|
||||
result = parse_sequence(input + used, rem - used, &out->sequence);
|
||||
out->count = 0;
|
||||
out->capacity = PARSE_TREE_START_CAPACITY;
|
||||
out->alternatives = malloc(out->capacity * sizeof(sequence_t));
|
||||
if (NULL == out->alternatives)
|
||||
return -1;
|
||||
|
||||
result = parse_sequence(input + used, rem - used, &out->alternatives[0]);
|
||||
if (result < 0)
|
||||
return -1;
|
||||
++out->count;
|
||||
used += result;
|
||||
|
||||
if (used < rem && '|' == input[used]) {
|
||||
while (used < rem) {
|
||||
if ('|' != input[used])
|
||||
break;
|
||||
++used;
|
||||
|
||||
out->alternative = malloc(sizeof(parse_tree_t));
|
||||
if (NULL == out->alternative)
|
||||
return -1;
|
||||
result = parse_expr(input + used, rem - used, out->alternative);
|
||||
if (out->count >= out->capacity) {
|
||||
out->capacity *= 2;
|
||||
out->alternatives = realloc(
|
||||
out->alternatives, out->capacity * sizeof(sequence_t));
|
||||
if (NULL == out->alternatives)
|
||||
return -1;
|
||||
}
|
||||
|
||||
result = parse_sequence(
|
||||
input + used, rem - used, &out->alternatives[out->count]);
|
||||
if (result < 0)
|
||||
return -1;
|
||||
break;
|
||||
++out->count;
|
||||
used += result;
|
||||
} else {
|
||||
out->alternative = NULL;
|
||||
}
|
||||
|
||||
return used;
|
||||
@@ -232,9 +247,9 @@ static void sequence_free(sequence_t *s)
|
||||
|
||||
void parse_tree_free_children(parse_tree_t *t)
|
||||
{
|
||||
sequence_free(&t->sequence);
|
||||
if (NULL != t->alternative) {
|
||||
parse_tree_free_children(t->alternative);
|
||||
free(t->alternative);
|
||||
if (NULL != t->alternatives) {
|
||||
for (int i = 0; i < t->count; ++i)
|
||||
sequence_free(&t->alternatives[i]);
|
||||
free(t->alternatives);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,8 +35,8 @@ typedef struct {
|
||||
} sequence_t;
|
||||
|
||||
typedef struct _parse_tree {
|
||||
sequence_t sequence;
|
||||
struct _parse_tree *alternative;
|
||||
int count, capacity;
|
||||
sequence_t *alternatives;
|
||||
} parse_tree_t;
|
||||
|
||||
typedef struct _term {
|
||||
|
||||
Reference in New Issue
Block a user