refactor: deduplicate repeat parsers alloc logic

Deduplicates the results allocation logic used in MPC_TYPE_MANY
and MPC_TYPE_MANY1 on a `grow_results` function.

This will aid in implementing new repeat parser types. A new one is
neeeded for `sepby1` as discussed on
https://github.com/orangeduck/mpc/pull/165#discussion_r1292878771.
This commit is contained in:
steve-chavez
2023-08-19 19:42:05 -05:00
parent 55f68efeed
commit 21286d5915

34
mpc.c
View File

@@ -1046,12 +1046,26 @@ enum {
#define MPC_MAX_RECURSION_DEPTH 1000
static mpc_result_t *grow_results(mpc_input_t *i, int j, mpc_result_t *results_stk, mpc_result_t *results){
mpc_result_t *tmp_results = results;
if (j == MPC_PARSE_STACK_MIN) {
int results_slots = j + j / 2;
tmp_results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots);
memcpy(tmp_results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN);
} else if (j >= MPC_PARSE_STACK_MIN) {
int results_slots = j + j / 2;
tmp_results = mpc_realloc(i, tmp_results, sizeof(mpc_result_t) * results_slots);
}
return tmp_results;
}
static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_err_t **e, int depth) {
int j = 0, k = 0;
mpc_result_t results_stk[MPC_PARSE_STACK_MIN];
mpc_result_t *results;
int results_slots = MPC_PARSE_STACK_MIN;
if (depth == MPC_MAX_RECURSION_DEPTH)
{
@@ -1176,14 +1190,7 @@ static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_e
while (mpc_parse_run(i, p->data.repeat.x, &results[j], e, depth+1)) {
j++;
if (j == MPC_PARSE_STACK_MIN) {
results_slots = j + j / 2;
results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots);
memcpy(results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN);
} else if (j >= results_slots) {
results_slots = j + j / 2;
results = mpc_realloc(i, results, sizeof(mpc_result_t) * results_slots);
}
results = grow_results(i, j, results_stk, results);
}
*e = mpc_err_merge(i, *e, results[j].error);
@@ -1198,14 +1205,7 @@ static int mpc_parse_run(mpc_input_t *i, mpc_parser_t *p, mpc_result_t *r, mpc_e
while (mpc_parse_run(i, p->data.repeat.x, &results[j], e, depth+1)) {
j++;
if (j == MPC_PARSE_STACK_MIN) {
results_slots = j + j / 2;
results = mpc_malloc(i, sizeof(mpc_result_t) * results_slots);
memcpy(results, results_stk, sizeof(mpc_result_t) * MPC_PARSE_STACK_MIN);
} else if (j >= results_slots) {
results_slots = j + j / 2;
results = mpc_realloc(i, results, sizeof(mpc_result_t) * results_slots);
}
results = grow_results(i, j, results_stk, results);
}
if (j == 0) {