willbooster-tree-sitter-c-sharp 38.2.1

C# grammar for tree-sitter
Documentation
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
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
// code-gauge-allow-file fileNcss -- Scanner dispatch and literal lifecycles share token state.
#include "tree_sitter/alloc.h"
#include "tree_sitter/array.h"
#include "tree_sitter/parser.h"

#include "identifierCharacters.h"

enum TokenType {
    OPT_SEMI,
    INTERPOLATION_REGULAR_START,
    INTERPOLATION_VERBATIM_START,
    INTERPOLATION_RAW_START,
    INTERPOLATION_START_QUOTE,
    INTERPOLATION_END_QUOTE,
    INTERPOLATION_OPEN_BRACE,
    INTERPOLATION_CLOSE_BRACE,
    INTERPOLATION_STRING_CONTENT,
    RAW_STRING_START,
    RAW_STRING_END,
    RAW_STRING_CONTENT,
    LAMBDA_PAREN_OPEN,
    END_OF_INPUT,
    DIRECTIVE_NEWLINE,
    FILE_DIRECTIVE_PREPROC_ARG,
    FILE_DIRECTIVE_SDK,
    FILE_DIRECTIVE_PACKAGE,
    FILE_DIRECTIVE_PROPERTY,
    FILE_DIRECTIVE_PROJECT,
    FILE_DIRECTIVE_REF,
    FILE_DIRECTIVE_INCLUDE,
    FILE_DIRECTIVE_EXCLUDE,
    FILE_DIRECTIVE_KIND,
    FILE_DIRECTIVE_LITERAL_CONTEXT,
    FILE_DIRECTIVE_NEWLINE,
    PRAGMA_BOUNDARY,
    PRAGMA_TEXT,
    PREPROC_INACTIVE,
    CONDITIONAL_ACCESS_QUESTION,
    NULLABLE_QUESTION,
    TERNARY_QUESTION,
    TYPE_LIST_OPEN,
    LESS_THAN,
    TYPE_LIST_OR_LESS_THAN,
    NULLABLE_OR_TERNARY_QUESTION,
    AWAIT_IDENTIFIER,
    RECORD_KEYWORD,
    RECORD_CONSTRUCTOR,
    MEMBER_RECORD_MODIFIER,
    CREATION_TYPE_START,
    CREATION_NULLABLE_QUESTION,
};

typedef enum {
    REGULAR = 1 << 0,
    VERBATIM = 1 << 1,
    RAW = 1 << 2,
} StringType;

typedef struct {
    uint8_t dollar_count;
    uint8_t open_brace_count;
    uint8_t quote_count;
    StringType string_type;
} Interpolation;

static inline bool is_regular(Interpolation *interpolation) { return interpolation->string_type & REGULAR; }

static inline bool is_verbatim(Interpolation *interpolation) { return interpolation->string_type & VERBATIM; }

static inline bool is_raw(Interpolation *interpolation) { return interpolation->string_type & RAW; }

typedef struct {
    uint8_t quote_count;
    bool next_file_directive;
    Array(Interpolation) interpolation_stack;
} Scanner;

static inline void advance(TSLexer *lexer) { lexer->advance(lexer, false); }

static inline void skip(TSLexer *lexer) { lexer->advance(lexer, true); }

static inline bool is_line_terminator(int32_t c) {
    return c == '\r' || c == '\n' || c == 0x85 || c == 0x2028 || c == 0x2029;
}

// Use a fixed set for end-of-input lookahead: `iswspace` depends on the C library and locale (it rejects NBSP on macOS).
// Line terminators that remain here are handled by the grammar when end-of-input lookahead fails.
static inline bool is_space_but_line_feed(int32_t c) {
    return c == '\t' || c == '\v' || c == '\f' || c == '\r' || c == ' ' || c == 0xA0 || c == 0x3000 || c == 0xFEFF;
}

static bool skip_block_comment(TSLexer *lexer);
static void skip_line_comment(TSLexer *lexer);

// The parameter-list caller requires a consumed non-comment slash to remain invalid.
// Returns whether it stopped after a `/` that starts no comment, which the lexer is then past.
static bool skip_ws_and_comments(TSLexer *lexer) {
    for (;;) {
        int32_t c = lexer->lookahead;
        if (is_space_but_line_feed(c) || is_line_terminator(c)) {
            advance(lexer);
            continue;
        }
        if (c != '/') return false;
        advance(lexer);
        if (lexer->lookahead == '/') skip_line_comment(lexer);
        else if (lexer->lookahead == '*') skip_block_comment(lexer);
        else return true;
    }
}

static bool skip_block_comment(TSLexer *lexer) {
    advance(lexer);
    int32_t previous = 0;
    while (!at_eof(lexer) && !(previous == '*' && lexer->lookahead == '/')) {
        previous = lexer->lookahead;
        advance(lexer);
    }
    if (at_eof(lexer)) return false;
    advance(lexer);
    return true;
}

static void skip_line_comment(TSLexer *lexer) {
    while (!at_eof(lexer) && !is_line_terminator(lexer->lookahead)) advance(lexer);
}

static size_t consume_identifier_into(TSLexer *lexer, char *buf, size_t max) {
    size_t n = 0;
    while (is_id_continue(lexer->lookahead)) {
        if (n < max) buf[n] = lexer->lookahead <= 0x7F ? (char)lexer->lookahead : '?';
        n++;
        advance(lexer);
    }
    return n;
}

void *tree_sitter_c_sharp_external_scanner_create() {
    Scanner *scanner = ts_calloc(1, sizeof(Scanner));
    array_init(&scanner->interpolation_stack);
    return scanner;
}

void tree_sitter_c_sharp_external_scanner_destroy(void *payload) {
    Scanner *scanner = (Scanner *)payload;
    array_delete(&scanner->interpolation_stack);
    ts_free(scanner);
}

unsigned tree_sitter_c_sharp_external_scanner_serialize(void *payload, char *buffer) {
    Scanner *scanner = (Scanner *)payload;
    if (!scanner->quote_count && !scanner->next_file_directive && !scanner->interpolation_stack.size) return 0;
    if (scanner->interpolation_stack.size * 4 + 3 > TREE_SITTER_SERIALIZATION_BUFFER_SIZE) return 0;
    unsigned size = 0;
    buffer[size++] = (char)scanner->quote_count;
    buffer[size++] = (char)scanner->next_file_directive;
    buffer[size++] = (char)scanner->interpolation_stack.size;
    for (unsigned i = 0; i < scanner->interpolation_stack.size; i++) {
        Interpolation item = scanner->interpolation_stack.contents[i];
        buffer[size++] = (char)item.dollar_count;
        buffer[size++] = (char)item.open_brace_count;
        buffer[size++] = (char)item.quote_count;
        buffer[size++] = (char)item.string_type;
    }
    return size;
}

