All files semantics.ts

92.47% Statements 565/611
80% Branches 220/275
91.83% Functions 90/98
95.16% Lines 512/538

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153                                                                    49x             626x 626x 626x 217343x   626x                         11x 11x 11x 11x       11x   11x       4x     4x       207x 207x 207x         207x 21x 21x 21x 21x 21x 21x     207x 207x   207x 268x 268x 113x 155x 155x       207x 207x 207x 207x       268x 268x 268x 268x 113x     155x             21x 21x 21x 21x       21x 21x 21x 21x 1x 20x 7x       7x 13x 4x       4x 9x 9x 15x 7x       21x       21x       5x 5x 9x 9x 8x   5x       4x 4x 7x 7x 7x   4x       7x 7x       4x 4x       11x 11x 11x 11x 11x 12x 12x 12x 12x 12x       12x 12x   11x       15x 15x 15x       6x       9x           155x   155x 155x 7x   155x   155x               155x   155x             155x 155x 155x 155x 155x 155x 155x 7x 148x 1x 147x 2x     155x               155x 7x 7x 2x   5x 5x 2x   3x 3x 3x 3x 3x 3x 3x         155x                     25x         25x 25x 25x 11x   25x                 119x         119x               11x   11x     11x       144x 144x         144x 181x 181x 8x 8x 8x 6x 6x 5x 5x     3x 3x 3x   3x   173x 173x 173x 3x   173x   173x     144x       173x       173x 173x 173x 173x 173x             173x 173x 173x 173x 173x       201x 201x 201x 201x 201x 201x 201x 201x 27x 27x 27x 15x 1x 14x     15x 15x 12x 5x 5x 7x 7x 7x     201x   201x 14x   201x       9x       6x       5x       7x           363x 363x 363x 363x 14x   363x 11x       377x 377x 377x 377x 2x   377x 2x       1x 1x 1x 1x 1x       19x       49x 49x 49x       310x       49x       23x     6x     1x     1x     48x       2x     7x     14x                   20x 20x       20x 20x   20x 28x 28x                       28x 28x 28x 28x   28x     20x       28x       28x 28x 28x 28x 28x             28x 28x 28x 28x 28x       14x             113x 113x   113x 113x 4x   113x   113x 113x   113x 113x 113x   113x             113x                         113x 113x 152x   113x       23x       129x           113x 113x       113x     113x 140x 140x 140x 140x 1x 1x 1x   139x 14x 14x 125x 4x 121x 121x 121x 1x   121x   139x     113x       140x 1x   139x             14x 1x 1x 1x   14x 14x       13x 13x 13x 13x 14x 14x 14x   13x       1x       14x 14x 14x 14x   14x 14x     14x 1x     14x                         121x 121x   121x 121x       121x       121x   121x 121x 121x 121x   121x   121x                               121x               121x           121x 121x                       121x     121x 136x 136x 136x   3x 3x   24x 24x   21x 21x   3x 3x 3x   6x 6x 6x   12x 1x   11x 11x   12x   15x 15x   44x 44x   8x 8x       121x       136x 136x           3x       24x       21x       3x   3x 3x             6x 1x 1x 1x   6x 6x       1x         11x 2x 2x 2x   11x 11x           15x 15x 15x 15x 15x 17x 17x 17x 17x 17x 1x 1x   16x 16x   15x       44x 44x 68x 68x 68x   44x             68x 68x 68x         68x       68x 68x 68x 40x 40x 40x 40x 8x 1x 1x   7x 7x 1x   6x   32x 32x       32x 32x       68x 68x 68x 68x 68x 68x       40x 40x       49x 49x 49x       1x       7x 7x 7x 7x 7x 11x 11x 11x 11x 11x 1x 1x   10x 10x   7x       23x 23x 23x 23x 23x 23x   23x 23x           13x       3x       10x 10x   10x 11x 11x 11x 11x 10x 10x       10x       11x       10x 10x 13x     10x 1x   10x               1x 1x 1x           49x 49x 49x 49x 30x   49x               3x       5x       3x       3x                       4x    
/**
 * Semantic Actions — transforms Ohm parse tree to CkRootNode AST.
 */
import type { Grammar, IterationNode } from 'ohm-js';
import type {
    CkRootNode,
    ModelNode,
    OpRouteNode,
    OpOperationNode,
    OpParamNode,
    OpRequestNode,
    OpRequestBodyNode,
    OpResponseNode,
    OpResponseHeaderNode,
    ContractTypeNode,
    FieldNode,
    ParamSource,
    SecurityNode,
    SecurityFields,
    ObjectMode,
    RouteModifier,
    HttpMethod,
    InlineObjectTypeNode,
} from './ast.js';
import { SECURITY_NONE } from './ast.js';
import { buildCompoundType, resolveSimpleType, extractNullability, typeNodeToParamSource, OBJECT_MODES, type TypeArg } from './type-builders.js';
import type { DiagnosticCollector } from './diagnostics.js';
 
/**
 * Normalize a parsed `type/subtype` string for storage in the AST. Mime types are
 * case-insensitive per RFC 9110, so we lowercase to give codegen and diagnostics a stable
 * comparison key. Anything matching the grammar's `mimeType` rule is accepted as-is.
 */
function normalizeContentType(raw: string): string {
    return raw.toLowerCase();
}
 
/**
 * Get the line number (1-based) from an Ohm Node.
 */
function getLine(node: { source: { sourceString: string; startIdx: number } }): number {
    const contents = node.source.sourceString;
    let line = 1;
    for (let i = 0; i < node.source.startIdx; i++) {
        if (contents[i] === '\n') line++;
    }
    return line;
}
 
