Repository navigation
Expand file tree
/
Copy pathscanner.h
More file actions
2279 lines (2161 loc) · 89.2 KB
/
Copy pathscanner.h
File metadata and controls
2279 lines (2161 loc) · 89.2 KB
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
#ifndef TREE_SITTER_FSHARP_SCANNER_H_
#define TREE_SITTER_FSHARP_SCANNER_H_
#include "tree_sitter/alloc.h"
#include "tree_sitter/array.h"
#include "tree_sitter/parser.h"
enum TokenType {
NEWLINE,
INDENT,
DEDENT,
THEN,
ELSE,
ELIF,
PREPROC_IF,
PREPROC_ELSE,
PREPROC_END,
CLASS,
BEGIN,
STRUCT,
INTERFACE,
END,
AND,
WITH,
TRIPLE_QUOTE_CONTENT,
FORMAT_TRIPLE_QUOTE_CONTENT,
BLOCK_COMMENT_CONTENT,
INSIDE_STRING,
NEWLINE_NO_ALIGNED,
TUPLE_MARKER,
QUOTED_CLOSE,
UNTYPED_QUOTED_CLOSE,
MULTI_DOLLAR_TRIPLE_QUOTE_START,
MULTI_DOLLAR_TRIPLE_QUOTED_CONTENT,
MULTI_DOLLAR_INTERP_START,
MULTI_DOLLAR_INTERP_END,
MULTI_DOLLAR_TRIPLE_QUOTE_END,
TYAPP_OPEN,
PAREN_INDENT,
TYPE_APP_INDENT,
TYPE_DECL_NEWLINE,
IN,
DO_KEYWORD,
TRY_INDENT,
PREPROC_INACTIVE,
ELEM_SEP,
BRACE_INDENT,
ERROR_SENTINEL
};
typedef enum {
INDENT_NORMAL = 0,
INDENT_PAREN = 1,
INDENT_TYPE_APP = 2,
// Body of a `try` expression. Behaves like a normal indent for all dedent
// logic, but can be force-closed when its terminating `with`/`finally` sits
// at the same column as the body (where an ordinary dedent would not fire).
INDENT_TRY = 3,
// Body of a `{...}` record / computation-expression block. Closed by '}'
// (never DEDENTs on under-indentation, like a paren indent), but an
// under-indented line still emits a NEWLINE so record/CE items keep
// separating even when a continuation item sits left of the first one.
INDENT_BRACE = 4,
} IndentKind;
// OR-ed into the indent_kinds byte when the scope's INDENT fired mid-line
// (no newline crossed before the anchor token), so the anchor column is a
// mid-line position like the `Some` in `let a = Some <|`. A continuation
// line that sits strictly BETWEEN such an anchor and the enclosing level is
// part of the expression (F# offside is measured from the construct start,
// not the anchor), so DEDENT must not fire into it.
#define INDENT_KIND_MIDLINE_FLAG 0x80
// OR-ed into the indent_kinds byte when a mid-line scope was opened on a
// STRANDED line — one that itself hangs between two open levels and was
// introduced by the stranded-dedent NEWLINE (e.g. `let c = ()` at col 8
// under a col-4 module body). A following line at that column is a sibling
// declaration, not a continuation, so the midline-anchor dedent guard must
// not apply.
#define INDENT_KIND_STRANDED_LINE_FLAG 0x40
#define INDENT_KIND_FLAGS_MASK 0xC0
// How an open `#if` directive entered the parse. STRUCTURED directives were
// handed to the grammar (preproc_if rules) and both branches parse as syntax.
// STRAY directives appeared at a position the grammar has no preproc rule for
// and their `#if` line was consumed as trivia; only the active (first) branch
// is parsed — a later `#else` swallows everything to the matching `#endif`.
typedef enum {
PREPROC_STRUCTURED = 0,
PREPROC_STRAY = 1,
} PreprocKind;
typedef struct {
Array(uint16_t) indents;
Array(uint8_t) indent_kinds;
Array(uint16_t) preprocessor_indents;
Array(uint8_t) preproc_kinds;
// Set when the current line was introduced by a stranded-dedent NEWLINE
// (the line hangs between two open levels); cleared when a scan's
// whitespace walk crosses onto the next line. Durable because the
// stranded NEWLINE is an emitted token, so the flag is captured in the
// serialized state that later same-line scans restore.
uint8_t line_stranded;
uint8_t multi_dollar_count;
// Set when a DEDENT pops a level but the current line still sits *above* the
// new enclosing level (a "stranded"/partial dedent). Consumed on the very
// next scan to emit the NEWLINE the enclosing block owes as an item
// separator. See the emit site in the found_end_of_line handling.
uint8_t stranded_dedent;
} 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_word_char(int32_t c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') || c == '_' || c == '\'';
}
static inline bool keyword_equals(const char *word, const char *keyword) {
size_t i = 0;
while (word[i] != '\0' && word[i] == keyword[i]) {
i++;
}
return word[i] == '\0' && keyword[i] == '\0';
}
static inline void push_indent(Scanner *scanner, uint16_t indent_length,
IndentKind kind) {
array_push(&scanner->indents, indent_length);
array_push(&scanner->indent_kinds, (uint8_t)kind);
}
static inline void pop_indent(Scanner *scanner) {
if (scanner->indents.size > 0) {
array_pop(&scanner->indents);
}
if (scanner->indent_kinds.size > 0) {
array_pop(&scanner->indent_kinds);
}
}
static inline uint16_t peek_indent_length(Scanner *scanner) {
return *array_back(&scanner->indents);
}
static inline void push_preproc_kind(Scanner *scanner, PreprocKind kind) {
array_push(&scanner->preproc_kinds, (uint8_t)kind);
}
static inline void pop_preproc_kind(Scanner *scanner) {
if (scanner->preproc_kinds.size > 0) {
array_pop(&scanner->preproc_kinds);
}
}
static inline bool top_preproc_is_stray(Scanner *scanner) {
return scanner->preproc_kinds.size > 0 &&
*array_back(&scanner->preproc_kinds) == (uint8_t)PREPROC_STRAY;
}
static inline bool top_preproc_is_structured(Scanner *scanner) {
return scanner->preproc_kinds.size > 0 &&
*array_back(&scanner->preproc_kinds) == (uint8_t)PREPROC_STRUCTURED;
}
// Consume everything from the current position (just past a stray `#else`)
// through the end of the matching `#endif` line, tracking nested directives
// textually (proper nesting is guaranteed by the F# lexer, and the inactive
// branch is never parsed, so line-start matching is sufficient). Stops before
// the trailing newline so normal newline/indent processing resumes after the
// region. At EOF (unterminated directive) the rest of the file is consumed.
static inline void swallow_inactive_region(TSLexer *lexer) {
int depth = 1;
for (;;) {
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
advance(lexer);
}
if (lexer->eof(lexer)) {
return;
}
advance(lexer); // consume the newline
while (lexer->lookahead == ' ' || lexer->lookahead == '\t' ||
lexer->lookahead == '\r') {
advance(lexer);
}
if (lexer->lookahead != '#') {
continue;
}
advance(lexer);
if (lexer->lookahead == 'i') {
advance(lexer);
if (lexer->lookahead == 'f') {
advance(lexer);
if (!is_word_char(lexer->lookahead)) {
depth++;
}
}
} else if (lexer->lookahead == 'e') {
advance(lexer);
if (lexer->lookahead == 'n') {
advance(lexer);
if (lexer->lookahead == 'd') {
advance(lexer);
if (lexer->lookahead == 'i') {
advance(lexer);
if (lexer->lookahead == 'f') {
advance(lexer);
if (!is_word_char(lexer->lookahead)) {
depth--;
if (depth == 0) {
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
advance(lexer);
}
return;
}
}
}
}
}
}
}
}
}
static inline IndentKind peek_indent_kind(Scanner *scanner) {
if (scanner->indent_kinds.size == 0) return INDENT_NORMAL;
return (IndentKind)(*array_back(&scanner->indent_kinds) &
~INDENT_KIND_FLAGS_MASK);
}
static inline bool top_indent_is_midline_anchor(Scanner *scanner) {
return scanner->indent_kinds.size > 0 &&
(*array_back(&scanner->indent_kinds) & INDENT_KIND_MIDLINE_FLAG) != 0;
}
static inline bool top_indent_is_stranded_line(Scanner *scanner) {
return scanner->indent_kinds.size > 0 &&
(*array_back(&scanner->indent_kinds) &
INDENT_KIND_STRANDED_LINE_FLAG) != 0;
}
static inline bool peek_is_paren_indent(Scanner *scanner) {
IndentKind kind = peek_indent_kind(scanner);
return kind == INDENT_PAREN || kind == INDENT_TYPE_APP;
}
static inline bool peek_is_brace_indent(Scanner *scanner) {
return peek_indent_kind(scanner) == INDENT_BRACE;
}
static inline bool peek_is_type_app_indent(Scanner *scanner) {
return peek_indent_kind(scanner) == INDENT_TYPE_APP;
}
static inline bool peek_is_try_indent(Scanner *scanner) {
return peek_indent_kind(scanner) == INDENT_TRY;
}
// Peek forward from after a '<' to its matching '>' and check that the content
// is type-arg-shaped per F# spec Section 15.3 (identifiers, whitespace, and
// ',', '*', '->', '(', ')', '[', ']', '<', '>', '^', '#', ':', '{|', '|}').
// If `out_saw_newline` is non-NULL, also reports whether a newline appeared
// before the close — used to distinguish multi-line type apps where the first
// arg sits on the same line as '<' (which `found_end_of_line` alone misses).
static inline bool is_type_application_open_ex(TSLexer *lexer,
bool *out_saw_newline) {
int angle_depth = 1;
int paren_depth = 0;
bool saw_newline = false;
// Whether the character just consumed was a '^'. Only the exact `^-<int>`
// spelling of a negative measure exponent may relax the '-' rule below, so
// this is per-character state, not "a caret appeared somewhere".
bool prev_was_caret = false;
while (!lexer->eof(lexer) && angle_depth > 0) {
int32_t c = lexer->lookahead;
bool after_caret = prev_was_caret;
prev_was_caret = false;
if (c == '\n' || c == '\r') {
saw_newline = true;
advance(lexer);
continue;
}
if (is_word_char(c) || c == ' ' || c == '\t' || c == ',' || c == '*' ||
c == '.' || c == ':' || c == '#' || c == '^' || c == '/' || c == '|' ||
c == '{' || c == '}' || c == '[' || c == ']' ||
// Backtick-quoted measure/type names may contain '%' and '`',
// e.g. 0.95m<``Risk %``>.
c == '`' || c == '%') {
prev_was_caret = (c == '^');
advance(lexer);
continue;
}
if (c == '(') { paren_depth++; advance(lexer); continue; }
if (c == ')') {
// Unbalanced ')' rules out type args (e.g. `(l<r)`).
if (paren_depth <= 0) return false;
paren_depth--; advance(lexer); continue;
}
if (c == '<') { angle_depth++; advance(lexer); continue; }
if (c == '>') {
angle_depth--;
if (angle_depth == 0) {
// A '>' inside unbalanced parens (e.g. the ':>' in
// `box<|(inst :> IFoo).M`) cannot close a type application.
if (paren_depth > 0) return false;
if (out_saw_newline) *out_saw_newline = saw_newline;
return true;
}
advance(lexer);
continue;
}
if (c == '-') {
// '->' is valid in function types, bare '-' is not.
advance(lexer);
if (lexer->lookahead == '>') { advance(lexer); continue; }
// A negative measure exponent: `float<m s^-1>` directly after the '^',
// or the numerator of a rational one, `23<kg^(-12345/123)>`, where the
// '-' sits inside the parens. Both spellings are narrow, so ordinary
// comparison chains (`a<b-1>c`, `a<b^2 - 1>c`) remain non-type-apps.
if ((after_caret || paren_depth > 0) && lexer->lookahead >= '0' &&
lexer->lookahead <= '9') {
continue;
}
return false;
}
// Anything else (`&`, `!`, `=`, `+`, `;`, `@`, `$`, `%`, `?`, …) rules out type args.
return false;
}
return false;
}
static inline bool is_type_application_open(TSLexer *lexer) {
return is_type_application_open_ex(lexer, NULL);
}
// Peek the body of a parenthesised multi-typar group that opens an SRTP trait
// call: `^a or ^b) : (` / `'T1 or 'T2) : (`, as in
// `((^a or ^b) : (static member op_Implicit: ^a -> ^b) x)`. Called with the
// lookahead on the first typar — the group's '(' has already been passed,
// either by the parser or by one of scan()'s own probes. At least two typars
// joined by `or`, then the group's ')' and the following `: (`, are required,
// so the body of a parenthesised expression can never match.
static inline bool is_srtp_typar_group_ahead(TSLexer *lexer) {
unsigned typars = 0;
for (;;) {
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
if (lexer->lookahead != '^' && lexer->lookahead != '\'') {
return false;
}
advance(lexer);
if (!is_word_char(lexer->lookahead)) {
return false;
}
while (is_word_char(lexer->lookahead)) {
advance(lexer);
}
typars++;
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
if (lexer->lookahead != 'o') {
break;
}
advance(lexer);
if (lexer->lookahead != 'r') {
return false;
}
advance(lexer);
if (is_word_char(lexer->lookahead)) {
return false; // an identifier starting with "or", not the keyword
}
}
if (typars < 2 || lexer->lookahead != ')') {
return false;
}
advance(lexer);
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
if (lexer->lookahead != ':') {
return false;
}
advance(lexer);
while (lexer->lookahead == ' ' || lexer->lookahead == '\t') {
advance(lexer);
}
return lexer->lookahead == '(';
}
static inline bool is_multiline_type_app_ahead(TSLexer *lexer) {
bool saw_newline = false;
return is_type_application_open_ex(lexer, &saw_newline) && saw_newline;
}
static inline bool scan_n_chars(TSLexer *lexer, char ch, uint8_t count) {
lexer->mark_end(lexer);
for (uint8_t i = 0; i < count; i++) {
if (lexer->lookahead != ch) {
return false;
}
advance(lexer);
}
lexer->mark_end(lexer);
return true;
}
static inline bool scan_block_comment(TSLexer *lexer) {
lexer->mark_end(lexer);
if (lexer->lookahead != '(')
return false;
advance(lexer);
if (lexer->lookahead != '*')
return false;
advance(lexer);
while (true) {
switch (lexer->lookahead) {
case '(':
scan_block_comment(lexer);
break;
case '*':
advance(lexer);
if (lexer->lookahead == ')') {
advance(lexer);
return true;
}
break;
case '\0':
return true;
default:
advance(lexer);
}
}
}
static inline bool is_infix_op_start(TSLexer *lexer) {
switch (lexer->lookahead) {
case '+':
case '-':
skip(lexer);
return !(lexer->lookahead >= '0' && lexer->lookahead <= '9');
case '*':
case '%':
case '&':
case '=':
case '?':
case '<':
case '>':
case '^':
// A line-leading ',' continues the previous line (leading-comma style in
// multiline tuples / named arguments), exactly like an infix operator.
case ',':
return true;
case '/':
skip(lexer);
return lexer->lookahead != '/';
case '.':
skip(lexer);
return lexer->lookahead != '.';
case '!':
skip(lexer);
return lexer->lookahead == '=';
case ':':
skip(lexer);
return lexer->lookahead == '=' || lexer->lookahead == ':' ||
lexer->lookahead == '?' || lexer->lookahead == ' ' ||
lexer->lookahead == '>';
case 'o':
skip(lexer);
if (lexer->lookahead != 'r') {
return false;
}
skip(lexer);
// Only the standalone `or` operator counts; identifiers that merely start
// with "or" (e.g. `orderId`) must not be treated as an infix op, otherwise
// the newline before them is suppressed and they get glued to the previous
// token (e.g. a record field type).
return !is_word_char(lexer->lookahead);
case '@':
case '$':
skip(lexer);
return lexer->lookahead != '"';
default:
return false;
}
}
static inline bool is_bracket_end(TSLexer *lexer) {
switch (lexer->lookahead) {
case ')':
case ']':
case '}':
return true;
default:
return false;
}
}
// Match remaining characters of a keyword after the first character.
// Returns true if the rest of the keyword matches and is followed by a non-word char.
static inline bool match_keyword_rest(TSLexer *lexer, const char *rest) {
for (; *rest; rest++) {
if (lexer->lookahead != *rest) return false;
advance(lexer);
}
return !is_word_char(lexer->lookahead);
}
// Table-driven block opener matching for class/begin/struct/interface.
typedef struct {
char first_char;
const char *rest;
enum TokenType token;
} BlockOpener;
static const BlockOpener block_openers[] = {
{'c', "lass", CLASS},
{'b', "egin", BEGIN},
{'s', "truct", STRUCT},
{'i', "nterface", INTERFACE},
};
// Check if a preprocessor directive requires emitting DEDENT before itself.
// Used by both #endif and #else handlers to pop indent when the preprocessor
// indent is less than the current block indent.
static inline bool try_dedent_for_preproc(Scanner *scanner, TSLexer *lexer) {
if (scanner->indents.size > 0 &&
scanner->preprocessor_indents.size > 0) {
uint16_t current_indent_length = peek_indent_length(scanner);
uint16_t current_preproc_length =
*array_back(&scanner->preprocessor_indents);
if (current_preproc_length < current_indent_length) {
pop_indent(scanner);
lexer->result_symbol = DEDENT;
return true;
}
}
return false;
}
static bool scan(Scanner *scanner, TSLexer *lexer, const bool *valid_symbols) {
// A stranded-dedent flag lives for exactly one scan: capture it and clear
// the persistent copy up front so it is consumed by the immediately
// following scan (the NEWLINE emit below) and never leaks further.
bool prev_stranded_dedent = scanner->stranded_dedent;
scanner->stranded_dedent = false;
if (valid_symbols[ERROR_SENTINEL]) {
// During error recovery, all valid_symbols are true. Tree-sitter's error
// recovery mechanism cannot emit external scanner tokens, so we must still
// produce tokens like DEDENT and PREPROC_END when we can identify them.
// This enables partial parse tree recovery -- e.g., "match x with" needs
// DEDENT to be recognized as a partially correct match-statement for
// syntax highlighting purposes.
// At EOF, emit DEDENT to drain the indent stack. This is critical for
// closing partial parse trees at end of input.
if (lexer->eof(lexer) && scanner->indents.size > 1) {
pop_indent(scanner);
lexer->result_symbol = DEDENT;
return true;
}
// For non-EOF cases, fall through to normal scanning logic below.
// The normal path handles whitespace consumption and emits DEDENT/NEWLINE
// based on actual indentation levels. Features that should not run during
// error recovery (multi-dollar strings, quotation closers, etc.) are
// already guarded by !valid_symbols[ERROR_SENTINEL] checks.
}
if (valid_symbols[INSIDE_STRING] && !valid_symbols[ERROR_SENTINEL]) {
return false;
}
// `preproc_inactive` is an extra, so it is valid in nearly every state —
// including states that had no valid external tokens before it existed and
// therefore never invoked this scanner. The full scan logic below assumes
// some structural token is wanted (several paths emit DEDENT/NEWLINE
// unconditionally), so in those states handle only the stray-directive
// fallback and otherwise stay out of the internal lexer's way.
if (!valid_symbols[ERROR_SENTINEL]) {
bool any_structural_valid = false;
for (int i = 0; i < PREPROC_INACTIVE; i++) {
if (valid_symbols[i]) {
any_structural_valid = true;
break;
}
}
// BRACE_INDENT sits after the PREPROC_INACTIVE/ELEM_SEP "extra" tokens in
// the enum but is a structural indent token like INDENT, so it must count
// here — otherwise a state where only BRACE_INDENT is valid (right after a
// record/CE '{') bails out and the token is never emitted.
if (valid_symbols[BRACE_INDENT]) {
any_structural_valid = true;
}
if (!any_structural_valid) {
while (lexer->lookahead == ' ' || lexer->lookahead == '\t' ||
lexer->lookahead == '\n' || lexer->lookahead == '\r' ||
lexer->lookahead == '\f') {
skip(lexer);
}
if (lexer->lookahead != '#') {
return false;
}
advance(lexer);
if (lexer->lookahead == 'i') { // #if — grammar cannot place it here
advance(lexer);
if (lexer->lookahead != 'f') return false;
advance(lexer);
if (is_word_char(lexer->lookahead)) return false;
push_preproc_kind(scanner, PREPROC_STRAY);
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
advance(lexer);
}
lexer->mark_end(lexer);
lexer->result_symbol = PREPROC_INACTIVE;
return true;
}
if (lexer->lookahead != 'e') {
return false;
}
advance(lexer);
if (lexer->lookahead == 'l') { // #else of a stray directive
advance(lexer);
if (lexer->lookahead != 's') return false;
advance(lexer);
if (lexer->lookahead != 'e') return false;
advance(lexer);
if (is_word_char(lexer->lookahead) || !top_preproc_is_stray(scanner)) {
return false;
}
pop_preproc_kind(scanner);
swallow_inactive_region(lexer);
lexer->mark_end(lexer);
lexer->result_symbol = PREPROC_INACTIVE;
return true;
}
if (lexer->lookahead == 'n') { // #endif of a stray directive
advance(lexer);
if (lexer->lookahead != 'd') return false;
advance(lexer);
if (lexer->lookahead != 'i') return false;
advance(lexer);
if (lexer->lookahead != 'f') return false;
advance(lexer);
if (is_word_char(lexer->lookahead) || !top_preproc_is_stray(scanner)) {
return false;
}
pop_preproc_kind(scanner);
lexer->mark_end(lexer);
lexer->result_symbol = PREPROC_INACTIVE;
return true;
}
return false;
}
}
// Type application '<' disambiguation (F# spec Section 15.3).
// When the grammar expects TYAPP_OPEN (i.e., a '<' immediately after an expression),
// peek ahead to determine if the content between '<' and '>' looks like type arguments.
// If not (e.g., it's a comparison operator like l<r), return false so the grammar
// falls through to infix_op.
if (valid_symbols[TYAPP_OPEN] && !valid_symbols[ERROR_SENTINEL] &&
lexer->lookahead == '<') {
lexer->mark_end(lexer);
advance(lexer);
// Mark end right after '<' - this is what we want the token to contain
lexer->mark_end(lexer);
// Now peek ahead (advancing further) to check if content looks like type args.
// Even though we advance past the type content, mark_end is already set to
// just after '<', so the emitted token will be exactly '<'.
if (is_type_application_open(lexer)) {
lexer->result_symbol = TYAPP_OPEN;
return true;
}
// Not a type application - don't consume the '<', let grammar handle it as infix_op.
// But we already advanced past '<' and potentially more. That's OK because
// we return false and tree-sitter will reset the lexer position.
return false;
}
if (!valid_symbols[ERROR_SENTINEL] && scanner->multi_dollar_count > 1) {
if (valid_symbols[MULTI_DOLLAR_INTERP_START] && lexer->lookahead == '{') {
if (scan_n_chars(lexer, '{', scanner->multi_dollar_count)) {
lexer->result_symbol = MULTI_DOLLAR_INTERP_START;
return true;
}
}
if (valid_symbols[MULTI_DOLLAR_INTERP_END] && lexer->lookahead == '}') {
if (scan_n_chars(lexer, '}', scanner->multi_dollar_count)) {
lexer->result_symbol = MULTI_DOLLAR_INTERP_END;
return true;
}
}
if (valid_symbols[MULTI_DOLLAR_TRIPLE_QUOTE_END] && lexer->lookahead == '"') {
if (scan_n_chars(lexer, '"', 3)) {
scanner->multi_dollar_count = 0;
lexer->result_symbol = MULTI_DOLLAR_TRIPLE_QUOTE_END;
return true;
}
}
}
if (!valid_symbols[ERROR_SENTINEL] &&
(valid_symbols[TRIPLE_QUOTE_CONTENT] || valid_symbols[FORMAT_TRIPLE_QUOTE_CONTENT] ||
valid_symbols[MULTI_DOLLAR_TRIPLE_QUOTED_CONTENT])) {
bool is_format = valid_symbols[FORMAT_TRIPLE_QUOTE_CONTENT];
bool is_multi_dollar = valid_symbols[MULTI_DOLLAR_TRIPLE_QUOTED_CONTENT];
bool has_content = false;
lexer->mark_end(lexer);
while (true) {
if (lexer->lookahead == '\0') {
break;
}
if ((is_format || is_multi_dollar) && lexer->lookahead == '{') {
// In format triple-quoted strings, stop at '{' to allow interpolation.
// Multi-dollar interpolated strings require N braces, where N is the
// number of leading '$' characters.
uint8_t brace_count = is_multi_dollar ? scanner->multi_dollar_count : 1;
lexer->mark_end(lexer);
if (!is_multi_dollar) {
advance(lexer);
if (lexer->lookahead == '{') {
advance(lexer);
lexer->mark_end(lexer);
has_content = true;
continue;
}
if (!has_content) {
return false;
}
break;
}
bool matches_interp_start = true;
for (uint8_t i = 0; i < brace_count; i++) {
if (lexer->lookahead != '{') {
matches_interp_start = false;
break;
}
advance(lexer);
}
if (matches_interp_start) {
if (!has_content) {
return false;
}
break;
}
has_content = true;
lexer->mark_end(lexer);
continue;
}
if (lexer->lookahead != '"') {
advance(lexer);
has_content = true;
} else {
if (is_multi_dollar) {
advance(lexer);
if (lexer->lookahead == '"') {
advance(lexer);
if (lexer->lookahead == '"') {
break;
}
}
has_content = true;
lexer->mark_end(lexer);
} else {
lexer->mark_end(lexer);
skip(lexer);
if (lexer->lookahead == '"') {
skip(lexer);
if (lexer->lookahead == '"') {
skip(lexer);
break;
}
}
}
has_content = true;
lexer->mark_end(lexer);
}
}
if (is_multi_dollar) {
lexer->result_symbol = MULTI_DOLLAR_TRIPLE_QUOTED_CONTENT;
} else {
lexer->result_symbol = is_format ? FORMAT_TRIPLE_QUOTE_CONTENT : TRIPLE_QUOTE_CONTENT;
}
return true;
}
if (valid_symbols[TYPE_DECL_NEWLINE] && !valid_symbols[ERROR_SENTINEL]) {
// Only fire at EOF or newline; if the current character is something else
// (e.g. '=' during GLR exploration), fall through to general scanning —
// the lexer position is unchanged so this is safe.
if (lexer->eof(lexer)) {
lexer->result_symbol = TYPE_DECL_NEWLINE;
return true;
}
if (lexer->lookahead == '\n' || lexer->lookahead == '\r') {
// Emit a zero-width token: fix the token end at the newline so the newline
// itself is NOT consumed. This matters inside module bodies, where the
// newline is the separator between elements; if TYPE_DECL_NEWLINE ate it,
// the module would close after a single bare type declaration.
lexer->mark_end(lexer);
// Peek ahead: skip newlines/whitespace to find indentation of next content.
// If next content is NOT more indented than current scope, this is a bare
// type declaration (e.g. [<Measure>] type Dollars).
// If next content IS more indented, the type has a body (e.g. type CsvFile
// private (...) = ...) and TYPE_DECL_NEWLINE should not fire.
uint32_t next_indent = 0;
for (;;) {
if (lexer->lookahead == '\n' || lexer->lookahead == '\r') {
next_indent = 0;
skip(lexer);
} else if (lexer->lookahead == ' ') {
next_indent++;
skip(lexer);
} else if (lexer->lookahead == '\t') {
next_indent += 8;
skip(lexer);
} else {
break;
}
}
if (lexer->eof(lexer)) {
lexer->result_symbol = TYPE_DECL_NEWLINE;
return true;
}
uint32_t scope_indent = (scanner->indents.size > 0)
? (uint32_t)*array_back(&scanner->indents)
: 0;
if (next_indent <= scope_indent) {
// Next line is at same or lower indentation — bare type declaration
lexer->result_symbol = TYPE_DECL_NEWLINE;
return true;
}
// else: next line is more indented — type has a body, don't fire
return false;
}
}
// Block-comment content must be handled before the whitespace/offside walk
// below. It is only ever valid immediately after a '(*' opener, so nothing
// else needs scanning here; running the ws-walk instead lets a '#' that is
// the first non-space char of the comment (e.g. a Markdown '(* # Heading')
// be mis-read as a preprocessor directive, breaking the comment.
if (valid_symbols[BLOCK_COMMENT_CONTENT] && !valid_symbols[ERROR_SENTINEL]) {
// Scan position is directly after a shifted '(*'. If the very next char
// is ')', the source text was `(*)` — F# defines that as the
// multiplication operator reference, never a comment (matching FSC's
// lexer). Decline so the GLR version that lexed '(*' as a comment opener
// dies immediately instead of swallowing an arbitrary span hunting for
// '*)' (`Constant(Checked.(*) l r, t)` arms repeated in one match were
// compounding such zombie versions past the GLR version cap, killing the
// correct parse — ExpressionOptimizer.fs whole-file wrap).
if (lexer->lookahead == ')') {
return false;
}
lexer->mark_end(lexer);
while (true) {
if (lexer->lookahead == '\0') {
break;
}
if (lexer->lookahead != '(' && lexer->lookahead != '*') {
advance(lexer);
} else if (lexer->lookahead == '*') {
lexer->mark_end(lexer);
advance(lexer);
if (lexer->lookahead == ')') {
break;
}
} else if (scan_block_comment(lexer)) {
lexer->mark_end(lexer);
advance(lexer);
if (lexer->lookahead == '*') {
break;
}
}
}
lexer->result_symbol = BLOCK_COMMENT_CONTENT;
return true;
}
lexer->mark_end(lexer);
bool found_end_of_line = false;
bool found_end_of_line_semi_colon = false;
bool found_start_of_infix_op = false;
bool found_same_line_pipe_infix = false;
bool found_bracket_end = false;
bool found_preprocessor_end = false;
bool found_preproc_if = false;
bool found_preproc_else = false;
bool found_comment_start = false;
bool advanced_in_ws_walk = false;
bool skipped_open_paren = false;
uint32_t indent_length = lexer->get_column(lexer);
for (;;) {
if (lexer->lookahead == '\n') {
found_end_of_line = true;
indent_length = 0;
skip(lexer);
} else if (lexer->lookahead == ' ') {
indent_length++;
skip(lexer);
} else if (lexer->lookahead == '\r' || lexer->lookahead == '\f') {
indent_length = 0;
skip(lexer);
} else if (lexer->lookahead == '\t') {
indent_length += 8;
skip(lexer);
} else if (lexer->eof(lexer)) {
found_end_of_line = true;
indent_length = 0;
break;
} else if (lexer->lookahead == '/') {
skip(lexer);
if (!valid_symbols[INSIDE_STRING] && lexer->lookahead == '/') {
// Once the loop has scanned past a directive (`#endif`/`#else` that
// couldn't be emitted yet, or a `#if` line), declining on a trailing
// line comment would leave the directive — not the comment — as the
// next text for the internal lexer, which cannot lex it (ERROR).
// Skip the comment like whitespace instead, exactly as if the line
// were blank, so the pending NEWLINE/DEDENT decision proceeds.
if (!found_preproc_if && !found_preprocessor_end &&
!found_preproc_else) {
return false;
}
while (lexer->lookahead != '\n' && !lexer->eof(lexer)) {
skip(lexer);
}
} else {
return false;
}
} else if (lexer->lookahead == '#') {
advanced_in_ws_walk = true;
advance(lexer);
if (lexer->lookahead == 'e') {
advance(lexer);
if (lexer->lookahead == 'n') {
advance(lexer);
if (lexer->lookahead == 'd') {
advance(lexer);
if (lexer->lookahead == 'i') {
advance(lexer);
if (lexer->lookahead == 'f') {
advance(lexer);
// The innermost open directive was consumed as trivia (no
// grammar rule at its position), so this `#endif` closes it
// textually: consume it as an inactive-trivia extra instead
// of handing it to the grammar.
if (top_preproc_is_stray(scanner) &&
!valid_symbols[ERROR_SENTINEL] &&
!is_word_char(lexer->lookahead)) {
pop_preproc_kind(scanner);
lexer->mark_end(lexer);
lexer->result_symbol = PREPROC_INACTIVE;
return true;
}
found_preprocessor_end = true;
if (try_dedent_for_preproc(scanner, lexer)) {
return true;
}
if (valid_symbols[PREPROC_END]) {
if (scanner->preprocessor_indents.size > 0) {
array_pop(&scanner->preprocessor_indents);
}
pop_preproc_kind(scanner);
lexer->mark_end(lexer);
lexer->result_symbol = PREPROC_END;
return true;
}
}
}
}
} else if (lexer->lookahead == 'l') {
advance(lexer);
if (lexer->lookahead == 's') {
advance(lexer);
if (lexer->lookahead == 'e') {
advance(lexer);
// The innermost open directive was consumed as trivia, so its
// `#else` branch is inactive: swallow everything through the
// matching `#endif` as a single extra token. Only the active
// (first) branch reaches the grammar, so a directive the
// grammar has no rule for can never split a construct in two.
if (top_preproc_is_stray(scanner) &&