void tree_sitter_c_sharp_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) {
    Scanner *scanner = (Scanner *)payload;
    scanner->quote_count = 0;
    scanner->next_file_directive = false;
    array_clear(&scanner->interpolation_stack);
    if (length < 3) return;
    unsigned count = (unsigned char)buffer[2];
    if (3 + count * 4 != length) return;
    scanner->quote_count = (unsigned char)buffer[0];
    scanner->next_file_directive = buffer[1] != 0;
    array_reserve(&scanner->interpolation_stack, count);
    scanner->interpolation_stack.size = count;
    for (unsigned i = 0; i < count; i++) {
        const char *item = buffer + 3 + i * 4;
        scanner->interpolation_stack.contents[i] = (Interpolation){
            .dollar_count = (unsigned char)item[0],
            .open_brace_count = (unsigned char)item[1],
            .quote_count = (unsigned char)item[2],
            .string_type = (unsigned char)item[3],
        };
    }
}

// Distinguishes untouched lookahead (safe to fall through) from a speculative advance past '(' (must return false so
// tree-sitter rewinds instead of letting later handlers emit spans starting at the pre-'(' cursor).
typedef enum {
    LAMBDA_SCAN_NO_PAREN,
    LAMBDA_SCAN_FAILED_AFTER_PAREN,
    LAMBDA_SCAN_SUCCESS,
} LambdaScanResult;

static bool consume_lambda_element(TSLexer *lexer, bool *saw_hard_modifier);

// Whole-word buffering avoids rewinding on the `ref` vs `readonly` prefix conflict (`TSLexer` has no rewind), and
// requiring a hard modifier rejects `(scoped x) =>` where `scoped` is a legal type name.
// code-gauge-allow functionCognitiveComplexity -- Parameter-list commas and balanced-group closing share the speculative cursor until `=>` is confirmed.
// code-gauge-allow functionNcss -- Parameter-list commas and balanced-group closing share the speculative cursor until `=>` is confirmed.
static LambdaScanResult scan_lambda_paren_open(TSLexer *lexer) {
    while (is_unicode_whitespace(lexer->lookahead)) skip(lexer);
    if (lexer->lookahead != '(') return LAMBDA_SCAN_NO_PAREN;
    advance(lexer);
    lexer->mark_end(lexer);

    #define BAIL return LAMBDA_SCAN_FAILED_AFTER_PAREN
    bool saw_hard_modifier = false;
    bool expecting_element = true;

    for (;;) {
        if (skip_ws_and_comments(lexer)) BAIL;
        int32_t c = lexer->lookahead;
        if (at_eof(lexer)) BAIL;

        if (c == ')') {
            advance(lexer);
            if (skip_ws_and_comments(lexer) || !saw_hard_modifier || lexer->lookahead != '=') BAIL;
            advance(lexer);
            if (lexer->lookahead != '>') BAIL;
            lexer->result_symbol = LAMBDA_PAREN_OPEN;
            return LAMBDA_SCAN_SUCCESS;
        }

        if (!expecting_element) {
            if (c != ',') BAIL;
            advance(lexer);
            expecting_element = true;
            continue;
        }

        if (!consume_lambda_element(lexer, &saw_hard_modifier)) BAIL;
        expecting_element = false;
    }
}
#undef BAIL

static bool consume_lambda_element(TSLexer *lexer, bool *saw_hard_modifier) {
    for (;;) {
        if (skip_ws_and_comments(lexer) || !is_id_start(lexer->lookahead)) return false;
        char buf[9];
        size_t n = consume_identifier_into(lexer, buf, sizeof(buf));
        if (buf_equals(buf, n, "ref") || buf_equals(buf, n, "out") ||
            buf_equals(buf, n, "in") || buf_equals(buf, n, "readonly")) {
            *saw_hard_modifier = true;
        } else if (!buf_equals(buf, n, "scoped")) {
            return true;
        }
    }
}

static bool scan_file_directive_prefix(TSLexer *lexer) {
    if (lexer->lookahead != '#') return false;
    advance(lexer);
    if (lexer->lookahead != ':') return false;
    advance(lexer);
    return true;
}

static bool scan_preproc_arg(TSLexer *lexer, bool opaque, enum TokenType symbol) {
    lexer->mark_end(lexer);
    while (!at_eof(lexer) && !is_line_terminator(lexer->lookahead)) {
        int32_t c = lexer->lookahead;
        advance(lexer);
        if (!opaque && c == '/') {
            if (lexer->lookahead == '*') break;
            if (at_eof(lexer) || is_line_terminator(lexer->lookahead)) {
                lexer->mark_end(lexer);
                break;
            }
            advance(lexer);
        }
        lexer->mark_end(lexer);
    }
    lexer->result_symbol = symbol;
    return true;
}

static bool is_directive_horizontal(int32_t c);
static bool scan_file_directive_kind(TSLexer *lexer);
static bool scan_pragma_boundary(TSLexer *lexer);
static bool scan_pragma_text(TSLexer *lexer);
static bool scan_preproc_inactive(TSLexer *lexer);
static bool scan_question(TSLexer *lexer, const bool *valid_symbols);

typedef enum {
    QUESTION_NOT_STARTED,
    QUESTION_MATCHED,
    QUESTION_MISMATCHED,
} QuestionScanResult;

static void advance_identifier(TSLexer *lexer);
static int32_t advance_skipping_literal(TSLexer *lexer);

#include "awaitIdentifier.h"
#include "recordKeyword.h"

static bool scan_less_than(TSLexer *lexer, const bool *valid_symbols);
static bool scan_recovery(Scanner *scanner, TSLexer *lexer, bool next_file_directive);

