-
Notifications
You must be signed in to change notification settings - Fork 35
/
scanner.c
1620 lines (1488 loc) · 43.3 KB
/
scanner.c
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
/**
* Print input and result information.
*/
// #define DEBUG 1
/**
* Print the upcoming token after parsing finished.
* Note: May change parser behaviour.
*/
// #define DEBUG_NEXT_TOKEN 1
#include "tree_sitter/parser.h"
#include <assert.h>
#ifdef DEBUG
#include <stdio.h>
#endif
#include <string.h>
#include <stdbool.h>
#include <wctype.h>
// short circuit
#define SHORT_SCANNER if (res.finished) return res;
#define PEEK state->lexer->lookahead
// Move the parser position one character to the right.
#define S_ADVANCE state->lexer->advance(state->lexer, false)
// Move the parser position one character to the right, treating the consumed character as whitespace.
#define S_SKIP state->lexer->advance(state->lexer, true)
#define SYM(s) (state->symbols[s])
#ifdef DEBUG
#define DEBUG_PRINTF(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINTF(...) do{ } while ( false )
#endif
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define VEC_RESIZE(vec, _cap) \
(vec)->data = realloc((vec)->data, (_cap) * sizeof((vec)->data[0])); \
assert((vec)->data != NULL); \
(vec)->cap = (_cap);
#define VEC_GROW(vec, _cap) if ((vec)->cap < (_cap)) { VEC_RESIZE((vec), (_cap)); }
#define VEC_PUSH(vec, el) \
if ((vec)->cap == (vec)->len) { VEC_RESIZE((vec), MAX(20, (vec)->len * 2)); } \
(vec)->data[(vec)->len++] = (el);
#define VEC_POP(vec) (vec)->len--;
#define VEC_NEW { .len = 0, .cap = 0, .data = NULL }
#define VEC_BACK(vec) ((vec)->data[(vec)->len - 1])
#define VEC_FREE(vec) { if ((vec)->data != NULL) free((vec)->data); }
// --------------------------------------------------------------------------------------------------------
// Symbols
// --------------------------------------------------------------------------------------------------------
/**
* This enum is mapped to the `externals` list in the grammar according to how they are ordered (the names are
* abitrary).
*
* When the `scan` function is called, the parameter `syms` contains a bool for each enum attribute indicating whether
* the parse tree at the current position can accept the corresponding symbol.
*
* The attribute `fail` is not part of the parse tree, it is used to indicate that no matching symbol was found.
*
* The meanings are:
* - semicolon: An implicit end of a decl or statement, a newline in place of a semicolon
* - start: Start an implicit new layout after `where`, `do`, `of` or `in`, in place of an opening brace
* - end: End an implicit layout, in place of a closing brace
* - dot: For qualified modules `Data.List.null`, which have to be disambiguated from the `(.)` operator based on
* surrounding whitespace.
* - where: Parse an inline `where` token. This is necessary because `where` tokens can end layouts and it's necesary
* to know whether it is valid at that position, which can mean that it belongs to the last statement of the layout
* - splice: A TH splice starting with a `$`, to disambiguate from the operator
* - varsym: A symbolic operator
* - consym: A symbolic constructor
* - tyconsym: A symbolic type operator
* - comment: A line or block comment, because they interfere with operators, especially in QQs
* - cpp: A preprocessor directive. Needs to push and pop indent stacks
* - comma: Needed to terminate inline layouts like `of`, `do`
* - qq_start: Disambiguate the opening oxford bracket from list comprehension
* - qq_bar: Disambiguate the vertical bar `|` after the quasiquoter from symbolic operators, which may be a problem
* when the quasiquote body starts with an operator character.
* - qq_body: Prevent extras, like comments, from breaking quasiquotes
* - strict: Disambiguate strictness annotation `!` from symbolic operators
* - unboxed_tuple_close: Disambiguate the closing parens for unboxed tuples `#)` from symbolic operators
* - bar: The vertical bar `|`, used for guards and list comprehension
* - in: Closes the layout of a `let` and consumes the token `in`
* - indent: Used as a dummy symbol for initialization; uses newline in the grammar to ensure the scanner is called
* for each token
* - empty: The empty file
* - fail: special indicator of failure
*/
typedef enum {
SEMICOLON,
START,
END,
DOT,
WHERE,
SPLICE,
VARSYM,
CONSYM,
TYCONSYM,
COMMENT,
CPP,
COMMA,
QQ_START,
QQ_BAR,
QQ_BODY,
STRICT,
UNBOXED_TUPLE_CLOSE,
BAR,
IN,
INDENT,
EMPTY,
FAIL,
} Sym;
#ifdef DEBUG
static char *sym_names[] = {
"semicolon",
"start",
"end",
"dot",
"where",
"splice",
"varsym",
"consym",
"tyconsym",
"comment",
"cpp",
"comma",
"qq_start",
"qq_bar",
"qq_body",
"strict",
"unboxed_tuple_close",
"bar",
"in",
"indent",
"empty",
};
#endif
/**
* The parser appears to call `scan` with all symbols declared as valid directly after it encountered an error, so
* this function is used to detect them.
*/
static bool all_syms(const bool *syms) {
for (int i = 0; i <= EMPTY; i++) {
if (!syms[i]) return false;
}
return true;
}
#ifdef DEBUG
/**
* Produce a comma-separated string of valid symbols.
*/
static void debug_valid(const bool *syms) {
if (all_syms(syms)) {
DEBUG_PRINTF("all");
return;
}
bool fst = true;
DEBUG_PRINTF("\"");
for (Sym i = SEMICOLON; i <= EMPTY; i++) {
if (syms[i]) {
if (!fst) DEBUG_PRINTF(",");
DEBUG_PRINTF("%s", sym_names[i]);
fst = false;
}
}
DEBUG_PRINTF("\"");
}
#endif
typedef struct {
uint32_t len;
uint32_t cap;
uint16_t *data;
} indent_vec;
// --------------------------------------------------------------------------------------------------------
// State
// --------------------------------------------------------------------------------------------------------
/**
* This structure contains the external and internal state.
*
* The parser provides the lexer interface and the list of valid symbols.
*
* The internal state consists of a stack of indentation widths that is manipulated whenever a layout is started or
* terminated.
*/
typedef struct {
TSLexer *lexer;
const bool *symbols;
indent_vec *indents;
#ifdef DEBUG
int marked;
char *marked_by;
bool needs_free;
#endif
} State;
State state_new(TSLexer *l, const bool * restrict vs, indent_vec *is) {
return (State) {
.lexer = l,
.symbols = vs,
.indents = is,
#ifdef DEBUG
.marked = -1,
.marked_by = "",
.needs_free = false,
#endif
};
}
#ifdef DEBUG
static void debug_indents(indent_vec *indents) {
if (indents->len == 0) DEBUG_PRINTF("empty");
bool empty = true;
for (size_t i = 0; i < indents->len; i++) {
if (!empty) DEBUG_PRINTF("-");
DEBUG_PRINTF("%d", indents->data[i]);
empty = false;
}
}
void debug_state(State *state) {
DEBUG_PRINTF("State { syms = ");
debug_valid(state->symbols);
DEBUG_PRINTF(", indents = ");
debug_indents(state->indents);
}
#endif
/**
* These functions provide the basic interface to the lexer.
* They are not defined as members for easier composition.
*/
static bool is_eof(State *state) { return state->lexer->eof(state->lexer); }
/**
* The parser's position in the current line.
*/
static uint32_t column(State *state) {
return is_eof(state) ? 0 : state->lexer->get_column(state->lexer);
}
/**
* Instruct the lexer that the current position is the end of the potentially detected symbol, causing the next run to
* be started after this character in the success case.
*
* This is useful if the validity of the detected symbol depends on what follows, e.g. in the case of a layout end
* before a `where` token.
*/
// Only use string literals we actually need
#ifdef DEBUG
static void MARK(char *marked_by, bool needs_free, State *state) {
state->marked = column(state);
if (state->needs_free) free(state->marked_by);
state->marked_by = marked_by;
state->needs_free = needs_free;
state->lexer->mark_end(state->lexer);
}
#else
#define MARK(s, nf, state) state->lexer->mark_end(state->lexer);
#endif
// --------------------------------------------------------------------------------------------------------
// Condition
// --------------------------------------------------------------------------------------------------------
/**
* The set of conditions used in the parser implementation.
*/
static bool varid_start_char(const uint32_t c) { return c == '_' || iswlower(c); }
static bool varid_char(const uint32_t c) {
switch (c) {
case '_':
case '\'':
return true;
default:
// TODO(414owen) is haskell C_LOCALE sensitive?
return iswalnum(c);
}
}
static bool quoter_char(const uint32_t c) { return varid_char(c) || c == '.'; };
static bool seq(const char * restrict s, State *state) {
size_t len = strlen(s);
for (size_t i = 0; i < len; i++) {
int32_t c = s[i];
int32_t c2 = PEEK;
if (c != c2) return false;
S_ADVANCE;
}
return true;
}
static void consume_until(char *target, State *state) {
int32_t first = target[0];
assert(first != 0);
while (PEEK != 0 && !seq(target, state)) {
while (PEEK != 0 && PEEK != first) S_ADVANCE;
// TODO(414owen): This mimics the combinator's behaviour, but it seems a bit silly.
// Why mark where the first char matched? Let's just not do this check.
if (first == PEEK) {
#ifdef DEBUG
char *prefix = "consume_until ";
char *mark_target = calloc(strlen(prefix) + strlen(target) + 1, 1);
sprintf(mark_target, "%s%s", prefix, target);
MARK(mark_target, true, state);
#else
state->lexer->mark_end(state->lexer);
#endif
}
}
}
typedef struct {
uint32_t len;
uint32_t cap;
int32_t *data;
} wchar_vec;
static wchar_vec read_string(bool (*cond)(uint32_t), State *state) {
wchar_vec res = VEC_NEW;
int32_t c = PEEK;
while (cond(c)) {
VEC_PUSH(&res, c);
S_ADVANCE;
c = PEEK;
}
return res;
}
#define WS_CASES \
case ' ': \
case '\f': \
case '\n': \
case '\r': \
case '\t': \
case '\v'
/**
* Require that the next character is whitespace (space or newline) without advancing the parser.
*/
static bool isws(uint32_t c) {
switch (c) {
WS_CASES: return true;
default: return false;
}
}
/**
* A token like a varsym can be terminated by whitespace of brackets.
*/
static bool token_end(uint32_t c) {
switch (c) {
WS_CASES:
case 0:
case '(':
case ')':
case '[':
case ']':
return true;
default:
return false;
}
}
/**
* Require that the argument string follows the current position and is followed by whitespace.
* See `seq`
*/
static bool token(const char *restrict s, State *state) {
return seq(s, state) && token_end(PEEK);
}
/**
* Require that the stack of layout indentations is not empty.
* This is mostly used for safety.
*/
static bool indent_exists(State *state) { return state->indents->len != 0; };
/**
* Require that the current line's indent is greater or equal than the containing layout's, so the current layout is
* continued.
*/
static bool keep_layout(uint16_t indent, State *state) {
return indent_exists(state) && indent >= VEC_BACK(state->indents);
}
/**
* Require that the current line's indent is equal to the containing layout's, so the line may start a new `decl`.
*/
static bool same_indent(uint32_t indent, State *state) { return indent_exists(state) && indent == VEC_BACK(state->indents); }
/**
* Require that the current line's indent is smaller than the containing layout's, so the layout may be ended.
*/
static bool smaller_indent(uint32_t indent, State *state) {
return indent_exists(state) && indent < VEC_BACK(state->indents);
}
static bool indent_lesseq(uint32_t indent, State *state) { return indent_exists(state) && indent <= VEC_BACK(state->indents); }
/**
* Composite condition examining whether the current layout can be terminated if the line after the position where the
* scan started begins with a `where`.
*
* This is needed because `where` can appear on the same indent as, for example, a `do` statement in a `decl`, while
* being part of the latter and therefore having to end the `do`'s layout before parsing the `where`.
*
* This does only check whether the line begins with a `w`, the entire `where` is consumed by the calling parser below.
*/
static bool is_newline_where(uint32_t indent, State *state) {
return keep_layout(indent, state)
&& (SYM(SEMICOLON) || SYM(END))
&& !SYM(WHERE)
&& PEEK == 'w';
}
#define NEWLINE_CASES \
case '\n': \
case '\r': \
case '\f'
static bool is_newline(uint32_t c) {
switch (c) {
NEWLINE_CASES:
return true;
default:
return false;
}
}
/**
* Require that the state has not been initialized after parsing has started.
*
* This is necessary to handle a nonexistent `module` declaration.
*/
static bool uninitialized(State *state) { return !indent_exists(state); }
/**
* Require that the parser determined an error in the previous step (see `all_syms`).
*/
static bool after_error(State *state) { return all_syms(state->symbols); }
#define SYMBOLICS_WITHOUT_BAR \
case '!': \
case '#': \
case '$': \
case '%': \
case '&': \
case '*': \
case '+': \
case '.': \
case '/': \
case '<': \
case '>': \
case '?': \
case '^': \
case ':': \
case '=': \
case '-': \
case '~': \
case '@': \
case '\\'
#define SYMBOLIC_CASES \
SYMBOLICS_WITHOUT_BAR: \
case '|'
static bool symbolic(uint32_t c) {
switch (c) {
SYMBOLIC_CASES:
return true;
default:
return false;
}
}
/**
* Test for reserved operators of two characters.
*/
static bool valid_symop_two_chars(uint32_t first_char, uint32_t second_char) {
switch (first_char) {
case '-':
return second_char != '-' && second_char != '>';
case '=':
return second_char != '>';
case '<':
return second_char != '-';
case '.':
return second_char != '.';
case ':':
return second_char != ':';
default:
return true;
}
}
static bool valid_splice(State *state) {
return varid_start_char(PEEK) || PEEK == '(';
}
typedef enum {
S_CON,
S_OP,
S_SPLICE,
S_STRICT,
S_STAR,
S_TILDE,
S_IMPLICIT,
S_MODIFIER,
S_MINUS,
S_UNBOXED_TUPLE_CLOSE,
S_BAR,
S_COMMENT,
S_INVALID,
} Symbolic;
static Symbolic con_or_var(uint32_t c) { return c == ':' ? S_CON : S_OP; }
/**
* Symbolic operators that are eligible to close a layout when they are on a newline with less/eq indent.
*
* Very crude heuristic. Layouts bad.
*/
static bool expression_op(Symbolic type) {
switch (type) {
case S_OP:
case S_CON:
case S_STAR:
return true;
default:
return false;
}
}
/**
* Check all conditions for symbolic expression operators and return a variant of the enum `Symbolic`.
*
* - The `single` predicate is used for single-character symops
* - does not match a reserved operator
* - is not a comment
*
* Even if one of those conditions is unmet, it might still be parsed as a varsym, e.g. if a strictness annotation is
* not valid at the current position.
*
* This only explicitly excludes `(!)` from being strictness; It could test for `varid` plus opening
* parens/bracket, but strictness is only valid in patterns and that makes it ambiguous anyway.
* Needs something better, but seems unlikely to be deterministic.
*
* Hashes followed by a varid start character `#foo` are labels.
*/
static Symbolic s_symop(wchar_vec s, State *state) {
if (s.data == NULL || s.data[0] == 0) return S_INVALID;
int32_t c = s.data[0];
if (s.len == 1) {
if (c == '!' && !(isws(PEEK) || PEEK == ')')) return S_STRICT;
if (c == '#' && PEEK == ')') return S_UNBOXED_TUPLE_CLOSE;
if (c == '#' && varid_start_char(PEEK)) return S_INVALID;
if (c == '$' && valid_splice(state)) return S_SPLICE;
if (c == '?' && varid_start_char(PEEK)) return S_IMPLICIT;
if (c == '%' && !(isws(PEEK) || PEEK == ')')) return S_MODIFIER;
if (c == '|') return S_BAR;
switch (c) {
case '*':
return S_STAR;
case '~':
return S_TILDE;
case '-':
return S_MINUS;
case '=':
case '@':
case '\\':
return S_INVALID;
default: return con_or_var(c);
}
} else {
bool is_comment = true;
for (size_t i = 0; i < s.len; i++) { is_comment &= s.data[i] == '-'; }
if (is_comment) return S_COMMENT;
if (s.len == 2) {
if (s.data[0] == '$' && s.data[1] == '$' && valid_splice(state)) return S_SPLICE;
if (!valid_symop_two_chars(s.data[0], s.data[1])) return S_INVALID;
}
}
return con_or_var(c);
}
// --------------------------------------------------------------------------------------------------------
// Result
// --------------------------------------------------------------------------------------------------------
/**
* Returned by a parser, indicating whether to continue with the next parser (`finished`) which symbol to select when
* successful (`sym`).
*
* Whether parsing was successful is indicated by which symbol is selected – `FAIL` signals failure.
*/
typedef struct {
Sym sym;
bool finished;
} Result;
#ifdef DEBUG
void debug_result(Result res) {
DEBUG_PRINTF("Result { finished = %d", res.finished);
if (res.finished)
DEBUG_PRINTF(", result = %s }\n", sym_names[res.sym]);
}
#endif
/**
* Constructors for the continue, failure and success results.
*/
static Result res_cont = {.sym = FAIL, .finished = false};
static Result res_finish(Sym t) { return (Result) {.sym = t, .finished = true}; }
static Result res_fail = {.sym = FAIL, .finished = true};
// --------------------------------------------------------------------------------------------------------
// Parser
// --------------------------------------------------------------------------------------------------------
/**
* Parser that terminates the execution with the successful detection of the given symbol.
*/
static Result finish(const Sym s, char *restrict desc) {
DEBUG_PRINTF("finish: %s\n", desc);
return res_finish(s);
}
/**
* Parser that terminates the execution with the successful detection of the given symbol, but only if it is expected.
*/
static Result finish_if_valid(const Sym s, char *restrict desc, State *state) {
return SYM(s) ? finish(s, desc) : res_cont;
}
/**
* Add one level of indentation to the stack, caused by starting a layout.
*/
static void push(uint16_t ind, State *state) {
DEBUG_PRINTF("push: %d\n", ind);
VEC_PUSH(state->indents, ind);
}
/**
* Remove one level of indentation from the stack, caused by the end of a layout.
*/
static void pop(State *state) {
if (indent_exists(state)) {
DEBUG_PRINTF("pop");
VEC_POP(state->indents);
}
}
/**
* Advance the lexer until the following character is neither space nor tab.
*/
static void skipspace(State *state) {
for (;;) {
switch (PEEK) {
case ' ':
case '\t':
S_SKIP;
break;
default:
return;
}
}
}
/**
* If a layout end is valid at this position, remove one indentation layer and succeed with layout end.
*/
static Result layout_end(char *desc, State *state) {
if (SYM(END)) {
pop(state);
return finish(END, desc);
}
return res_cont;
}
/**
* Convenience parser, since those two are often used together.
*/
static Result end_or_semicolon(char *desc, State *state) {
Result res = layout_end(desc, state);
SHORT_SCANNER;
return finish_if_valid(SEMICOLON, desc, state);
}
// --------------------------------------------------------------------------------------------------------
// Logic
// --------------------------------------------------------------------------------------------------------
/**
* These parsers constitute the higher-level logic, loosely.
*/
/**
* Advance the parser until a non-whitespace character is encountered, while counting whitespace according to the rules
* in the syntax reference, resetting the counter on each newline.
*
* This advances to the first nonwhite character in the next nonempty line and determines its indentation.
*/
static uint32_t count_indent(State *state) {
uint32_t indent = 0;
for (;;) {
switch (PEEK) {
NEWLINE_CASES:
S_SKIP;
indent = 0;
break;
case ' ':
S_SKIP;
indent++;
break;
case '\t':
S_SKIP;
indent += 8;
break;
default:
return indent;
}
}
}
/**
* End-of-file check.
*
* If EOF has been reached, two scenarios are valid:
* - The file is empty, in which case the parser is still at the root rule, where `S_EMPTY` is valid.
* - The current layout can be ended. This may happen multiple times, since the parser will restart until the last
* layout end rule has been parsed.
* If those cases do not apply, parsing fails.
*/
static Result eof(State *state) {
if (is_eof(state)) {
if (SYM(EMPTY)) {
return finish(EMPTY, "eof");
}
Result res = end_or_semicolon("eof", state);
SHORT_SCANNER;
return res_fail;
}
return res_cont;
}
/**
* Set the initial indentation at the beginning of the file or module decl to the column of first nonwhite character,
* then succeed with the dummy symbol `INDENT`.
*
* If there is a `module` declaration, this will be handled by the grammar.
*/
static Result initialize(uint32_t column, State *state) {
if (uninitialized(state)) {
MARK("initialize", false, state);
bool match = token("module", state);
if (match) return res_fail;
push(column, state);
return finish(INDENT, "init");
}
return res_cont;
}
static Result initialize_init(State *state) {
if (uninitialized(state)) {
uint32_t col = column(state);
if (col == 0) return initialize(col, state);
};
return res_cont;
}
/**
* If a dot is neither preceded nor succeded by whitespace, it may be parsed as a qualified module dot.
*
* The preceding space is ensured by sequencing this parser before `skipspace` in `init`.
* Since this parser cannot look back to see whether the preceding name is a conid, this has to be ensured by the
* grammar, represented here by the requirement of a valid symbol `DOT`.
*
* Since the dot is consumed here, the alternative interpretation, a `VARSYM`, has to be emitted here.
* A `TYCONSYM` is invalid here, because the dot is only expected in expressions.
*/
static Result dot(State *state) {
if (SYM(DOT)) {
if (PEEK == '.') {
S_ADVANCE;
if (SYM(VARSYM) && iswspace(PEEK)) return finish(VARSYM, "dot");
MARK("dot", false, state);
return finish(DOT, "dot");
}
}
return res_cont;
}
/**
* Consume the body of a cpp directive.
*
* Since they can contain escaped newlines, they have to be consumed, after which the parser recurses.
*/
static void cpp_consume(State *state) {
for (;;) {
while (PEEK != 0 && !is_newline(PEEK) && PEEK != '\\') S_ADVANCE;
if (PEEK == '\\') {
S_ADVANCE;
S_ADVANCE;
continue;
}
return;
}
}
/**
* Parse a cpp directive.
*
* This is a workaround for the problem described in `cpp`. It will simply consume all code between `#else` or `#elif`
* and `#endif`.
*/
static Result cpp_workaround(State *state) {
if (PEEK == '#') {
S_ADVANCE;
if (seq("el", state)) {
consume_until("#endif", state);
if (PEEK == 0) {
Result res = eof(state);
SHORT_SCANNER;
return res_fail;
}
return finish(CPP, "cpp-else");
}
cpp_consume(state);
MARK("cpp_workaround", false, state);
return finish(CPP, "cpp");
}
return res_cont;
}
/**
* If the current column i 0, a cpp directive may begin.
*/
static Result cpp_init(State *state) {
if (column(state) == 0) {
return cpp_workaround(state);
}
return res_cont;
}
/**
* End a layout by removing an indentation from the stack, but only if the current column (which should be in the next
* line after skipping whitespace) is smaller than the layout indent.
*/
static Result dedent(uint32_t indent, State *state) {
if (smaller_indent(indent, state)) return layout_end("dedent", state);
return res_cont;
}
/**
* Succeed if a `where` on a newline can end a statement or layout (see `is_newline_where`).
*
* This is the case after `do` or `of`, where the `where` can be on the same indent.
*/
static Result newline_where(uint32_t indent, State *state) {
if (is_newline_where(indent, state)) {
MARK("newline_where", false, state);
if (token("where", state)) {
return end_or_semicolon("newline_where", state);
}
return res_fail;
}
return res_cont;
}
/**
* Succeed for `SEMICOLON` if the indent of the next line is equal to the current layout's.
*/
static Result newline_semicolon(uint32_t indent, State *state) {
if (SYM(SEMICOLON) && same_indent(indent, state)) {
return finish(SEMICOLON, "newline_semicolon");
}
return res_cont;
}
/**
* A layout may be closed by an infix operator on the same column as a `do` layout:
*
* a :: IO Int
* a = do a <- pure 5
* pure a
* >>= pure
*
* In this situation, the entire `do` block is the left operand of the `>>=`.
* The same applies for `infix` functions.
*/
static bool end_on_infix(uint32_t indent, Symbolic type, State *state) {
return indent_lesseq(indent, state) && (expression_op(type) || PEEK == '`');
}
/**
* End a layout if the next token is an infix operator and the indent is equal to or less than the current layout.
*/
static Result newline_infix(uint32_t indent, Symbolic type, State *state) {
if (end_on_infix(indent, type, state)) {
return layout_end("newline_infix", state);
}
return res_cont;
}
/**
* Parse an inline `where` token.
*
* Necessary because `is_newline_where` needs to know that no `where` may follow.
*/
static Result where(State *state) {
if (token("where", state)) {
if (SYM(WHERE)) {
MARK("where", false, state);
return finish(WHERE, "where");
}
return layout_end("where", state);
}
return res_cont;
}
/**
* An `in` token ends the layout openend by a `let` and its nested layouts.
*/
static Result in(State *state) {
if (SYM(IN) && token("in", state)) {
MARK("in", false, state);
pop(state);
return finish(IN, "in");
}
return res_cont;
}
/**
* An `else` token may end a layout opened in the body of a `then`.
*/
static Result else_(State *state) {
return token("else", state) ? end_or_semicolon("else", state) : res_cont;
}
/**
* Detect the start of a quasiquote: An opening bracket followed by an optional varid and a vertical bar, all without
* whitespace in between
*/
static Result qq_start(State *state) {
MARK("qq_start", false, state);
while (quoter_char(PEEK)) S_ADVANCE;
if (PEEK == '|') return finish(QQ_START, "qq_start");
return res_cont;
}
static Result qq_body(State *state) {
for (;;) {
if (PEEK == 0) {
Result res = eof(state);
SHORT_SCANNER;
return res_fail;
}
MARK("qq_body", false, state);
if (PEEK == '\\') {
S_ADVANCE;
S_ADVANCE;
} else {
if (PEEK == '|') {
S_ADVANCE;
if (PEEK == ']') {
S_ADVANCE;
return finish(QQ_BODY, "qq_body");
}
}
S_ADVANCE;
}
}
}
/**
* When a dollar is followed by a varid or opening paren, parse a splice.
*/