Parse CASE WHEN ... THEN ... [ELSE ...] END */
| 1426 | |
| 1427 | /* Parse CASE WHEN ... THEN ... [ELSE ...] END */ |
| 1428 | static cbm_case_expr_t *parse_case_expr(parser_t *p) { |
| 1429 | /* CASE already consumed */ |
| 1430 | cbm_case_expr_t *kase = calloc(CBM_ALLOC_ONE, sizeof(cbm_case_expr_t)); |
| 1431 | if (!kase) { |
| 1432 | return NULL; |
| 1433 | } |
| 1434 | int bcap = CYP_INIT_CAP4; |
| 1435 | kase->branches = malloc(bcap * sizeof(cbm_case_branch_t)); |
| 1436 | if (!kase->branches) { |
| 1437 | free(kase); |
| 1438 | return NULL; |
| 1439 | } |
| 1440 | |
| 1441 | while (check(p, TOK_WHEN)) { |
| 1442 | advance(p); |
| 1443 | cbm_expr_t *when = parse_or_expr(p); |
| 1444 | if (!expect(p, TOK_THEN)) { |
| 1445 | expr_free(when); |
| 1446 | break; |
| 1447 | } |
| 1448 | const char *then_val = parse_value_literal(p); |
| 1449 | if (kase->branch_count >= bcap) { |
| 1450 | int new_bcap = bcap * PAIR_LEN; |
| 1451 | void *tmp = realloc(kase->branches, new_bcap * sizeof(cbm_case_branch_t)); |
| 1452 | if (!tmp) { |
| 1453 | expr_free(when); |
| 1454 | safe_str_free(&then_val); |
| 1455 | for (int i = 0; i < kase->branch_count; i++) { |
| 1456 | expr_free(kase->branches[i].when_expr); |
| 1457 | safe_str_free(&kase->branches[i].then_val); |
| 1458 | } |
| 1459 | free(kase->branches); |
| 1460 | free(kase); |
| 1461 | return NULL; |
| 1462 | } |
| 1463 | kase->branches = tmp; |
| 1464 | bcap = new_bcap; |
| 1465 | } |
| 1466 | kase->branches[kase->branch_count++] = |
| 1467 | (cbm_case_branch_t){.when_expr = when, .then_val = then_val}; |
| 1468 | } |
| 1469 | |
| 1470 | if (match(p, TOK_ELSE)) { |
| 1471 | kase->else_val = parse_value_literal(p); |
| 1472 | } |
| 1473 | expect(p, TOK_END); |
| 1474 | return kase; |
| 1475 | } |
| 1476 | |
| 1477 | /* Parse a single RETURN/WITH item (aggregate, string func, CASE, or plain var.prop). |
| 1478 | * Returns 0 on success, -1 on error. */ |
no test coverage detected