bool tree_sitter_c_sharp_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) {
    Scanner *scanner = (Scanner *)payload;

    uint8_t brace_advanced = 0;
    uint8_t quote_count = 0;
    bool did_advance = false;

    bool next_file_directive = scanner->next_file_directive;
    scanner->next_file_directive = false;
    if (valid_symbols[OPT_SEMI] && valid_symbols[INTERPOLATION_REGULAR_START]) {
        return scan_recovery(scanner, lexer, next_file_directive);
    }

    if (valid_symbols[PRAGMA_BOUNDARY]) return scan_pragma_boundary(lexer);
    if (valid_symbols[PRAGMA_TEXT]) {
        while (is_directive_horizontal(lexer->lookahead)) skip(lexer);
        if (!at_eof(lexer) && !is_line_terminator(lexer->lookahead)) return scan_pragma_text(lexer);
    }

    // Outside directives and literals, where FILE_DIRECTIVE_LITERAL_CONTEXT is valid, a `#` starts a directive. Skipping
    // whitespace before a zero-width OPT_SEMI would extend the node that ends with it.
    if (valid_symbols[PREPROC_INACTIVE] && !valid_symbols[OPT_SEMI] && !valid_symbols[FILE_DIRECTIVE_LITERAL_CONTEXT] &&
        !valid_symbols[FILE_DIRECTIVE_PREPROC_ARG] && !valid_symbols[END_OF_INPUT] && !valid_symbols[DIRECTIVE_NEWLINE] &&
        !valid_symbols[FILE_DIRECTIVE_NEWLINE] && !valid_symbols[RAW_STRING_CONTENT] && !valid_symbols[INTERPOLATION_STRING_CONTENT]) {
        while (is_directive_horizontal(lexer->lookahead) || is_line_terminator(lexer->lookahead)) skip(lexer);
        if (lexer->lookahead == '#') {
            advance(lexer);
            if (lexer->lookahead != ':') return scan_preproc_inactive(lexer);
            advance(lexer);
            return valid_symbols[FILE_DIRECTIVE_KIND] && scan_file_directive_kind(lexer);
        }
    }

    QuestionScanResult word = scan_contextual_word(lexer, valid_symbols);
    if (word != QUESTION_NOT_STARTED) return word == QUESTION_MATCHED;

    if ((valid_symbols[CONDITIONAL_ACCESS_QUESTION] || valid_symbols[NULLABLE_QUESTION] || valid_symbols[TERNARY_QUESTION] ||
         valid_symbols[CREATION_NULLABLE_QUESTION]) &&
        !valid_symbols[OPT_SEMI]) {
        while (is_unicode_whitespace(lexer->lookahead)) skip(lexer);
        if (lexer->lookahead == '?') return scan_question(lexer, valid_symbols);
    }

    if ((valid_symbols[TYPE_LIST_OPEN] || valid_symbols[LESS_THAN]) && !valid_symbols[OPT_SEMI]) {
        while (is_unicode_whitespace(lexer->lookahead)) skip(lexer);
        if (lexer->lookahead == '<') return scan_less_than(lexer, valid_symbols);
    }

    if (valid_symbols[LAMBDA_PAREN_OPEN]) {
        LambdaScanResult lambda = scan_lambda_paren_open(lexer);
        if (lambda != LAMBDA_SCAN_NO_PAREN) return lambda == LAMBDA_SCAN_SUCCESS;
    }

    if (valid_symbols[FILE_DIRECTIVE_PREPROC_ARG]) {
        while (lexer->lookahead == ' ' || lexer->lookahead == '\t' || lexer->lookahead == '\v' || lexer->lookahead == '\f') skip(lexer);
        while (is_space_but_line_feed(lexer->lookahead) && !is_line_terminator(lexer->lookahead)) advance(lexer);
        if (lexer->lookahead == '#') return scan_file_directive_prefix(lexer) && scan_preproc_arg(lexer, false, FILE_DIRECTIVE_PREPROC_ARG);
    }
    if (valid_symbols[DIRECTIVE_NEWLINE] || valid_symbols[FILE_DIRECTIVE_NEWLINE]) {
        while (is_directive_horizontal(lexer->lookahead)) skip(lexer);
        if (is_line_terminator(lexer->lookahead)) {
            bool cr = lexer->lookahead == '\r';
            advance(lexer);
            bool crlf = cr && lexer->lookahead == '\n';
            if (crlf) advance(lexer);
            lexer->mark_end(lexer);
            if (!valid_symbols[FILE_DIRECTIVE_NEWLINE] && !crlf) {
                while (is_line_terminator(lexer->lookahead)) advance(lexer);
                lexer->mark_end(lexer);
            }
            while (is_directive_horizontal(lexer->lookahead) || is_line_terminator(lexer->lookahead)) advance(lexer);
            scanner->next_file_directive = scan_file_directive_prefix(lexer);
            lexer->result_symbol = valid_symbols[FILE_DIRECTIVE_NEWLINE] ? FILE_DIRECTIVE_NEWLINE : DIRECTIVE_NEWLINE;
            return true;
        }
    }

    // A directive may end the input without a line break, which no regex token can match.
    if (valid_symbols[END_OF_INPUT]) {
        while (is_space_but_line_feed(lexer->lookahead)) skip(lexer);
        lexer->result_symbol = END_OF_INPUT;
        return at_eof(lexer);
    }

    if (valid_symbols[OPT_SEMI]) {
        lexer->result_symbol = OPT_SEMI;
        if (lexer->lookahead == ';') advance(lexer);
        return true;
    }

    if (valid_symbols[RAW_STRING_START]) {
        while (is_unicode_whitespace(lexer->lookahead)) skip(lexer);

        if (lexer->lookahead == '"') {
            while (lexer->lookahead == '"') {
                advance(lexer);
                quote_count++;
            }

            if (quote_count >= 3) {
                lexer->result_symbol = RAW_STRING_START;
                scanner->quote_count = quote_count;
                return true;
            }
        }
    }

    if (valid_symbols[RAW_STRING_END] && lexer->lookahead == '"') {
        while (lexer->lookahead == '"') {
            advance(lexer);
            quote_count++;
        }

        if (quote_count == scanner->quote_count) {
            lexer->result_symbol = RAW_STRING_END;
            scanner->quote_count = 0;
            return true;
        }

        did_advance = quote_count > 0;
    }

    if (valid_symbols[RAW_STRING_CONTENT]) {
        while (!at_eof(lexer)) {
            if (lexer->lookahead == '"') {
                lexer->mark_end(lexer);
                quote_count = 0;

                while (lexer->lookahead == '"') {
                    advance(lexer);
                    quote_count++;
                }

                if (quote_count == scanner->quote_count) {
                    lexer->result_symbol = RAW_STRING_CONTENT;
                    return true;
                }
            }
            advance(lexer);
            did_advance = true;
        }
        lexer->mark_end(lexer);
        lexer->result_symbol = RAW_STRING_CONTENT;
        return true;
    }

    if (valid_symbols[INTERPOLATION_REGULAR_START] || valid_symbols[INTERPOLATION_VERBATIM_START] ||
        valid_symbols[INTERPOLATION_RAW_START]) {
        while (is_unicode_whitespace(lexer->lookahead)) skip(lexer);

        uint8_t dollar_advanced = 0;

        bool is_verbatim = false;

        if (lexer->lookahead == '@') {
            is_verbatim = true;
            advance(lexer);
        }

        while (lexer->lookahead == '$' && quote_count == 0) {
            advance(lexer);
            dollar_advanced++;
        }

        if (dollar_advanced > 0 && (lexer->lookahead == '"' || lexer->lookahead == '@')) {
            lexer->result_symbol = INTERPOLATION_REGULAR_START;
            Interpolation interpolation = {
                .dollar_count = dollar_advanced,
                .open_brace_count = 0,
                .quote_count = 0,
                .string_type = 0,
            };

            if (is_verbatim || lexer->lookahead == '@') {
                if (lexer->lookahead == '@') {
                    advance(lexer);
                    is_verbatim = true;
                }
                lexer->result_symbol = INTERPOLATION_VERBATIM_START;
                interpolation.string_type = VERBATIM;
            }

            lexer->mark_end(lexer);
            advance(lexer);
            interpolation.string_type |= REGULAR;

            if (lexer->lookahead == '"' && !is_verbatim) {
                advance(lexer);
                if (lexer->lookahead == '"') {
                    lexer->result_symbol = INTERPOLATION_RAW_START;
                    interpolation.string_type = RAW;
                }
            }
            array_push(&scanner->interpolation_stack, interpolation);

            return true;
        }
    }

    if (valid_symbols[INTERPOLATION_START_QUOTE] && scanner->interpolation_stack.size > 0) {
        Interpolation *current_interpolation = array_back(&scanner->interpolation_stack);

        while (lexer->lookahead == '"') {
            advance(lexer);
            current_interpolation->quote_count++;
            if (is_verbatim(current_interpolation) || is_regular(current_interpolation)) break;
        }

        lexer->result_symbol = INTERPOLATION_START_QUOTE;
        return current_interpolation->quote_count > 0;
    }

    if (valid_symbols[INTERPOLATION_END_QUOTE] && scanner->interpolation_stack.size > 0) {
        Interpolation *current_interpolation = array_back(&scanner->interpolation_stack);

        while (lexer->lookahead == '"') {
            advance(lexer);
            quote_count++;
            if (is_verbatim(current_interpolation) && quote_count == 2) {
                lexer->mark_end(lexer);
                did_advance = true;
                quote_count = 0;
            }
        }

        if (is_verbatim(current_interpolation) && did_advance && quote_count == 1) {
            lexer->result_symbol = INTERPOLATION_STRING_CONTENT;
            return valid_symbols[INTERPOLATION_STRING_CONTENT];
        }

        if (quote_count == current_interpolation->quote_count) {
            lexer->result_symbol = INTERPOLATION_END_QUOTE;
            array_pop(&scanner->interpolation_stack);
            return true;
        }

        did_advance = did_advance || quote_count > 0;
    }

    if (valid_symbols[INTERPOLATION_OPEN_BRACE] && scanner->interpolation_stack.size > 0) {
        Interpolation *current_interpolation = array_back(&scanner->interpolation_stack);

        if (did_advance) lexer->mark_end(lexer);

        while (lexer->lookahead == '{' && brace_advanced < current_interpolation->dollar_count) {
            advance(lexer);
            brace_advanced++;
            if (is_raw(current_interpolation) && !did_advance && brace_advanced == 1) lexer->mark_end(lexer);
        }

        if (!is_raw(current_interpolation) && brace_advanced == 1 && lexer->lookahead == '{') {
            advance(lexer);
            brace_advanced = 0;
            did_advance = true;
        }

        if (is_raw(current_interpolation) && brace_advanced == current_interpolation->dollar_count && lexer->lookahead == '{') {
            lexer->result_symbol = INTERPOLATION_STRING_CONTENT;
            return valid_symbols[INTERPOLATION_STRING_CONTENT];
        }

        if (brace_advanced > 0 && brace_advanced == current_interpolation->dollar_count &&
            (brace_advanced == 0 || lexer->lookahead != '{')) {
            if (did_advance) {
                lexer->result_symbol = INTERPOLATION_STRING_CONTENT;
                return valid_symbols[INTERPOLATION_STRING_CONTENT];
            }
            lexer->mark_end(lexer);
            current_interpolation->open_brace_count = brace_advanced;
            lexer->result_symbol = INTERPOLATION_OPEN_BRACE;
            return true;
        }
    }

    if (valid_symbols[INTERPOLATION_CLOSE_BRACE] && scanner->interpolation_stack.size > 0) {
        uint8_t brace_advanced = 0;
        Interpolation *current_interpolation = array_back(&scanner->interpolation_stack);

        while (is_unicode_whitespace(lexer->lookahead)) advance(lexer);

        while (lexer->lookahead == '}') {
            advance(lexer);
            brace_advanced++;

            if (brace_advanced == current_interpolation->open_brace_count) {
                current_interpolation->open_brace_count = 0;
                lexer->mark_end(lexer);
                lexer->result_symbol = INTERPOLATION_CLOSE_BRACE;
                return true;
            }
        }

        return false;
    }

    if (valid_symbols[INTERPOLATION_STRING_CONTENT] && scanner->interpolation_stack.size > 0) {
        lexer->result_symbol = INTERPOLATION_STRING_CONTENT;
        Interpolation *current_interpolation = array_back(&scanner->interpolation_stack);
        bool raw = is_raw(current_interpolation);
        bool verbatim = !raw && is_verbatim(current_interpolation);
        bool regular = !raw && !verbatim && is_regular(current_interpolation);

        while (!at_eof(lexer)) {
            if (raw) {
                if (lexer->lookahead == '"') {
                    lexer->mark_end(lexer);
                    advance(lexer);
                    if (lexer->lookahead == '"') {
                        advance(lexer);
                        uint8_t quote_advanced = 2;
                        while (lexer->lookahead == '"') {
                            quote_advanced++;
                            advance(lexer);
                        }
                        if (quote_advanced == current_interpolation->quote_count) return did_advance;
                    }
                }
            } else if (verbatim) {
                if (lexer->lookahead == '"') {
                    lexer->mark_end(lexer);
                    advance(lexer);
                    if (lexer->lookahead != '"') return did_advance;
                    advance(lexer);
                    did_advance = true;
                    continue;
                }
            } else if (regular) {
                if (lexer->lookahead == '\\' || is_line_terminator(lexer->lookahead) || lexer->lookahead == '"') {
                    lexer->mark_end(lexer);
                    return did_advance;
                }
            }

            if ((raw || verbatim || regular) && lexer->lookahead == '{') {
                lexer->mark_end(lexer);
                while (lexer->lookahead == '{' && brace_advanced < current_interpolation->open_brace_count) {
                    advance(lexer);
                    brace_advanced++;
                }
                if (brace_advanced == current_interpolation->open_brace_count &&
                    (brace_advanced == 0 || lexer->lookahead != '{')) {
                    return did_advance;
                }
            }

            if (lexer->lookahead != '{') brace_advanced = 0;
            advance(lexer);
            did_advance = true;
        }

        lexer->mark_end(lexer);
        return did_advance;
    }

    return false;
}

