| 272 | } |
| 273 | |
| 274 | index_t ParseContext::parse_typeuse() { |
| 275 | index_t typeidx = 0; |
| 276 | bool has_explicit_type = false; |
| 277 | |
| 278 | // Optional '(' 'type' typeidx ')' |
| 279 | if (tok_.peek().type == TokenType::LParen && |
| 280 | tok_.peek2().type == TokenType::Keyword && tok_.peek2().text == "type") { |
| 281 | tok_.consume(); tok_.consume(); // '(' 'type' |
| 282 | typeidx = parse_typeidx(); |
| 283 | tok_.expect(TokenType::RParen); |
| 284 | has_explicit_type = true; |
| 285 | } |
| 286 | |
| 287 | if (!has_explicit_type) { |
| 288 | typeidx = types_.size(); |
| 289 | types_.emplace_back(); // placeholder empty type |
| 290 | } |
| 291 | |
| 292 | // Check for params/results |
| 293 | bool has_params_results = false; |
| 294 | std::vector<std::pair<std::string, std::vector<ValueType>>> params_list; |
| 295 | std::vector<std::vector<ValueType>> results_list; |
| 296 | |
| 297 | while (tok_.peek().type == TokenType::LParen && |
| 298 | tok_.peek2().type == TokenType::Keyword && tok_.peek2().text == "param") { |
| 299 | params_list.push_back(parse_param()); |
| 300 | has_params_results = true; |
| 301 | } |
| 302 | while (tok_.peek().type == TokenType::LParen && |
| 303 | tok_.peek2().type == TokenType::Keyword && tok_.peek2().text == "result") { |
| 304 | results_list.push_back(parse_result()); |
| 305 | has_params_results = true; |
| 306 | } |
| 307 | |
| 308 | if (!has_params_results) return typeidx; |
| 309 | |
| 310 | // Create a new type by copying the base type and adding params/results. |
| 311 | // Copy first to avoid reference invalidation when emplace_back reallocates. |
| 312 | auto base_type = types_[typeidx]; |
| 313 | auto& new_type = types_.emplace_back(std::move(base_type)); |
| 314 | typeidx = (index_t)(types_.size() - 1); |
| 315 | |
| 316 | for (auto& [id, types] : params_list) { |
| 317 | if (!id.empty()) { |
| 318 | if (new_type.second.contains(id)) |
| 319 | throw Exception::Parse("duplicated param id '" + id + "'", tok_.location()); |
| 320 | new_type.second[id] = new_type.first.params.size(); |
| 321 | } |
| 322 | new_type.first.params.insert(new_type.first.params.end(), types.begin(), types.end()); |
| 323 | } |
| 324 | for (auto& results : results_list) { |
| 325 | new_type.first.results.insert(new_type.first.results.end(), results.begin(), results.end()); |
| 326 | } |
| 327 | return typeidx; |
| 328 | } |
| 329 | |
| 330 | // ── Numeric parsers ─────────────────────────────────────────────────────────── |
| 331 | |