/
scanner.cc
1653 lines (1451 loc) · 49.3 KB
/
scanner.cc
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
#include "tree_sitter/parser.h"
#include <vector>
#include <cstdio>
#include <iostream>
#include <functional>
#include <algorithm>
#include <string>
#include <iterator>
using namespace std;
/**
* The scanner is abstracted for compositionality as functions of the type:
*
* typedef function<Result(State&)> Parser;
*
* A simple parser can look like this:
*
* Result layout_start_brace(State & state) {
* if (next_char(state) == '{') return result::finish(Sym::start);
* else return result::cont;
* }
*
* With the provided combinators in `namespace `parser`, this can be rewritten as:
*
* Parser layout_start_brace = peek('{')(finish(Sym::start));
*
* In the API function `scan`, this parser can be executed:
*
* parser::eval(layout_start_brace, state);
*
* This will set the `lexer-result_symbol` accordingly and return a bool indicating success.
*
* Multiple parsers can be executed in succession with the plus operator:
*
* peek('w')(handle_w) + peek('i')(handle_i)
*
* If `handle_w` terminates with `result::finish` or `result::fail` instead of `result::cont`, `handle_i` is not
* executed.
*/
// --------------------------------------------------------------------------------------------------------
// Utilities
// --------------------------------------------------------------------------------------------------------
/**
* Print input and result information.
*/
bool debug = false;
/**
* Print the upcoming token after parsing finished.
* Note: May change parser behaviour.
*/
bool debug_next_token = false;
/**
* Print to stderr if the `debug` flag is `true`.
*/
struct Log {
template<class A> void operator()(A msg) { if (debug) cerr << msg << endl; }
} logger;
struct Endl {} nl;
template<class A> Log & operator<<(Log & l, const A & a) {
if (debug) cerr << a;
return l;
}
Log & operator<<(Log & l, Endl) {
if (debug) cerr << endl;
return l;
}
template<class A, class B> A fst(pair<A, B> p) { return p.first; }
template<class A, class B, class C> function<C(A)> operator*(function<C(B)> f, function<B(A)> g) {
return [=](A a) { return f(g(a)); };
}
template<class A, class B, class C> function<C(A)> operator*(function<C(B)> f, B (&g)(A)) {
return [=](A a) { return f(g(a)); };
}
template<class A, class B, class C> function<C(A)> operator*(C (&f)(B), function<B(A)> g) {
return [=](A a) { return f(g(a)); };
}
template<class A, class B> function<B(A)> const_(B b) { return [=](auto _) { return b; }; }
// --------------------------------------------------------------------------------------------------------
// Symbols
// --------------------------------------------------------------------------------------------------------
namespace syms {
/**
* 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
*/
enum Sym: uint16_t {
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,
};
vector<string> 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",
};
string name(Sym t) { return t < names.size() ? names[t] : "unknown"; }
/**
* 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.
*/
bool all(const bool *syms) { return std::all_of(syms, syms + empty, [](bool a) { return a; }); }
/**
* Append a symbol's string representation to the string `s` if it is valid.
*/
void add(string & s, const bool *syms, Sym t) {
if (syms[t]) {
if (!s.empty()) s += ",";
s += name(t);
}
}
/**
* Produce a comma-separated string of valid symbols.
*/
string valid(const bool *syms) {
if (syms::all(syms)) return "all";
string result = "";
for (Sym i = semicolon; i <= semicolon + empty; i = Sym(i + 1)) add(result, syms, i);
return '"' + result + '"';
}
}
using syms::Sym;
// --------------------------------------------------------------------------------------------------------
// 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.
*/
struct State {
TSLexer *lexer;
const bool *symbols;
vector<uint16_t> & indents;
int marked;
string marked_by;
State(TSLexer *l, const bool *vs, vector<uint16_t> & is):
lexer(l),
symbols(vs),
indents(is),
marked(-1),
marked_by("")
{}
};
const string format_indents(State & state) {
if (state.indents.empty()) return "empty";
string s;
for (auto i : state.indents) {
if (!s.empty()) s += "-";
s += std::to_string(i);
}
return s;
}
ostream & operator<<(ostream & out, State & state) {
return out << "State { syms = " << syms::valid(state.symbols) <<
", indents = " << format_indents(state) <<
" }";
}
/**
* These functions provide the basic interface to the lexer.
* They are not defined as members for easier composition.
*/
namespace state {
bool eof(State & state) { return state.lexer->eof(state.lexer); }
/**
* The parser's position in the current line.
*/
uint32_t column(State & state) {
return eof(state) ? 0 : state.lexer->get_column(state.lexer);
}
/**
* The next character that would be parsed.
* Does not advance the parser position (consume the character).
*/
uint32_t next_char(State & state) { return state.lexer->lookahead; }
/**
* Move the parser position one character to the right, treating the consumed character as part of the parsed token.
*/
void advance(State & state) { state.lexer->advance(state.lexer, false); }
/**
* Move the parser position one character to the right, treating the consumed character as whitespace.
*/
void skip(State & state) { state.lexer->advance(state.lexer, true); }
function<void(State&)> mark(string marked_by) {
return [=](State & state) {
if (debug) {
state.marked = column(state);
state.marked_by = marked_by;
}
state.lexer->mark_end(state.lexer);
};
}
}
// --------------------------------------------------------------------------------------------------------
// Condition
// --------------------------------------------------------------------------------------------------------
/**
* A predicate for the next character.
*
* With the provided operator overloads, conditions can be logically combined without having to write lambdas for
* passing along the character.
*/
typedef function<bool(uint32_t)> Peek;
Peek operator&(const Peek & l, const Peek & r) { return [=](uint32_t c) { return l(c) && r(c); }; }
Peek operator|(const Peek & l, const Peek & r) { return [=](uint32_t c) { return l(c) || r(c); }; }
Peek not_(Peek con) { return [=](uint32_t c) { return !con(c); }; }
/**
* This type abstracts over a boolean predicate of the current state.
* It is used whenever a condition should guard a nested parser.
*
* With the provided operator overloads, conditions can be logically combined without having to write lambdas for
* passing along the `State`.
*/
typedef function<bool(State&)> Condition;
Condition operator&(const Condition & l, const Condition & r) { return [=](auto s) { return l(s) && r(s); }; }
Condition operator|(const Condition & l, const Condition & r) { return [=](auto s) { return l(s) || r(s); }; }
Condition not_(const Condition & c) { return [=](State & state) { return !c(state); }; }
/**
* Peeking the next character uses the `State` to access the lexer and returns the predicate success as well as the
* character itself.
*/
typedef function<pair<bool, uint32_t>(State &)> PeekResult;
/**
* The set of conditions used in the parser implementation.
*/
namespace cond {
Condition pure(bool c) { return const_<State&>(c); }
Peek eq(uint32_t target) { return [=](uint32_t c) { return target == static_cast<uint32_t>(c); }; }
bool varid_start_char(const uint32_t c) { return eq('_')(c) || iswlower(c); }
bool varid_char(const uint32_t c) { return eq('_')(c) || eq('\'')(c) || iswalnum(c); };
bool quoter_char(const uint32_t c) { return varid_char(c) || eq('.')(c); };
/**
* Require that the next character matches a predicate, without advancing the parser.
* Returns the next char as well.
*/
function<std::pair<bool, uint32_t>(State &)> peeks(Peek pred) {
return [=](State & state) {
auto c = state::next_char(state);
auto res = pred(c);
return std::make_pair(res, c);
};
}
Condition peek_with(Peek pred) { return fst<bool, uint32_t> * peeks(pred); }
Condition varid = cond::peek_with(cond::varid_start_char);
/**
* Require that the next character equals a concrete `c`, without advancing the parser.
*/
Condition peek(uint32_t c) { return fst<bool, uint32_t> * peeks(eq(c)); }
/**
* Require that the next character matches a predicate, advancing the parser on success, treating the character as
* whitespace.
*/
PeekResult skip_if(Peek pred) {
return [=](State & state) {
auto res = peeks(pred)(state);
if (res.first) { state::skip(state); }
return res;
};
}
/**
* Like `skip_if`, but only return the bool result.
*/
Condition skips(Peek pred) { return fst<bool, uint32_t> * skip_if(pred); }
/**
* Require that the next character equals a concrete `c`, advancing the parser on success, treating the character as
* whitespace.
*/
Condition skip(uint32_t c) { return skips(eq(c)); }
/**
* Require that the next character matches a predicate, advancing the parser on success.
*/
PeekResult consume_if(Peek pred) {
return [=](State & state) {
auto res = peeks(pred)(state);
if (res.first) { state::advance(state); }
return res;
};
}
/**
* Like `consume_if`, but only return the bool result.
*/
Condition consumes(Peek pred) { return fst<bool, uint32_t> * consume_if(pred); }
/**
* Require that the next character equals a concrete `c`, advancing the parser on success.
*/
Condition consume(uint32_t c) { return consumes(eq(c)); }
/**
* Require that the argument string follows the current position, consuming all characters.
* Note: This leaves characters from a partial match consumed, there is no way to backtrack the parser.
*/
Condition seq(const string & s) {
return [=](State & state) { return all_of(s.begin(), s.end(), [&](auto a) { return consume(a)(state); }); };
}
function<void(State &)> consume_while(Peek pred) {
return [=](State & state) {
while (true) {
if (state::eof(state)) break;
uint32_t c = state::next_char(state);
if (!pred(c)) break;
state::advance(state);
}
};
}
// TODO this breaks if the target sequence has a repetition of its prefix
function<void(State &)> consume_until(string target) {
if (target.empty()) return [=](auto) {};
uint32_t first = target[0];
return [=](State & state) {
Peek check = [&](uint32_t c) {
if (eq(first)(c)) {
state::mark("consume_until " + target)(state);
return !seq(target)(state);
}
else return true;
};
return consume_while(check)(state);
};
}
function<u32string(State &)> read_string(Peek pred) {
return [=](State & state) {
u32string s;
consume_while([&](uint32_t c) {
auto res = pred(c);
if (res) s += static_cast<uint32_t>(c);
return res;
})(state);
return s;
};
}
/**
* Require that the argument symbol is valid for the current parse tree state.
*/
Condition sym(Sym t) { return [=](State & state) { return state.symbols[t]; }; }
/**
* Require that the next character is whitespace (space or newline) without advancing the parser.
*/
Condition peekws = [](State & state) { return iswspace(state::next_char(state)); };
/**
* Require that the next character is end-of-file.
*/
Condition peekeof = peek(0);
/**
* A token like a varsym can be terminated by whitespace of brackets.
*/
Condition token_end =
peekeof | peekws | peek(')') | peek(']') | peek('[') | peek('(');
/**
* Require that the argument string follows the current position and is followed by whitespace.
* See `seq`
*/
Condition token(const string & s) { return seq(s) & token_end; }
/**
* Require that the stack of layout indentations is not empty.
* This is mostly used for safety.
*/
const bool indent_exists(State & state) { return !state.indents.empty(); };
/**
* Helper function for executing a condition callback with the current indentation.
*/
Condition check_indent(function<bool(uint16_t)> f) {
return [=](State & state) { return indent_exists(state) && f(state.indents.back()); };
}
/**
* Require that the current line's indent is greater or equal than the containing layout's, so the current layout is
* continued.
*/
Condition keep_layout(uint16_t indent) { return check_indent([=](auto i) { return indent >= i; }); }
/**
* Require that the current line's indent is equal to the containing layout's, so the line may start a new `decl`.
*/
Condition same_indent(uint32_t indent) { return check_indent([=](auto i) { return indent == i; }); }
/**
* Require that the current line's indent is smaller than the containing layout's, so the layout may be ended.
*/
Condition smaller_indent(uint32_t indent) { return check_indent([=](auto i) { return indent < i; }); }
Condition indent_lesseq(uint32_t indent) { return check_indent([=](auto i) { return indent <= i; }); }
/**
* 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.
*/
Condition is_newline_where(uint32_t indent) {
return keep_layout(indent) & (sym(Sym::semicolon) | sym(Sym::end)) & (not_(sym(Sym::where))) & peek('w');
}
Peek newline = eq('\n') | eq('\r') | eq('\f');
Peek ticked = eq('`');
/**
* Require that the state has not been initialized after parsing has started.
*
* This is necessary to handle a nonexistent `module` declaration.
*/
bool uninitialized(State & state) { return !indent_exists(state); }
Condition column(uint32_t col) {
return [=](State & state) { return state::column(state) == col; };
}
/**
* Require that the parser determined an error in the previous step (see `syms::all`).
*/
bool after_error(State & state) { return syms::all(state.symbols); }
bool symbolic(uint32_t c) {
switch (c) {
case '!':
case '#':
case '$':
case '%':
case '&':
case '*':
case '+':
case '.':
case '/':
case '<':
case '>':
case '?':
case '^':
case ':':
case '=':
case '|':
case '-':
case '~':
case '@':
case '\\':
return true;
default:
return false;
}
}
Peek valid_first_varsym = not_(eq(':')) & symbolic;
/**
* Test for reserved operators of two characters.
*/
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;
}
}
Condition valid_splice = peek_with(cond::varid_start_char) | peek('(');
}
namespace symbolic {
enum Symbolic: uint16_t {
con,
op,
splice,
strict,
star,
tilde,
implicit,
modifier,
minus,
unboxed_tuple_close,
bar,
comment,
invalid,
};
bool success(Symbolic type) { return type == Symbolic::con || type == Symbolic::op; }
Symbolic con_or_var(uint32_t c) { return c == ':' ? Symbolic::con : Symbolic::op; }
bool single(uint32_t c) {
switch (c) {
case '!':
case '#':
case '%':
case '&':
case '*':
case '+':
case '/':
case '<':
case '>':
case '?':
case '^':
case '.':
case '$':
return true;
default:
return false;
}
}
/**
* Symbolic operators that are eligible to close a layout when they are on a newline with less/eq indent.
*
* Very crude heuristic. Layouts bad.
*/
bool expression_op(Symbolic type) {
switch (type) {
case Symbolic::op:
case Symbolic::con:
case Symbolic::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 `cond::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.
*/
function<Symbolic(State &)> symop(u32string s) {
return [=](State & state) {
if (s.empty()) return Symbolic::invalid;
uint32_t c = s[0];
if (s.size() == 1) {
if (c == '!' && !(cond::peekws(state) || cond::peek(')')(state))) return Symbolic::strict;
if (c == '#' && cond::peek(')')(state)) return Symbolic::unboxed_tuple_close;
if (c == '#' && cond::peek_with(cond::varid_start_char)(state)) return Symbolic::invalid;
if (c == '$' && cond::valid_splice(state)) return Symbolic::splice;
if (c == '?' && cond::varid(state)) return Symbolic::implicit;
if (c == '%' && !(cond::peekws(state) || cond::peek(')')(state))) return Symbolic::modifier;
if (c == '|') return Symbolic::bar;
switch (c) {
case '*':
return Symbolic::star;
case '~':
return Symbolic::tilde;
case '-':
return Symbolic::minus;
case '=':
case '@':
case '\\':
return Symbolic::invalid;
default: return con_or_var(c);
}
} else {
if (all_of(s.begin(), s.end(), cond::eq('-'))) return Symbolic::comment;
if (s.size() == 2) {
if (s[0] == '$' && s[1] == '$' && cond::valid_splice(state)) return Symbolic::splice;
if (!cond::valid_symop_two_chars(s[0], s[1])) return Symbolic::invalid;
}
}
return con_or_var(c);
};
}
}
using symbolic::Symbolic;
// --------------------------------------------------------------------------------------------------------
// 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 – `Sym::fail` signals failure.
*/
struct Result {
Sym sym;
bool finished;
Result(Sym s, bool f): sym(s), finished(f) {}
};
template<class A> ostream & operator<<(ostream & out, const Result & res) {
out << "Result { finished = " << res.finished;
if (res.finished) out << ", " << "result = " << syms::name(res.sym);
return out << " }";
}
/**
* Constructors for the continue, failure and success results.
*/
namespace result {
Result cont = Result(Sym::fail, false);
Result finish(Sym t) { return Result(t, true); }
Result fail = finish(Sym::fail);
}
// --------------------------------------------------------------------------------------------------------
// Parser
// --------------------------------------------------------------------------------------------------------
namespace parser {
/**
* The main function shape for all parser combinators.
*/
typedef function<Result(State&)> Parser;
/**
* Parsers that depend on the next character.
*/
typedef function<Parser(uint32_t)> CharParser;
/**
* Convenience alias for a function that attaches conditions to a parser.
*/
typedef function<Parser(Parser)> Modifier;
/**
* Combinators that manipulate the state without producing a value or parse result.
*/
typedef function<void(State&)> Effect;
/**
* Monadic bind for `Parser`. (>>=)
*/
template<class A> function<Parser(function<Parser(A)>)> with(A (&fa)(State &)) {
return [&](function<Parser(A)> f) {
return [=](State & state) {
return f(fa(state))(state);
};
};
}
template<class A> function<Parser(function<Parser(A)>)> with(function<A(State &)> fa) {
return [&](function<Parser(A)> f) {
return [=](State & state) {
return f(fa(state))(state);
};
};
}
/**
* Variant of `with` that discards the left operand's result. (>>)
*
* Semantics are "execute the right parser if the left parser doesn't finish".
*/
Parser operator+(Parser fa, Parser fb) {
return [=](State & state) {
auto res = fa(state);
return res.finished ? res : fb(state);
};
}
/**
* Depending on the result of a condition, execute one of the supplied parsers.
*/
Parser either(Condition c, Parser match, Parser nomatch) {
return [=](State & state) { return c(state) ? match(state) : nomatch(state); };
}
/**
* Depending on the result of a condition, execute one of the supplied parsers.
*/
Parser either(bool c, Parser match, Parser nomatch) { return either(const_<State &>(c), match, nomatch); }
/**
* Lazy evaluation for recursion.
*/
Parser lazy(function<Parser()> p) {
return [=](State & state) { return p()(state); };
}
/**
* Execute an `Effect`, then continue.
*/
Parser effect(Effect eff) {
return [=](State & state) {
eff(state);
return result::cont;
};
}
/**
* Parser that terminates the execution with the successful detection of the given symbol.
*/
Parser finish(const Sym s, string desc) {
return [=](auto _) {
logger << "finish: " << desc << nl;
return result::finish(s);
};
}
/**
* Parser that terminates the execution unsuccessfully.
*/
Parser fail = ::const_<State>(result::fail);
/**
* Parser that does nothing, causing the next parser to be executed.
*/
Parser cont = ::const_<State>(result::cont);
CharParser as_char_parser(CharParser p) { return p; }
CharParser as_char_parser(Parser p) { return ::const_<uint32_t>(p); }
CharParser as_char_parser(Result r) { return ::const_<uint32_t>(::const_<State>(r)); }
/**
* Require a condition to be true for the next parser to be executed.
*
* If the condition is false, parsing continues after the skipped parser.
*
* This function returns a function, so it is applied with two parameter lists:
*
* iff(cond::after_error)(fail)
*/
Modifier iff(Condition c) { return [=](Parser next) { return either(c, next, cont); }; }
/**
* Require a plain `bool` to be true for the next parser to be executed.
*/
Modifier when(const bool c) { return iff(::const_<State>(c)); }
/**
* Require the given symbol to be valid for the next parser to be executed.
*/
Modifier sym(const Sym s) { return iff(cond::sym(s)); }
/**
* Parser that terminates the execution with the successful detection of the given symbol, but only if it is expected.
*/
Parser finish_if_valid(const Sym s, string desc) { return sym(s)(finish(s, desc)); }
/**
* :: (State -> (bool, uint32_t)) -> (uint32_t -> Parser) -> (uint32_t -> Parser) -> Parser
*
* If the predicate is true, pass the character to the `match` parser, otherwise the `nomatch`
* parser.
*
* The template allows passing in `Parser` or `Result` for the `(uint32_t -> Parser)` parameters.
*/
template<class A, class B> Parser either(function<pair<bool, uint32_t>(State &)> con, A match, B nomatch) {
return [=](State & state) {
auto res = con(state);
return res.first ? as_char_parser(match)(res.second)(state) : as_char_parser(nomatch)(res.second)(state);
};
}
/**
* :: (uint32_t -> bool) -> (uint32_t -> Parser) -> (uint32_t -> Parser) -> Parser
*
* If the predicate for the next character is true, pass the character to the `match` parser, otherwise the `nomatch`
* parser.
*
* The template allows passing in `Parser` or `Result` for the `(uint32_t -> Parser)` parameters.
*/
template<class A, class B> Parser peeks(Peek pred, A match, B nomatch) {
return either(cond::peeks(pred), match, nomatch);
}
/**
* :: (uint32_t -> bool) -> Parser -> Parser
*
* Specialization for a conditional parser that's executed in the success case.
*/
Modifier peeks(Peek pred) { return [=](Parser next) { return peeks(pred, next, result::cont); }; }
/**
* Requires the next character to be `c` for the next parser to be executed.
*/
Modifier peek(uint32_t c) { return peeks(cond::eq(c)); }
/**
* :: (uint32_t -> bool) -> (uint32_t -> Parser) -> Parser
*
* If the predicate for the next character is true, advance the lexer and pass the consumed character to the next
* parser.
*/
function<Parser(CharParser)> consume_if(Peek pred) {
return [=](const CharParser & next) { return either(cond::consume_if(pred), next, result::cont); };
}
/**
* Require the next character to be `c` for the next parser to be executed, advancing the lexer in the success case.
*/
Modifier consume(uint32_t c) { return [=](Parser next) { return consume_if(cond::eq(c))(as_char_parser(next)); }; }
/**
* Consume all characters while the predicate holds.
*/
Parser consume_while(Peek pred) { return effect(cond::consume_while(pred)); }
/**
* Consume all characters until the given sequence is encountered.
*/
Parser consume_until(string s) { return effect(cond::consume_until(s)); }
/**
* Advance the lexer.
*/
Parser advance = effect(state::advance);
/**
* Skip whitespace.
*/
Parser skip_ws = effect([](State & state) { while (cond::peekws(state)) state::skip(state); });
Modifier seq(string s) { return iff(cond::seq(s)); }
/**
* Require the next characters to be equal to `s` for the next parser to be executed, advancing the lexer as far as the
* characters match, even if not all of them match.
*/
Modifier token(string s) { return iff(cond::token(s)); }
/**
* 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.
*/
Parser mark(string target) { return effect(state::mark(target)); }
/**
* If the parser returns `cont`, fail.
*/
Parser or_fail(Parser chk) { return chk + fail; }
/**
* Require the next character to be whitespace for the next parser to be executed, not advancing the lexer.
*/
Modifier peekws = iff(cond::peekws);
/**
* Add one level of indentation to the stack, caused by starting a layout.
*/
Parser push(uint16_t ind) { return effect([=](State & state) {
logger << "push: " << ind << nl;
state.indents.push_back(ind);