static bool is_directive_horizontal(int32_t c) {
    return c == ' ' || c == '\t' || c == '\v' || c == '\f' || c == 0xA0 || c == 0x1680 ||
        (c >= 0x2000 && c <= 0x200A) || c == 0x202F || c == 0x205F || c == 0x3000 || c == 0xFEFF;
}

#include "pragmaDirectives.h"

// code-gauge-allow functionCognitiveComplexity -- Directive-kind recognition and fallback share the source line and marked token end.
static bool scan_file_directive_kind(TSLexer *lexer) {
    char kind[9] = {0};
    unsigned length = 0;
    while (!at_eof(lexer) && !is_directive_horizontal(lexer->lookahead) && !is_line_terminator(lexer->lookahead)) {
        int32_t c = lexer->lookahead;
        if (c >= 'A' && c <= 'Z') c += 'a' - 'A';
        if (length < sizeof(kind) - 1) kind[length] = c > 0 && c < 128 ? c : '?';
        if (length < sizeof(kind)) length++;
        advance(lexer);
    }
    const char *kinds[] = {"sdk", "package", "property", "project", "ref", "include", "exclude"};
    lexer->result_symbol = FILE_DIRECTIVE_KIND;
    if (length < sizeof(kind)) {
        for (unsigned i = 0; i < sizeof(kinds) / sizeof(kinds[0]); i++) {
            if (!strcmp(kind, kinds[i])) {
                lexer->result_symbol = FILE_DIRECTIVE_SDK + i;
                break;
            }
        }
    }
    lexer->mark_end(lexer);
    return true;
}