/**
 * Collect a single inner `headers: { ... }` block from an options-level `request:` or `response:` body.
 * Multiple inner blocks are tolerated but only the first is kept; duplicates emit a warning.
 */
function collectOptionsHeaders(
    items: IterationNode,
    file: string,
    diag: DiagnosticCollector | undefined,
): OpResponseHeaderNode[] {
    let headers: OpResponseHeaderNode[] | undefined;
    for (let i = 0; i < items.numChildren; i++) {
        const child = items.child(i);
        Iif (child.ctorName === 'comment') continue;
        Iif (headers !== undefined) {
            diag?.warn(file, getLine(child), `Duplicate headers block in options`);
            continue;
        }
        headers = child.toAst(file, diag) as OpResponseHeaderNode[];
    }
    return headers ?? [];
}
 
export function createSemantics(grammar: Grammar) {
    const semantics = grammar.createSemantics();
 
    /** eslint-disable @typescript-eslint/no-explicit-any */
    semantics.addOperation('toAst(file,diag)', {
        // ─── Top-level ────────────────────────────────────────────────
 
        Root(preambleOpt, decls, _end) {
            const file = this.args.file as string;
            let meta: Record<string, string> = {};
            let services: Record<string, string> = {};
            let security: SecurityNode | undefined;
            let requestHeaders: OpResponseHeaderNode[] | undefined;
            let responseHeaders: OpResponseHeaderNode[] | undefined;
 
            if (preambleOpt.numChildren > 0) {
                const result = preambleOpt.child(0).toAst(file, this.args.diag);
                meta = result.meta ?? {};
                services = result.services ?? {};
                security = result.security;
                requestHeaders = result.requestHeaders;
                responseHeaders = result.responseHeaders;
            }
 
            const models: ModelNode[] = [];
            const routes: OpRouteNode[] = [];
 
            for (let i = 0; i < decls.numChildren; i++) {
                const result = decls.child(i).toAst(file, this.args.diag);
                if (result?._ckType === 'route') {
                    routes.push(result.value);
                } else Eif (result?._ckType === 'model') {
                    models.push(result.value);
                }
            }
 
            const root: CkRootNode = { kind: 'ckRoot', meta, services, security, models, routes, file };
            if (requestHeaders) root.requestHeaders = requestHeaders;
            if (responseHeaders) root.responseHeaders = responseHeaders;
            return root;
        },
 
        Decl(child) {
            const file = this.args.file;
            const diag = this.args.diag;
            const result = child.toAst(file, diag);
            if (child.ctorName === 'RouteDecl') {
                return { _ckType: 'route', value: result };
            } else {
                // ModelDecl
                return { _ckType: 'model', value: result };
            }
        },
 
        // ─── Options block ───────────────────────────────────────────
 
        OptionsBlock(_optionsKw, _lb, items, _rb) {
            const file = this.args.file;
            const diag = this.args.diag;
            const meta: Record<string, string> = {};
            const services: Record<string, string> = {};
            let security: SecurityNode | undefined;
            let requestHeaders: OpResponseHeaderNode[] | undefined;
            let responseHeaders: OpResponseHeaderNode[] | undefined;
            for (let i = 0; i < items.numChildren; i++) {
                const itemNode = items.child(i);
                const result = itemNode.toAst(file, diag);
                if (result._type === 'security') {
                    security = result.value;
                } else if (result._type === 'optionsRequestHeaders') {
                    Iif (requestHeaders !== undefined) {
                        diag?.warn(file, getLine(itemNode), `Duplicate options request block`);
                        continue;
                    }
                    requestHeaders = result.value;
                } else if (result._type === 'optionsResponseHeaders') {
                    Iif (responseHeaders !== undefined) {
                        diag?.warn(file, getLine(itemNode), `Duplicate options response block`);
                        continue;
                    }
                    responseHeaders = result.value;
                } else Eif (result.entries) {
                    for (const [key, value] of result.entries as [string, string][]) {
                        if (result._type === 'keys') meta[key] = value;
                        else Eif (result._type === 'services') services[key] = value;
                    }
                }
            }
            return { meta, services, security, requestHeaders, responseHeaders };
        },
 
        OptionsBodyItem(child) {
            return child.toAst(this.args.file, this.args.diag);
        },
 
        OptionsKeysBlock(_keysKw, _colonOpt, _lb, items, _rb) {
            const entries: [string, string][] = [];
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                if (child.ctorName === 'comment') continue;
                entries.push(child.toAst(this.args.file, this.args.diag));
            }
            return { _type: 'keys', entries };
        },
 
        OptionsServicesBlock(_servicesKw, _colonOpt, _lb, items, _rb) {
            const entries: [string, string][] = [];
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                entries.push(child.toAst(this.args.file, this.args.diag));
            }
            return { _type: 'services', entries };
        },
 
        OptionsRequestBlock(_requestKw, _colon, _lb, items, _rb) {
            const headers = collectOptionsHeaders(items as IterationNode, this.args.file, this.args.diag);
            return { _type: 'optionsRequestHeaders', value: headers };
        },
 
        OptionsResponseBlock(_responseKw, _colon, _lb, items, _rb) {
            const headers = collectOptionsHeaders(items as IterationNode, this.args.file, this.args.diag);
            return { _type: 'optionsResponseHeaders', value: headers };
        },
 
        OptionsHeadersBlock(_headersKw, _colon, _lb, items, _rb) {
            const file = this.args.file;
            const diag = this.args.diag;
            const headers: OpResponseHeaderNode[] = [];
            const seen = new Set<string>();
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                const header = child.toAst(file, diag) as OpResponseHeaderNode;
                const key = header.name.toLowerCase();
                Iif (seen.has(key)) {
                    diag?.warn(file, getLine(child), `Duplicate header '${header.name}' in options block`);
                    continue;
                }
                seen.add(key);
                headers.push(header);
            }
            return headers;
        },
 
        OptionsEntry(keyNode, _colon, valueNode) {
            const key = keyNode.sourceString;
            const value = valueNode.toAst(this.args.file, this.args.diag);
            return [key, value] as [string, string];
        },
 
        optionsValue_quoted(strNode) {
            return strNode.sourceString.slice(1, -1);
        },
 
        optionsValue_unquoted(rawNode) {
            return rawNode.sourceString.trim();
        },
 
        // ─── Models ──────────────────────────────────────────────────
 
        ModelDecl(commentNodes, _contractKw, prefixNode, _colon, bodyNode) {
            const file = this.args.file as string;
 
            const comments = [];
            for (let i = 0; i < commentNodes.numChildren; i++) {
                comments.push(commentNodes.child(i));
            }
            const description = comments.length > 0 ? comments.map(c => c.sourceString.replace(/^#\s?/, '').trimEnd()).join('\n') : undefined;
 
            const prefix = prefixNode.toAst(file, this.args.diag) as {
                name: string;
                mode?: ObjectMode;
                inputCase?: 'camel' | 'snake' | 'pascal';
                outputCase?: 'camel' | 'snake' | 'pascal';
                deprecated?: boolean;
                line: number;
            };
            const body = bodyNode.toAst(file, this.args.diag);
 
            const result: ModelNode = {
                kind: 'model',
                name: prefix.name,
                fields: body.fields ?? [],
                loc: { file, line: prefix.line },
            };
 
            if (body.bases && body.bases.length > 0) result.bases = body.bases;
            if (body.type) result.type = body.type;
            if (prefix.mode) result.mode = prefix.mode;
            if (prefix.inputCase) result.inputCase = prefix.inputCase;
            if (prefix.outputCase) result.outputCase = prefix.outputCase;
            if (prefix.deprecated) result.deprecated = true;
            if (description) {
                result.description = description;
            } else if (body.inlineDescription) {
                result.description = body.inlineDescription;
            } else if (body.firstCommentText && body.firstCommentLine === prefix.line) {
                result.description = body.firstCommentText;
            }
 
            return result;
        },
 
        ModelPrefix(modifiers, nameNode) {
            let mode: ObjectMode | undefined;
            let inputCase: 'camel' | 'snake' | 'pascal' | undefined;
            let outputCase: 'camel' | 'snake' | 'pascal' | undefined;
            let deprecated: boolean | undefined;
            for (let i = 0; i < modifiers.numChildren; i++) {
                const text = modifiers.child(i).sourceString.trim();
                if (text === 'deprecated') {
                    deprecated = true;
                } else {
                    const modeMatch = text.match(/^mode\((\w+)\)$/);
                    if (modeMatch && OBJECT_MODES.has(modeMatch[1]!)) {
                        mode = modeMatch[1] as ObjectMode;
                    } else {
                        const formatMatch = text.match(/^format\(([^)]+)\)$/);
                        Eif (formatMatch) {
                            const args = formatMatch[1]!;
                            const inputMatch = args.match(/(?:^|,\s*)input=(\w+)/);
                            const outputMatch = args.match(/(?:^|,\s*)output=(\w+)/);
                            if (inputMatch) inputCase = inputMatch[1] as 'camel' | 'snake' | 'pascal';
                            if (outputMatch) outputCase = outputMatch[1] as 'camel' | 'snake' | 'pascal';
                        }
                    }
                }
            }
            return {
                name: nameNode.sourceString,
                mode,
                inputCase,
                outputCase,
                deprecated,
                line: getLine(nameNode),
            };
        },
 
        ModelBody_inheritance(firstBaseNode, _amp, restBases, _ampLast, _lb, fieldListNode, _rb) {
            const result = fieldListNode.toAst(this.args.file, this.args.diag) as {
                fields: FieldNode[];
                firstCommentLine?: number;
                firstCommentText?: string;
            };
            const bases = [firstBaseNode.sourceString];
            const rest = restBases as IterationNode;
            for (let i = 0; i < rest.numChildren; i++) {
                bases.push(rest.child(i).sourceString);
            }
            return {
                bases,
                fields: result.fields,
                firstCommentLine: result.firstCommentLine,
                firstCommentText: result.firstCommentText,
            };
        },
 
        ModelBody_fields(_lb, fieldListNode, _rb) {
            const result = fieldListNode.toAst(this.args.file, this.args.diag) as {
                fields: FieldNode[];
                firstCommentLine?: number;
                firstCommentText?: string;
            };
            return {
                fields: result.fields,
                firstCommentLine: result.firstCommentLine,
                firstCommentText: result.firstCommentText,
            };
        },
 
        ModelBody_alias(typeExprNode, inlineCommentOpt) {
            const type = typeExprNode.toAst(this.args.file, this.args.diag) as ContractTypeNode;
            const inlineDescription =
                (inlineCommentOpt as IterationNode).numChildren > 0
                    ? (inlineCommentOpt as IterationNode).child(0).sourceString.replace(/^#\s?/, '').trimEnd()
                    : undefined;
            return { type, fields: [], inlineDescription };
        },
 
        FieldList(items) {
            const file = this.args.file as string;
            const fields: FieldNode[] = [];
            let pendingComment: string | undefined;
            let firstCommentLine: number | undefined;
            let firstCommentText: string | undefined;
 
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                if (child.ctorName === 'comment') {
                    const commentLine = getLine(child);
                    const commentText = child.sourceString.replace(/^#\s?/, '').trimEnd();
                    if (fields.length > 0) {
                        const lastField = fields[fields.length - 1]!;
                        if (commentLine === lastField.loc.line) {
                            lastField.description = commentText; // inline comment always wins
                            continue;
                        }
                    }
                    Eif (firstCommentLine === undefined) {
                        firstCommentLine = commentLine;
                        firstCommentText = commentText;
                    }
                    pendingComment = pendingComment ? pendingComment + '\n' + commentText : commentText;
                } else {
                    const field = child.toAst(file, this.args.diag) as FieldNode;
                    Eif (field) {
                        if (pendingComment && !field.description) {
                            field.description = pendingComment;
                        }
                        fields.push(field);
                    }
                    pendingComment = undefined;
                }
            }
            return { fields, firstCommentLine, firstCommentText };
        },
 
        FieldEntry(fieldNode, _comma) {
            return fieldNode.toAst(this.args.file, this.args.diag);
        },
 
        FieldDecl(nameNode, questionOpt, _colon, bodyNode) {
            const file = this.args.file as string;
            const name = nameNode.sourceString;
            const line = getLine(nameNode);
            const optional = questionOpt.sourceString === '?';
            const body = bodyNode.toAst(file, this.args.diag) as {
                type: ContractTypeNode;
                visibility: 'readonly' | 'writeonly' | 'normal';
                deprecated?: boolean;
                override?: boolean;
                default?: string | number | boolean;
            };
            const { type, nullable } = extractNullability(body.type);
            const field: FieldNode = { name, optional, nullable, visibility: body.visibility, type, default: body.default, loc: { file, line } };
            if (body.deprecated) field.deprecated = true;
            if (body.override) field.override = true;
            return field;
        },
 
        FieldBody(modifiersIter, typeExprNode, _eqOpt, defaultValOpt) {
            const file = this.args.file;
            const diag = this.args.diag;
            let visibility: 'readonly' | 'writeonly' | 'normal' = 'normal';
            let deprecated = false;
            let override = false;
            let visibilitySet = false;
            const modifiers = modifiersIter as IterationNode;
            for (let i = 0; i < modifiers.numChildren; i++) {
                const modNode = modifiers.child(i);
                const tag = modNode.toAst(file, diag) as 'readonly' | 'writeonly' | 'deprecated' | 'override';
                if (tag === 'readonly' || tag === 'writeonly') {
                    if (visibilitySet && visibility !== tag) {
                        diag?.error(file, getLine(modNode), `Conflicting visibility modifiers: cannot combine 'readonly' and 'writeonly'`);
                    } else Iif (visibilitySet) {
                        diag?.warn(file, getLine(modNode), `Duplicate '${tag}' modifier`);
                    }
                    visibility = tag;
                    visibilitySet = true;
                } else if (tag === 'deprecated') {
                    Iif (deprecated) diag?.warn(file, getLine(modNode), `Duplicate 'deprecated' modifier`);
                    deprecated = true;
                } else Eif (tag === 'override') {
                    Iif (override) diag?.warn(file, getLine(modNode), `Duplicate 'override' modifier`);
                    override = true;
                }
            }
            const type = typeExprNode.toAst(file, diag) as ContractTypeNode;
            let defaultVal: string | number | boolean | undefined;
            if ((defaultValOpt as IterationNode).numChildren > 0) {
                defaultVal = (defaultValOpt as IterationNode).child(0).toAst(file, diag);
            }
            return { type, visibility, deprecated, override, default: defaultVal };
        },
 
        fieldModifier_readonly(_kw) {
            return 'readonly';
        },
 
        fieldModifier_writeonly(_kw) {
            return 'writeonly';
        },
 
        fieldModifier_deprecated(_kw) {
            return 'deprecated';
        },
 
        fieldModifier_override(_kw) {
            return 'override';
        },
 
        // ─── Type Expressions ────────────────────────────────────────
 
        TypeExpression(_leadPipeOpt, firstNode, _pipes, restNodes) {
            const file = this.args.file;
            const first = firstNode.toAst(file, this.args.diag) as ContractTypeNode;
            const rest: ContractTypeNode[] = [];
            for (let i = 0; i < restNodes.numChildren; i++) {
                rest.push(restNodes.child(i).toAst(file, this.args.diag));
            }
            if (rest.length === 0) return first;
            return { kind: 'union', members: [first, ...rest] } as ContractTypeNode;
        },
 
        IntersectionExpr(firstNode, _amps, restNodes) {
            const file = this.args.file;
            const first = firstNode.toAst(file, this.args.diag) as ContractTypeNode;
            const rest: ContractTypeNode[] = [];
            for (let i = 0; i < restNodes.numChildren; i++) {
                rest.push(restNodes.child(i).toAst(file, this.args.diag));
            }
            if (rest.length === 0) return first;
            return { kind: 'intersection', members: [first, ...rest] } as ContractTypeNode;
        },
 
        SingleType_modedObject(modeNode, objNode) {
            const modeText = modeNode.sourceString.trim();
            const m = modeText.match(/^mode\((\w+)\)$/);
            const mode = (m ? m[1] : modeText) as ObjectMode;
            const obj = objNode.toAst(this.args.file, this.args.diag) as InlineObjectTypeNode;
            return { ...obj, mode };
        },
 
        SingleType_bareObject(objNode) {
            return objNode.toAst(this.args.file, this.args.diag);
        },
 
        SingleType_withArgs(nameNode, _lp, argsNode, _rp) {
            const name = nameNode.sourceString;
            const args = argsNode.toAst(this.args.file, this.args.diag) as TypeArg[];
            return buildCompoundType(name, args);
        },
 
        SingleType_simple(nameNode) {
            return resolveSimpleType(nameNode.sourceString);
        },
 
        TypeArgs(listNode) {
            return listNode.toAst(this.args.file, this.args.diag);
        },
 
        TypeArg_keyValue(keyNode, _eq, valNode) {
            return { key: keyNode.sourceString, value: valNode.toAst(this.args.file, this.args.diag) };
        },
        TypeArg_string(node) {
            return { type: 'string', value: node.sourceString.slice(1, -1) };
        },
        TypeArg_number(node) {
            return { type: 'number', value: Number(node.sourceString) };
        },
        TypeArg_boolean(node) {
            return { type: 'boolean', value: node.sourceString === 'true' };
        },
        TypeArg_type(node) {
            return { type: 'type', value: node.toAst(this.args.file, this.args.diag) };
        },
 
        ArgValue_regex(node) {
            return node.sourceString.slice(1, -1);
        },
        ArgValue_ident(node) {
            return node.sourceString;
        },
        ArgValue_number(node) {
            return Number(node.sourceString);
        },
        ArgValue_string(node) {
            return node.sourceString.slice(1, -1);
        },
        ArgValue_boolean(node) {
            return node.sourceString === 'true';
        },
 
        InlineBraceObject(_lb, fieldsNode, _rb) {
            const fields = fieldsNode.toAst(this.args.file, this.args.diag) as FieldNode[];
            return { kind: 'inlineObject', fields } as InlineObjectTypeNode;
        },
 
        InlineFieldList(items) {
            const file = this.args.file;
            const fields: FieldNode[] = [];
            let pendingComment: string | undefined;
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') {
                    const commentLine = getLine(child);
                    const commentText = child.sourceString.replace(/^#\s?/, '').trimEnd();
                    if (fields.length > 0) {
                        const lastField = fields[fields.length - 1]!;
                        if (commentLine === lastField.loc.line) {
                            lastField.description = commentText; // inline comment always wins
                            continue;
                        }
                    }
                    pendingComment = pendingComment ? pendingComment + '\n' + commentText : commentText;
                } else {
                    const field = child.toAst(file, this.args.diag) as FieldNode;
                    Eif (field) {
                        Iif (pendingComment && !field.description) field.description = pendingComment;
                        fields.push(field);
                    }
                    pendingComment = undefined;
                }
            }
            return fields;
        },
 
        InlineFieldEntry(fieldNode, _comma) {
            return fieldNode.toAst(this.args.file, this.args.diag);
        },
 
        InlineField(nameNode, questionOpt, _colon, bodyNode) {
            const file = this.args.file as string;
            const name = nameNode.sourceString;
            const line = getLine(nameNode);
            const optional = questionOpt.sourceString === '?';
            const body = bodyNode.toAst(file, this.args.diag) as {
                type: ContractTypeNode;
                visibility: 'readonly' | 'writeonly' | 'normal';
                deprecated?: boolean;
                override?: boolean;
                default?: string | number | boolean;
            };
            const { type, nullable } = extractNullability(body.type);
            const field: FieldNode = { name, optional, nullable, visibility: body.visibility, type, default: body.default, loc: { file, line } };
            Iif (body.deprecated) field.deprecated = true;
            Iif (body.override) field.override = true;
            return field;
        },
 
        DefaultValue(node) {
            return node.toAst(this.args.file, this.args.diag);
        },
 
        // ─── Routes ───────────────────────────────────────────────────
 
        // RouteDecl = comment* operationKwCall RoutePath ":" "{" RouteBody "}"
        RouteDecl(commentNodes, operationKwCallNode, routePathNode, _colon, _lb, routeBodyNode, _rb) {
            const file = this.args.file as string;
            const diag = this.args.diag as DiagnosticCollector;
 
            const comments = [];
            for (let i = 0; i < commentNodes.numChildren; i++) {
                comments.push(commentNodes.child(i));
            }
            const description = comments.length > 0 ? comments.map(c => c.sourceString.replace(/^#\s?/, '').trimEnd()).join('\n') : undefined;
 
            const path = routePathNode.toAst(file, diag) as string;
            const line = getLine(routePathNode);
 
            const kwText = operationKwCallNode.sourceString.trim();
            const modMatch = kwText.match(/^operation\((\w+)\)$/);
            const modifiers: RouteModifier[] = modMatch ? [modMatch[1] as RouteModifier] : [];
 
            const routeBody = routeBodyNode.toAst(file, diag) as {
                params?: ParamSource;
                paramsMode?: ObjectMode;
                security?: SecurityNode;
                operations: OpOperationNode[];
            };
 
            return {
                path,
                params: routeBody.params,
                paramsMode: routeBody.paramsMode,
                security: routeBody.security,
                operations: routeBody.operations,
                modifiers: modifiers.length > 0 ? modifiers : undefined,
                description,
                loc: { file, line },
            } as OpRouteNode;
        },
 
        RoutePath(segments) {
            const parts: string[] = [];
            for (let i = 0; i < segments.numChildren; i++) {
                parts.push(segments.child(i).toAst(this.args.file, this.args.diag));
            }
            return parts.join('');
        },
 
        PathSegment_param(_slash, _lb, nameNode, _rb) {
            return '/{' + nameNode.sourceString + '}';
        },
 
        PathSegment_literal(_slash, nameNode) {
            return '/' + nameNode.sourceString;
        },
 
        // ─── Route Body ───────────────────────────────────────────────
 
        RouteBody(items) {
            const file = this.args.file;
            const diag = this.args.diag;
            let params: ParamSource | undefined;
            let paramsMode: ObjectMode | undefined;
            let security: SecurityNode | undefined;
            const operations: OpOperationNode[] = [];
            let pendingComment: string | undefined;
 
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                const result = child.toAst(file, diag);
                Iif (result === null || result === undefined) continue;
                if (result._type === 'comment') {
                    const text = result.value as string;
                    pendingComment = pendingComment ? pendingComment + '\n' + text : text;
                    continue;
                }
                if (result._type === 'params') {
                    params = result.source;
                    paramsMode = result.mode;
                } else if (result._type === 'security') {
                    security = result.value;
                } else Eif (result._type === 'operation') {
                    const op = result.value as OpOperationNode;
                    if (pendingComment && !op.description) {
                        op.description = pendingComment;
                    }
                    operations.push(op);
                }
                pendingComment = undefined;
            }
 
            return { params, paramsMode, security, operations };
        },
 
        RouteBodyItem(child) {
            if (child.ctorName === 'comment') {
                return { _type: 'comment', value: child.sourceString.replace(/^#\s?/, '').trimEnd() };
            }
            return child.toAst(this.args.file, this.args.diag);
        },
 
        // ─── Params Block ─────────────────────────────────────────────
 
        ParamsBlock(modeOpt, _paramsKw, _colon, bodyNode) {
            let mode: ObjectMode | undefined;
            if (modeOpt.numChildren > 0) {
                const modeText = modeOpt.child(0).sourceString.trim();
                const m = modeText.match(/^mode\((\w+)\)$/);
                mode = (m ? m[1] : modeText) as ObjectMode;
            }
            const body = bodyNode.toAst(this.args.file, this.args.diag);
            return { _type: 'params', source: body.source, mode };
        },
 
        ParamsBody_inline(_lb, items, _rb) {
            const file = this.args.file;
            const diag = this.args.diag;
            const params: OpParamNode[] = [];
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                params.push(child.toAst(file, diag));
            }
            return { source: { kind: 'params' as const, nodes: params } };
        },
 
        ParamsBody_ref(identNode) {
            return { source: { kind: 'ref' as const, name: identNode.sourceString } };
        },
 
        ParamDecl(nameNode, _colon, typeNode, commentOpt) {
            const file = this.args.file as string;
            const diag = this.args.diag;
            const name = nameNode.sourceString;
            const line = getLine(nameNode);
 
            const rawType = typeNode.toAst(file, diag) as ContractTypeNode;
            const { type, nullable } = extractNullability(rawType);
 
            let description: string | undefined;
            if ((commentOpt as IterationNode).numChildren > 0) {
                description = (commentOpt as IterationNode).child(0).sourceString.replace(/^#\s?/, '').trimEnd();
            }
 
            return {
                name,
                optional: false,
                nullable,
                type,
                description,
                loc: { file, line },
            } as OpParamNode;
        },
 
        // ─── HTTP Operations ──────────────────────────────────────────
 
        HttpOperation(commentNodes, httpMethodCallNode, _colon, _lb, inlineCommentOpt, bodyNode, _rb) {
            const file = this.args.file as string;
            const diag = this.args.diag as DiagnosticCollector;
 
            const comments = [];
            for (let i = 0; i < commentNodes.numChildren; i++) {
                comments.push(commentNodes.child(i));
            }
            const inlineComment =
                (inlineCommentOpt as IterationNode).numChildren > 0
                    ? (inlineCommentOpt as IterationNode).child(0).sourceString.replace(/^#\s?/, '').trimEnd()
                    : undefined;
            const description =
                inlineComment ?? (comments.length > 0 ? comments.map(c => c.sourceString.replace(/^#\s?/, '').trimEnd()).join('\n') : undefined);
 
            const methodText = httpMethodCallNode.sourceString.trim();
            const modMatch = methodText.match(/\((\w+)\)$/);
            const method = methodText.replace(/\(\w+\)$/, '').trim() as HttpMethod;
            const line = getLine(httpMethodCallNode);
 
            const modifiers: RouteModifier[] = modMatch ? [modMatch[1] as RouteModifier] : [];
 
            const body = bodyNode.toAst(file, diag) as {
                name?: string;
                service?: string;
                sdk?: string;
                signature?: string;
                signatureDescription?: string;
                query?: ParamSource;
                queryMode?: ObjectMode;
                headers?: ParamSource;
                headersMode?: ObjectMode;
                requestHeadersOptOut?: boolean;
                request?: OpRequestNode;
                responses: OpResponseNode[];
                security?: SecurityNode;
            };
 
            const op: OpOperationNode = {
                method,
                ...body,
                modifiers: modifiers.length > 0 ? modifiers : undefined,
                description,
                loc: { file, line },
            };
 
            return { _type: 'operation', value: op };
        },
 
        // ─── Operation Body ───────────────────────────────────────────
 
        OperationBody(items) {
            const file = this.args.file;
            const diag = this.args.diag;
            let name: string | undefined;
            let service: string | undefined;
            let sdk: string | undefined;
            let signature: string | undefined;
            let signatureDescription: string | undefined;
            let query: ParamSource | undefined;
            let queryMode: ObjectMode | undefined;
            let headers: ParamSource | undefined;
            let headersMode: ObjectMode | undefined;
            let requestHeadersOptOut: boolean | undefined;
            let request: OpRequestNode | undefined;
            let responses: OpResponseNode[] = [];
            let security: SecurityNode | undefined;
 
            for (let i = 0; i < items.numChildren; i++) {
                const item = items.child(i).toAst(file, diag);
                Iif (!item) continue;
                switch (item._type) {
                    case 'name':
                        name = item.value;
                        break;
                    case 'service':
                        service = item.value;
                        break;
                    case 'sdk':
                        sdk = item.value;
                        break;
                    case 'signature':
                        signature = item.value;
                        signatureDescription = item.description;
                        break;
                    case 'query':
                        query = item.source;
                        queryMode = item.mode;
                        break;
                    case 'headers':
                        if (item.optOut) {
                            requestHeadersOptOut = true;
                        } else {
                            headers = item.source;
                            headersMode = item.mode;
                        }
                        break;
                    case 'request':
                        request = item.value;
                        break;
                    case 'responses':
                        responses = item.value;
                        break;
                    case 'security':
                        security = item.value;
                        break;
                }
            }
 
            return { name, service, sdk, signature, signatureDescription, query, queryMode, headers, headersMode, requestHeadersOptOut, request, responses, security };
        },
 
        OperationBodyItem(child) {
            Iif (child.ctorName === 'comment') return null;
            return child.toAst(this.args.file, this.args.diag);
        },
 
        // ─── Service & SDK ────────────────────────────────────────────
 
        NameDecl(_nameKw, _colon, textNode) {
            return { _type: 'name', value: textNode.sourceString.trim() };
        },
 
        ServiceDecl(_serviceKw, _colon, identNode) {
            return { _type: 'service', value: identNode.sourceString };
        },
 
        SdkDecl(_sdkKw, _colon, identNode) {
            return { _type: 'sdk', value: identNode.sourceString };
        },
 
        SignatureDecl(_signatureKw, _colon, valueNode) {
            const raw = valueNode.sourceString;
            // Strip quotes if present
            const value = raw.startsWith('"') || raw.startsWith("'") ? raw.slice(1, -1) : raw;
            return { _type: 'signature', value, description: undefined };
        },
 
        // ─── Query & Headers ──────────────────────────────────────────
 
        QueryBlock(modeOpt, _queryKw, _colon, typeExprNode) {
            let mode: ObjectMode | undefined;
            if (modeOpt.numChildren > 0) {
                const modeText = modeOpt.child(0).sourceString.trim();
                const m = modeText.match(/^mode\((\w+)\)$/);
                mode = (m ? m[1] : modeText) as ObjectMode;
            }
            const typeNode = typeExprNode.toAst(this.args.file, this.args.diag) as ContractTypeNode;
            return { _type: 'query', source: typeNodeToParamSource(typeNode), mode };
        },
 
        HeadersBlock_none(_headersKw, _colon, _noneKw) {
            return { _type: 'headers', optOut: true };
        },
 
        HeadersBlock_type(modeOpt, _headersKw, _colon, typeExprNode) {
            let mode: ObjectMode | undefined;
            if (modeOpt.numChildren > 0) {
                const modeText = modeOpt.child(0).sourceString.trim();
                const m = modeText.match(/^mode\((\w+)\)$/);
                mode = (m ? m[1] : modeText) as ObjectMode;
            }
            const typeNode = typeExprNode.toAst(this.args.file, this.args.diag) as ContractTypeNode;
            return { _type: 'headers', source: typeNodeToParamSource(typeNode), mode };
        },
 
        // ─── Request & Response ───────────────────────────────────────
 
        RequestBlock(_requestKw, _colon, _lb, items, _rb) {
            const file = this.args.file as string;
            const diag = this.args.diag as DiagnosticCollector | undefined;
            const bodies: OpRequestBodyNode[] = [];
            const seen = new Map<string, number>();
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                const raw = child.toAst(file, diag) as { contentType: string; bodyType: ContractTypeNode };
                const ct = normalizeContentType(raw.contentType);
                if (seen.has(ct)) {
                    diag?.warn(file, getLine(child), `Duplicate request content type '${ct}'`);
                    continue;
                }
                seen.set(ct, i);
                bodies.push({ contentType: ct, bodyType: raw.bodyType });
            }
            return { _type: 'request', value: { bodies } as OpRequestNode };
        },
 
        ResponseBlock(_responseKw, _colon, _lb, items, _rb) {
            const responses: OpResponseNode[] = [];
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                responses.push(child.toAst(this.args.file, this.args.diag));
            }
            return { _type: 'responses', value: responses };
        },
 
        // StatusCodeBlock = numberLit ":" ("{" StatusCodeBodyItem* "}")?
        // The optional inline group desugars to three IterationNodes for its children.
        // Total: codeNode, _colon, _lbOpt, itemsOpt, _rbOpt = 5
        StatusCodeBlock(codeNode, _colon, _lbOpt, itemsOpt, _rbOpt) {
            const file = this.args.file;
            const diag = this.args.diag;
            const statusCode = parseInt(codeNode.sourceString, 10);
            let contentType: string | undefined;
            let bodyType: ContractTypeNode | undefined;
            let headers: OpResponseHeaderNode[] | undefined;
            let headersOptOut: boolean | undefined;
            let sawResponseHeaders = false;
 
            // ("{" StatusCodeBodyItem* "}")? desugars so that itemsOpt is the *outer* `?` wrapper
            // around the StatusCodeBodyItem* iteration; child(0) is the inner iteration when present.
            const outer = itemsOpt as IterationNode;
            const items = outer.numChildren > 0 ? (outer.child(0) as IterationNode) : null;
            for (let i = 0; items && i < items.numChildren; i++) {
                const itemNode = items.child(i);
                const item = itemNode.toAst(file, diag);
                Iif (!item) continue;
                if (item._type === 'responseHeaders') {
                    if (sawResponseHeaders) {
                        diag?.warn(file, getLine(itemNode), `Duplicate response headers block for status ${statusCode}`);
                        continue;
                    }
                    sawResponseHeaders = true;
                    if (item.optOut) {
                        headersOptOut = true;
                    } else {
                        headers = item.value;
                    }
                } else Eif (item.contentType !== undefined && item.bodyType !== undefined) {
                    Iif (contentType !== undefined) {
                        diag?.warn(file, getLine(itemNode), `Duplicate response body for status ${statusCode}`);
                        continue;
                    }
                    contentType = normalizeContentType(item.contentType);
                    bodyType = item.bodyType;
                }
            }
 
            const result: OpResponseNode = { statusCode };
            if (contentType) result.contentType = contentType;
            if (bodyType) result.bodyType = bodyType;
            if (headers) result.headers = headers;
            if (headersOptOut) result.headersOptOut = true;
            return result;
        },
 
        StatusCodeBodyItem(child) {
            Iif (child.ctorName === 'comment') return null;
            return child.toAst(this.args.file, this.args.diag);
        },
 
        ContentTypeLine(mimeNode, _colon, typeExprNode) {
            const contentType = mimeNode.sourceString;
            const bodyType = typeExprNode.toAst(this.args.file, this.args.diag) as ContractTypeNode;
            return { contentType, bodyType };
        },
 
        ResponseHeadersBlock_none(_headersKw, _colon, _noneKw) {
            return { _type: 'responseHeaders', optOut: true };
        },
 
        ResponseHeadersBlock_fields(_headersKw, _colon, _lb, items, _rb) {
            const file = this.args.file;
            const diag = this.args.diag;
            const headers: OpResponseHeaderNode[] = [];
            const seen = new Set<string>();
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                const header = child.toAst(file, diag) as OpResponseHeaderNode;
                const key = header.name.toLowerCase();
                if (seen.has(key)) {
                    diag?.warn(file, getLine(child), `Duplicate response header '${header.name}'`);
                    continue;
                }
                seen.add(key);
                headers.push(header);
            }
            return { _type: 'responseHeaders', value: headers };
        },
 
        ResponseHeaderField(nameNode, optMark, _colon, typeExprNode, inlineCommentOpt) {
            const file = this.args.file;
            const diag = this.args.diag;
            const name = nameNode.sourceString;
            const optional = (optMark as IterationNode).numChildren > 0;
            const type = typeExprNode.toAst(file, diag) as ContractTypeNode;
            const inline = inlineCommentOpt as IterationNode;
            const description =
                inline.numChildren > 0 ? inline.child(0).sourceString.replace(/^#\s?/, '').trimEnd() : undefined;
            return { name, optional, type, description } as OpResponseHeaderNode;
        },
 
        // ─── Security ─────────────────────────────────────────────────
 
        SecurityBlock(_securityKw, _colon, bodyNode) {
            return { _type: 'security', value: bodyNode.toAst(this.args.file, this.args.diag) };
        },
 
        SecurityBody_none(_noneKw) {
            return SECURITY_NONE;
        },
 
        SecurityBody_fields(_lb, items, _rb) {
            const file = this.args.file as string;
            const fields: SecurityFields = { loc: { file, line: getLine(this) } };
 
            for (let i = 0; i < items.numChildren; i++) {
                const child = items.child(i);
                Iif (child.ctorName === 'comment') continue;
                const result = child.toAst(file, this.args.diag);
                if (result._type === 'roles') {
                    fields.roles = result.roles;
                    if (result.description) fields.rolesDescription = result.description;
                }
            }
 
            return fields;
        },
 
        SecurityField(child) {
            return child.toAst(this.args.file, this.args.diag);
        },
 
        SecurityRolesLine(_rolesKw, _colon, roleNodes, commentOpt) {
            const roles: string[] = [];
            for (let i = 0; i < roleNodes.numChildren; i++) {
                roles.push(roleNodes.child(i).sourceString.trim());
            }
            let description: string | undefined;
            if ((commentOpt as IterationNode).numChildren > 0) {
                description = (commentOpt as IterationNode).child(0).sourceString.replace(/^#\s?/, '').trimEnd();
            }
            return { _type: 'roles', roles, description };
        },
 
        RoleName(identNode) {
            return identNode.sourceString;
        },
 
        SecuritySignatureLine(_signatureKw, _colon, valueNode, _commentOpt) {
            const raw = valueNode.sourceString;
            const value = raw.startsWith('"') || raw.startsWith("'") ? raw.slice(1, -1) : raw;
            return { _type: 'signatureField', value };
        },
 
        // ─── Shared lexical rules ─────────────────────────────────────
 
        NonemptyListOf(first, _sep, rest) {
            const file = this.args.file;
            const diag = this.args.diag;
            const result = [first.toAst(file, diag)];
            for (let i = 0; i < rest.numChildren; i++) {
                result.push(rest.child(i).toAst(file, diag));
            }
            return result;
        },
 
        EmptyListOf() {
            return [];
        },
 
        stringLit(_q1, chars, _q2) {
            return chars.sourceString;
        },
 
        numberLit(_neg, _digits, _dot, _decimals) {
            return Number(this.sourceString);
        },
 
        booleanLit(_) {
            return this.sourceString === 'true';
        },
 
        identifier(_start, _rest) {
            return this.sourceString;
        },
 
        _terminal() {
            return this.sourceString;
        },
 
        _iter(...children) {
            return children.map(c => c.toAst(this.args.file, this.args.diag));
        },
    });
 
    return semantics;
}