Parse CASE WHEN ... THEN ... [ELSE ...] END */
| 1262 | |
| 1263 | /* Parse CASE WHEN ... THEN ... [ELSE ...] END */ |
| 1264 | static cbm_case_expr_t *parse_case_expr(parser_t *p) { |
| 1265 | /* CASE already consumed */ |
| 1266 | cbm_case_expr_t *kase = calloc(CBM_ALLOC_ONE, sizeof(cbm_case_expr_t)); |
| 1267 | if (!kase) { |
| 1268 | return NULL; |
| 1269 | } |
| 1270 | int bcap = CYP_INIT_CAP4; |
| 1271 | kase->branches = malloc(bcap * sizeof(cbm_case_branch_t)); |
| 1272 | if (!kase->branches) { |
| 1273 | free(kase); |
| 1274 | return NULL; |
| 1275 | } |
| 1276 | |
| 1277 | while (check(p, TOK_WHEN)) { |
| 1278 | advance(p); |
| 1279 | cbm_expr_t *when = parse_or_expr(p); |
| 1280 | if (!expect(p, TOK_THEN)) { |
| 1281 | expr_free(when); |
| 1282 | break; |
| 1283 | } |
| 1284 | const char *then_val = parse_value_literal(p); |
| 1285 | if (kase->branch_count >= bcap) { |
| 1286 | int new_bcap = bcap * PAIR_LEN; |
| 1287 | void *tmp = realloc(kase->branches, new_bcap * sizeof(cbm_case_branch_t)); |
| 1288 | if (!tmp) { |
| 1289 | expr_free(when); |
| 1290 | safe_str_free(&then_val); |
| 1291 | for (int i = 0; i < kase->branch_count; i++) { |
| 1292 | expr_free(kase->branches[i].when_expr); |
| 1293 | safe_str_free(&kase->branches[i].then_val); |
| 1294 | } |
| 1295 | free(kase->branches); |
| 1296 | free(kase); |
| 1297 | return NULL; |
| 1298 | } |
| 1299 | kase->branches = tmp; |
| 1300 | bcap = new_bcap; |
| 1301 | } |
| 1302 | kase->branches[kase->branch_count++] = |
| 1303 | (cbm_case_branch_t){.when_expr = when, .then_val = then_val}; |
| 1304 | } |
| 1305 | |
| 1306 | if (match(p, TOK_ELSE)) { |
| 1307 | kase->else_val = parse_value_literal(p); |
| 1308 | } |
| 1309 | expect(p, TOK_END); |
| 1310 | return kase; |
| 1311 | } |
| 1312 | |
| 1313 | /* Parse a single RETURN/WITH item (aggregate, string func, CASE, or plain var.prop). |
| 1314 | * Returns 0 on success, -1 on error. */ |
no test coverage detected