// code-gauge-allow functionCognitiveComplexity -- Quote-width and brace-count synchronization share the active interpolation frame.
// code-gauge-allow functionNcss -- Quote-width and brace-count synchronization share the active interpolation frame.
static bool scan_interpolation_recovery(Scanner *scanner, TSLexer *lexer) {
    Interpolation *interpolation = array_back(&scanner->interpolation_stack);
    bool closes_hole = lexer->lookahead == '}';
    bool line_end = false;
    if (closes_hole) {
        if (!interpolation->open_brace_count) return false;
        unsigned braces = 0;
        while (lexer->lookahead == '}' && braces < interpolation->open_brace_count) {
            advance(lexer);
            braces++;
        }
        if (braces != interpolation->open_brace_count) return false;
        lexer->mark_end(lexer);
        if (is_regular(interpolation) && !is_verbatim(interpolation)) {
            while (is_directive_horizontal(lexer->lookahead)) advance(lexer);
            line_end = is_line_terminator(lexer->lookahead);
        }
    }
    unsigned quotes = 0;
    while (lexer->lookahead == '"' && quotes < interpolation->quote_count) {
        advance(lexer);
        quotes++;
    }
    if (!line_end && (!quotes || quotes != interpolation->quote_count || lexer->lookahead == '"')) return false;
    if (closes_hole) {
        interpolation->open_brace_count = 0;
        lexer->result_symbol = INTERPOLATION_CLOSE_BRACE;
    } else {
        array_pop(&scanner->interpolation_stack);
        lexer->result_symbol = INTERPOLATION_END_QUOTE;
    }
    return true;
}

static bool scan_recovery(Scanner *scanner, TSLexer *lexer, bool next_file_directive) {
    bool line_start = next_file_directive;
    while (is_directive_horizontal(lexer->lookahead) || is_line_terminator(lexer->lookahead)) {
        if (is_line_terminator(lexer->lookahead)) line_start = true;
        skip(lexer);
    }
    if (scanner->interpolation_stack.size && (lexer->lookahead == '"' || lexer->lookahead == '}')) {
        return scan_interpolation_recovery(scanner, lexer);
    }
    if (lexer->lookahead != '#') return false;
    advance(lexer);
    if (lexer->lookahead != ':') return scan_preproc_inactive(lexer);
    advance(lexer);
    return line_start ? scan_file_directive_kind(lexer) : scan_preproc_arg(lexer, true, FILE_DIRECTIVE_PREPROC_ARG);
}

#include "preprocInactive.h"

typedef char QuestionKeyword[sizeof("stackalloc")];

static bool is_word(const char *word, size_t length, const QuestionKeyword *words, size_t count) {
    if (length >= sizeof *words) return false;
    for (size_t i = 0; i < count; i++) {
        if (buf_equals(word, length, words[i])) return true;
    }
    return false;
}

// Skips a type parameter list, which the lexer is at, spending the shared lookahead budget. Attribute groups on the
// parameters may hold any argument tokens.
static bool skip_type_parameters(TSLexer *lexer, unsigned *budget) {
    for (unsigned angles = 0, brackets = 0; *budget > 0; (*budget)--) {
        if (skip_ws_and_comments(lexer) && brackets == 0) return false;
        int32_t c = lexer->lookahead;
        if (at_eof(lexer) || (brackets == 0 && !is_id_continue(c) && !is_ascii_in(c, "<>,[]@"))) return false;
        c = advance_skipping_literal(lexer);
        brackets += (c == '[') - (c == ']');
        if (brackets == 0) angles += (c == '<') - (c == '>');
        if (brackets == 0 && c == '>' && angles == 0) return true;
    }
    return false;
}

// Whether a local function body or constraint, `{`, `=>`, or `where`, follows the parameter list the lexer is after.
static bool local_function_body_follows(TSLexer *lexer) {
    if (skip_ws_and_comments(lexer)) return false;
    if (lexer->lookahead == '{') return true;
    if (lexer->lookahead == '=') {
        advance(lexer);
        return lexer->lookahead == '>';
    }
    char word[6];
    size_t length = consume_identifier_into(lexer, word, sizeof word);
    return buf_equals(word, length, "where");
}

// Skips the rest of a verbatim string after its `@"`: it spans lines and escapes a quote by doubling it.
static void skip_verbatim_string(TSLexer *lexer) {
    while (!at_eof(lexer)) {
        int32_t c = lexer->lookahead;
        advance(lexer);
        if (c == '"' && lexer->lookahead != '"') return;
        if (c == '"') advance(lexer);
    }
}

// Skips the rest of a raw string after its opening run of `quotes` quotes, through a run of as many.
static void skip_raw_string(TSLexer *lexer, unsigned quotes) {
    while (lexer->lookahead == '"') {
        quotes++;
        advance(lexer);
    }
    for (unsigned run = 0; !at_eof(lexer) && run < quotes;) {
        run = lexer->lookahead == '"' ? run + 1 : 0;
        advance(lexer);
    }
}

// Skips the rest of a regular string or character literal closed by `quote` on the same line.
static void skip_quoted_literal(TSLexer *lexer, int32_t quote) {
    while (!at_eof(lexer) && !is_line_terminator(lexer->lookahead) && lexer->lookahead != quote) {
        if (lexer->lookahead == '\\') advance(lexer);
        advance(lexer);
    }
    advance(lexer);
}

// Advances past a character, skipping a whole comment or string or character literal, whose punctuation does not count.
// Returns the character, or 0 after a comment.
static int32_t advance_skipping_literal(TSLexer *lexer) {
    int32_t c = lexer->lookahead;
    advance(lexer);
    if (c == '/' && (lexer->lookahead == '/' || lexer->lookahead == '*')) {
        if (lexer->lookahead == '/') skip_line_comment(lexer);
        else skip_block_comment(lexer);
        return 0;
    }
    if (c == '@' && lexer->lookahead == '"') {
        advance(lexer);
        skip_verbatim_string(lexer);
        return '"';
    }
    if (c == '"' && lexer->lookahead == '"') {
        advance(lexer);
        // `""` is an empty string, and a third quote opens a raw string.
        if (lexer->lookahead == '"') skip_raw_string(lexer, 2);
        return c;
    }
    if (c == '"' || c == '\'') skip_quoted_literal(lexer, c);
    return c;
}

// Whether a local function's type parameters and parameter list, which the lexer is at, follow, with its body or a
// constraint after them. A shared step budget bounds the look to keep parsing linear.
static bool parameter_list_follows(TSLexer *lexer) {
    unsigned budget = 1024;
    if (lexer->lookahead == '<') {
        if (!skip_type_parameters(lexer, &budget) || skip_ws_and_comments(lexer)) return false;
        if (lexer->lookahead != '(') return false;
    }
    for (unsigned depth = 0; budget > 0 && !at_eof(lexer); budget--) {
        int32_t c = advance_skipping_literal(lexer);
        if (c == '(') depth++;
        if (c == ')' && --depth == 0) return local_function_body_follows(lexer);
    }
    return false;
}

typedef enum {
    TERNARY,
    NULLABLE,
    // Only the parse context tells a declaration (`T? x = y;`, `T? when = y;`) from a ternary operand (`c ? x = y : z`,
    // `c ? when : z`) or a pattern (`x is T? and not null`).
    NULLABLE_OR_TERNARY,
} QuestionReading;

// Reads the tokens after a name, which the lexer is after: a declaration end (`;`, `,`, `)`) ends a nullable type.
static QuestionReading declaration_end_follows(TSLexer *lexer) {
    if (is_ascii_in(lexer->lookahead, ";,)")) return NULLABLE;
    if (lexer->lookahead != '=') return TERNARY;
    advance(lexer);
    return lexer->lookahead == '=' || lexer->lookahead == '>' ? TERNARY : NULLABLE_OR_TERNARY;
}

// Reads the tokens after a name, which the lexer is after: a declaration end or a local function's or property's body
// ends a nullable type before the name.
static QuestionReading name_ends_type(TSLexer *lexer) {
    static const QuestionKeyword operators[] = {"is", "as", "switch", "with"};
    if (lexer->lookahead == '{' || lexer->lookahead == '@') return NULLABLE;
    if (lexer->lookahead == '(' || lexer->lookahead == '<') return parameter_list_follows(lexer) ? NULLABLE : TERNARY;
    if (!is_id_start(lexer->lookahead)) return declaration_end_follows(lexer);
    char word[7];
    size_t length = consume_identifier_into(lexer, word, sizeof word);
    return length <= sizeof word && is_word(word, length, operators, sizeof operators / sizeof *operators) ? TERNARY
                                                                                                         : NULLABLE;
}

// Reads a `?` after a type, followed by an identifier: the identifier names a declaration or a local function, or is a
// keyword that continues a pattern or an expression after a type.
static QuestionReading identifier_follows_type(TSLexer *lexer, bool verbatim) {
    static const QuestionKeyword expression_starts[] = {
        "new", "typeof", "default", "null", "true", "false", "this", "base", "sizeof", "checked", "unchecked",
        "throw", "stackalloc", "delegate", "ref", "static",
        // A predefined type after `?` starts a typed lambda or a member access, never a declaration name.
        "bool", "byte", "char", "decimal", "double", "float", "int", "long", "object", "sbyte", "short", "string",
        "uint", "ulong", "ushort", "void",
    };
    static const QuestionKeyword type_followers[] = {"in", "is", "as", "switch"};
    // Contextual keywords may also name a declaration (`DateTime? from = null;`) or be an operand (`c ? when : d`).
    static const QuestionKeyword contextual[] = {"await", "async", "from", "not", "nameof", "and", "or", "when", "where", "with"};
    QuestionKeyword word;
    size_t length = consume_identifier_into(lexer, word, sizeof word);
    // A verbatim identifier (`@await`) is never a keyword.
    bool keyword = !verbatim && length < sizeof word;
    if (keyword && is_word(word, length, contextual, sizeof contextual / sizeof *contextual)) return NULLABLE_OR_TERNARY;
    if (keyword && is_word(word, length, expression_starts, sizeof expression_starts / sizeof *expression_starts)) {
        return TERNARY;
    }
    if (keyword && is_word(word, length, type_followers, sizeof type_followers / sizeof *type_followers)) return NULLABLE;
    // A division after the word makes it an operand.
    return skip_ws_and_comments(lexer) ? TERNARY : name_ends_type(lexer);
}

// Consumes the rest of an identifier, including Unicode escapes (`\u0061`), which appear nowhere else outside literals.
static void advance_identifier(TSLexer *lexer) {
    while (is_id_continue(lexer->lookahead) || lexer->lookahead == '\\') advance(lexer);
}

// Whether `=>` follows after trivia.
static bool arrow_follows(TSLexer *lexer) {
    if (skip_ws_and_comments(lexer) || lexer->lookahead != '=') return false;
    advance(lexer);
    return lexer->lookahead == '>';
}

typedef enum {
    HEADER_NAME_LAMBDA,
    HEADER_NAME_NOT_LAMBDA,
    HEADER_NAME_TYPE,
} HeaderName;

// Reads what follows a top-level name in a lambda header, which the lexer is after: `=>` after a lone parameter
// (`x =>`), which only a name before any return type can be, or the rest of a return type.
static HeaderName read_header_name(TSLexer *lexer, bool typed) {
    if (skip_ws_and_comments(lexer)) return HEADER_NAME_NOT_LAMBDA;
    if (typed || lexer->lookahead != '=') return HEADER_NAME_TYPE;
    return arrow_follows(lexer) ? HEADER_NAME_LAMBDA : HEADER_NAME_NOT_LAMBDA;
}

// Whether the rest of a lambda follows attributes, which the lexer is after: further attribute lists, `static` or
// `async`, then a parameter and `=>`, or an optional return type and a parameter list followed directly by `=>`. The
// look stops after a bounded number of tokens.
// code-gauge-allow functionCognitiveComplexity -- Attribute, modifier, type, and parameter groups share one bounded scan.
static bool lambda_follows(TSLexer *lexer) {
    unsigned depth = 0;
    bool typed = false;
    for (unsigned budget = 128; budget > 0 && !at_eof(lexer); budget--) {
        // A division inside a parameter or attribute group belongs to a default or argument value.
        if (skip_ws_and_comments(lexer) && depth == 0) return false;
        bool identifier = is_id_start(lexer->lookahead) || lexer->lookahead == '@';
        int32_t c = advance_skipping_literal(lexer);
        if (identifier) {
            advance_identifier(lexer);
            if (depth > 0) continue;
            HeaderName name = read_header_name(lexer, typed);
            if (name != HEADER_NAME_TYPE) return name == HEADER_NAME_LAMBDA;
            typed = true;
        } else if (c == '(' || c == '[' || c == '<') {
            depth++;
        } else if (c == ')' || c == ']' || c == '>') {
            if (depth-- == 0) return false;
            // A parameter list ends the header; only `=>` may follow it.
            if (depth == 0 && c == ')') return arrow_follows(lexer);
        } else if (depth == 0 && !is_ascii_in(c, ".?*,")) {
            return false;
        }
    }
    return false;
}

typedef enum {
    BRACKET_INDEX,
    BRACKET_ARM,
    BRACKET_UNDECIDED,
} BracketFollower;

// Reads what follows the closing `]` of the bracket after a spaced `?`, which the lexer is after.
static BracketFollower read_bracket_follower(TSLexer *lexer) {
    if (skip_ws_and_comments(lexer)) return BRACKET_UNDECIDED;
    // A collection expression has no members, so a member access after the bracket indexes (`calls ? [i].Name`).
    if (lexer->lookahead == '.') return BRACKET_INDEX;
    // Attributes before a lambda start a ternary arm (`c ? [A] static () => x : y`); an index can be called.
    if (lexer->lookahead == '(' || lexer->lookahead == '[' || is_id_start(lexer->lookahead)) {
        return lambda_follows(lexer) ? BRACKET_ARM : BRACKET_INDEX;
    }
    return BRACKET_UNDECIDED;
}

// Whether a bracket after a spaced `?`, which the lexer is at, indexes the operand before `?` (`items ? [key]`) rather
// than starting a collection arm of a ternary, which a `:` outside brackets follows before the expression or argument
// ends, except at the top of an interpolation hole, where that `:` starts the format. The look stops after a bounded
// number of tokens to keep parsing linear.
// code-gauge-allow functionCognitiveComplexity -- Bracket depth and the expression end share one bounded forward scan.
// code-gauge-allow functionNcss -- Bracket depth and the expression end share one bounded forward scan.
static bool spaced_index_follows(TSLexer *lexer, bool in_interpolation, bool *empty_rank) {
    advance(lexer);
    if (skip_ws_and_comments(lexer)) return false;
    *empty_rank = lexer->lookahead == ']' || lexer->lookahead == ',';
    if (*empty_rank) return false;
    unsigned depth = 1;
    for (unsigned budget = 128; budget > 0; budget--) {
        // A division is no bracket or separator, so the slash it consumed needs no further look.
        skip_ws_and_comments(lexer);
        if (at_eof(lexer)) return true;
        bool identifier = is_id_continue(lexer->lookahead);
        int32_t c = advance_skipping_literal(lexer);
        if (identifier) {
            advance_identifier(lexer);
        } else if (c == '(' || c == '[' || c == '{') {
            depth++;
        } else if (c == ')' || c == ']' || c == '}') {
            if (depth-- == 0) return true;
            if (depth > 0 || c != ']') continue;
            BracketFollower follower = read_bracket_follower(lexer);
            if (follower != BRACKET_UNDECIDED) return follower == BRACKET_INDEX;
        } else if (depth == 0 && (c == ';' || c == ',')) {
            return true;
        } else if (depth == 0 && c == ':') {
            // A ternary cannot sit unparenthesized at the top of an interpolation hole, so a colon there starts the format.
            if (lexer->lookahead != ':') return in_interpolation;
            advance(lexer);
        }
    }
    // An inconclusive look keeps the more common ternary reading.
    return false;
}

static bool select_question(TSLexer *lexer, const bool *valid_symbols, QuestionReading reading);

// Reads the role of a `?` that trivia separates from a following `[`, which the lexer is at: part of the element type in
// an array creation (`new byte[]? [n]`), a nullable array type or an empty collection arm before an empty rank
// (`DateOnly? []`, `c ? [] : x`), which only the parse context tells apart, or an index or a collection arm.
static QuestionReading read_spaced_bracket(TSLexer *lexer, const bool *valid_symbols, bool *access) {
    if (valid_symbols[CREATION_NULLABLE_QUESTION]) return NULLABLE;
    bool empty_rank = false;
    *access = spaced_index_follows(lexer, valid_symbols[INTERPOLATION_CLOSE_BRACE], &empty_rank);
    return empty_rank ? NULLABLE_OR_TERNARY : TERNARY;
}

// Whether an empty rank (`[]` or `[,`) starts at the `[` the lexer is at.
static bool empty_rank_follows(TSLexer *lexer) {
    advance(lexer);
    return !skip_ws_and_comments(lexer) && (lexer->lookahead == ']' || lexer->lookahead == ',');
}

// Like `skip_ws_and_comments`, also skipping directive lines, which may sit between any two tokens (`#pragma` inside a
// member chain, `#line` and `#nullable` around each type argument that Razor generates).
static bool skip_trivia_and_directives(TSLexer *lexer) {
    while (!skip_ws_and_comments(lexer)) {
        if (lexer->lookahead != '#') return false;
        advance_to_line_end(lexer);
    }
    return true;
}

static QuestionReading read_question_operand(TSLexer *lexer);

// The lexer is at `?` in a position that admits a nullable type, a conditional expression, or a conditional access.
// Reads it as conditional access when `.` follows other than as the start of a number or a range, or when `[` directly
// follows other than as an array rank specifier (`T?[]`, `T?[,]`); a `[` after trivia, which usually starts the
// collection arm of a ternary (`c ? [] : x`), is an index only when `spaced_index_follows` says so. In an array
// creation, `[` after `?` continues the element type (`new byte[]?[n]`).
// A chain may break the line between `?` and `.`. Otherwise, where both a
// nullable type and a conditional expression fit, it ends the type unless the next token starts an expression, as the
// C# compiler decides after `is` and `as`, except that an identifier that a declaration end or a local function body
// follows also ends the type, and that the parser decides where an initializer or a contextual keyword follows.
// code-gauge-allow functionCognitiveComplexity -- Bracket adjacency and parser-valid roles decide the token in one scan.
static bool scan_question(TSLexer *lexer, const bool *valid_symbols) {
    advance(lexer);
    lexer->mark_end(lexer);
    if (lexer->lookahead == '?') return false;
    bool access = false;
    QuestionReading reading = TERNARY;
    if (lexer->lookahead == '[') {
        // In an array creation, a rank continues the element type: `new byte[]?[n]`.
        if (valid_symbols[CREATION_NULLABLE_QUESTION] || empty_rank_follows(lexer)) reading = NULLABLE;
        else access = true;
    } else if (skip_trivia_and_directives(lexer)) {
        // A division cannot start an operand.
        reading = NULLABLE;
    } else if (lexer->lookahead == '.') {
        advance(lexer);
        access = !(lexer->lookahead >= '0' && lexer->lookahead <= '9') && lexer->lookahead != '.';
    } else if (lexer->lookahead == '[') {
        reading = read_spaced_bracket(lexer, valid_symbols, &access);
    } else if (valid_symbols[CREATION_NULLABLE_QUESTION] || (valid_symbols[NULLABLE_QUESTION] && valid_symbols[TERNARY_QUESTION])) {
        reading = read_question_operand(lexer);
    }
    if (access && valid_symbols[CONDITIONAL_ACCESS_QUESTION]) {
        lexer->result_symbol = CONDITIONAL_ACCESS_QUESTION;
        return true;
    }
    return select_question(lexer, valid_symbols, reading);
}

static QuestionReading read_question_operand(TSLexer *lexer) {
    int32_t c = lexer->lookahead;
    if (c == '(') return parameter_list_follows(lexer) ? NULLABLE_OR_TERNARY : TERNARY;
    if (c == '&' || c == '!') {
        advance(lexer);
        return lexer->lookahead == (c == '&' ? '&' : '=') ? NULLABLE : TERNARY;
    }
    if (c == '@') advance(lexer);
    if (c == '@' || is_id_start(c)) return identifier_follows_type(lexer, c == '@');
    return at_eof(lexer) || is_ascii_in(c, ")]},;:=><|?{%") ? NULLABLE : TERNARY;
}

// Emits the `?` of the reading among those the parser accepts here.
static bool select_question(TSLexer *lexer, const bool *valid_symbols, QuestionReading reading) {
    bool both = valid_symbols[NULLABLE_QUESTION] && valid_symbols[TERNARY_QUESTION];
    if (reading == NULLABLE && valid_symbols[CREATION_NULLABLE_QUESTION]) {
        lexer->result_symbol = CREATION_NULLABLE_QUESTION;
    } else if (reading == NULLABLE_OR_TERNARY && both) {
        lexer->result_symbol = NULLABLE_OR_TERNARY_QUESTION;
    } else if (valid_symbols[NULLABLE_QUESTION] && (reading == NULLABLE || !valid_symbols[TERNARY_QUESTION])) {
        lexer->result_symbol = NULLABLE_QUESTION;
    } else if (valid_symbols[TERNARY_QUESTION]) {
        lexer->result_symbol = TERNARY_QUESTION;
    } else {
        return false;
    }
    return true;
}

typedef enum {
    COMPARISON,
    TYPE_ARGUMENTS,
    // An identifier follows `>`: a declaration (`out List<int> x`) or a second comparison (`F(a < b, c > d)`), which only
    // the parse context tells apart.
    TYPE_ARGUMENTS_OR_COMPARISON,
} LessThanReading;

// Reads the token after the closing `>` of type arguments: one of the followers that the C# compiler prefers as
// closing them (§6.2.5), such as `(`, `)`, `.` or `;`, does, even where a comparison could also continue with it.
static LessThanReading type_arguments_end(TSLexer *lexer) {
    if (skip_trivia_and_directives(lexer)) return COMPARISON;
    int32_t c = lexer->lookahead;
    if (is_id_start(c) || c == '@' || c == '\\') return TYPE_ARGUMENTS_OR_COMPARISON;
    if (c == '!' || c == '=') {
        advance(lexer);
        bool closes = lexer->lookahead == '=' || (c == '=' && lexer->lookahead == '>');
        return closes ? TYPE_ARGUMENTS : COMPARISON;
    }
    return at_eof(lexer) || is_ascii_in(c, "()]}:;,.?|^&[{*") ? TYPE_ARGUMENTS : COMPARISON;
}

// Whether a token cannot follow a complete type (a name, `?`, `]`, or `>`) in type arguments: only a tuple element name
// follows one without a separator, and a tuple type never does, so `(` after one is a call.
static bool follows_complete_type(int32_t c, bool identifier, unsigned parentheses) {
    return (identifier && parentheses == 0) || c == '(';
}

// Reads `<`, which the lexer is after, by whether type arguments close with `>` followed by one of the tokens that the
// C# compiler prefers as following type arguments in an expression (§6.2.5), approximating its rule with a lookahead
// that stops after a bounded number of tokens to keep parsing linear.
// code-gauge-allow functionCognitiveComplexity -- Bracket depths and identifier adjacency share one bounded forward scan.
// code-gauge-allow functionNcss -- Bracket depths and identifier adjacency share one bounded forward scan.
static LessThanReading type_arguments_follow(TSLexer *lexer) {
    unsigned angles = 1;
    unsigned parentheses = 0;
    bool after_identifier = false;
    for (unsigned budget = 128; budget > 0; budget--) {
        if (skip_trivia_and_directives(lexer) || at_eof(lexer)) return COMPARISON;
        int32_t c = lexer->lookahead;
        bool identifier = is_id_start(c) || c == '@' || c == '\\';
        if (after_identifier && follows_complete_type(c, identifier, parentheses)) return COMPARISON;
        after_identifier = identifier || c == '?' || c == ']' || c == '>';
        advance(lexer);
        if (identifier) {
            advance_identifier(lexer);
        } else if (c == '>') {
            if (--angles == 0) return parentheses == 0 ? type_arguments_end(lexer) : COMPARISON;
        } else if (c == '<') {
            angles++;
        } else if (c == '(') {
            parentheses++;
        } else if (c == ')') {
            if (parentheses-- == 0) return COMPARISON;
        } else if (c == ':') {
            if (lexer->lookahead != ':') return COMPARISON;
            advance(lexer);
        } else if (!is_ascii_in(c, ".,?*[]")) {
            return COMPARISON;
        }
    }
    return COMPARISON;
}

// The lexer is at `<` where type arguments or a comparison may follow. `<<`, `<=`, and `<<=` are left to the grammar.
static bool scan_less_than(TSLexer *lexer, const bool *valid_symbols) {
    advance(lexer);
    lexer->mark_end(lexer);
    if (lexer->lookahead == '<' || lexer->lookahead == '=') return false;
    LessThanReading reading = !valid_symbols[LESS_THAN] ? TYPE_ARGUMENTS
        : !valid_symbols[TYPE_LIST_OPEN]               ? COMPARISON
                                                       : type_arguments_follow(lexer);
    lexer->result_symbol = reading == TYPE_ARGUMENTS ? TYPE_LIST_OPEN
        : reading == COMPARISON                      ? LESS_THAN
                                                     : TYPE_LIST_OR_LESS_THAN;
    return true;
}