-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathParserTest.cs
1329 lines (998 loc) · 49 KB
/
ParserTest.cs
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
using System;
using System.Linq;
using ChainingAssertion;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ParsecSharp;
using static ParsecSharp.Parser;
using static ParsecSharp.Text;
namespace UnitTest.ParsecSharp;
[TestClass]
public class ParserTest
{
[TestMethod]
public void AnyTest()
{
// Creates a parser that matches any token.
// This parser only fails if the input is at the end.
var parser = Any();
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
}
[TestMethod]
public void TokenTest()
{
// Creates a parser that matches a specified token.
// Uses `EqualityComparer<T>.Default` for equality comparison.
var source = "abcdEFGH";
var source2 = "123456";
// Parser that matches the token 'a'.
var parser = Token('a');
parser.Parse(source).WillSucceed(value => value.Is('a'));
parser.Parse(source2).WillFail();
}
[TestMethod]
public void EndOfInputTest()
{
// Creates a parser that matches the end of the input.
var parser = EndOfInput();
var source = string.Empty;
parser.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void NullTest()
{
// Creates a parser that matches an empty string and always succeeds in any state.
// This parser does not consume input.
var parser = Null();
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
var source2 = string.Empty;
parser.Parse(source2).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void OneOfTest()
{
// Creates a parser that succeeds if the token is included in the specified sequence.
// Parser that succeeds if the token is one of '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e'.
var parser = OneOf("6789abcde");
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
var source2 = "123456";
parser.Parse(source2).WillFail();
// Overload that takes `params IEnumerable<char>`.
var parser2 = OneOf('6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e');
parser2.Parse(source).WillSucceed(value => value.Is('a'));
parser2.Parse(source2).WillFail();
}
[TestMethod]
public void NoneOfTest()
{
// Creates a parser that succeeds if the token is not included in the specified sequence.
var source = "abcdEFGH";
var source2 = "123456";
// Parser that succeeds if the token is not one of 'd', 'c', 'b', 'a', '9', '8', '7'.
var parser = NoneOf("dcba987");
parser.Parse(source).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): Unexpected 'a<0x61>'"));
parser.Parse(source2).WillSucceed(value => value.Is('1'));
// Overload that takes `params IEnumerable<char>`.
var parser2 = NoneOf('d', 'c', 'b', 'a', '9', '8', '7');
parser2.Parse(source).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): Unexpected 'a<0x61>'"));
parser2.Parse(source2).WillSucceed(value => value.Is('1'));
}
[TestMethod]
public void TakeTest()
{
// Creates a parser that reads the specified number of tokens and returns the result as a sequence.
// Parser that reads 3 tokens.
var parser = Take(3);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is('1', '2', '3'));
// If the specified number of tokens exceeds the remaining input, the parser fails.
var parser2 = Take(9);
parser2.Parse(source).WillFail(failure => failure.Message.Is("An input does not have enough length"));
// If 0 is specified, the parser succeeds without consuming input.
var parser3 = Take(0);
parser3.Parse(source).WillSucceed(value => value.Is([]));
// If a value less than 0 is specified, the parser always fails.
var parser4 = Take(-1);
parser4.Parse(source).WillFail(failure => failure.Message.Is("An input does not have enough length"));
}
[TestMethod]
public void SkipTest()
{
// Creates a parser that skips the specified number of tokens.
var source = "abcdEFGH";
// Parser that skips 3 tokens and then returns the next token.
var parser = Skip(3).Right(Any());
parser.Parse(source).WillSucceed(value => value.Is('d'));
var parser2 = Skip(8).Right(EndOfInput());
parser2.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
// If the specified number of tokens cannot be skipped, the parser fails.
var parser3 = Skip(9);
parser3.Parse(source).WillFail(failure => failure.Message.Is("An input does not have enough length"));
// If 0 is specified, the parser succeeds without consuming input.
var parser4 = Skip(0);
parser4.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
// If a value less than 0 is specified, the parser always fails.
var parser5 = Skip(-1);
parser5.Parse(source).WillFail(failure => failure.Message.Is("An input does not have enough length"));
}
[TestMethod]
public void TakeWhileTest()
{
// Creates a parser that continues to read input as long as the given condition is met.
// Parser that continues to read input as long as the token is lowercase letter.
var parser = TakeWhile(char.IsLower);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is(Enumerable.Empty<char>()));
}
[TestMethod]
public void TakeWhile1Test()
{
// Creates a parser that continues to read input as long as the given condition is met.
// If no match is found, the parser fails.
// Parser that continues to read input as long as the token is lowercase letter.
var parser = TakeWhile1(char.IsLower);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd'));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void SkipWhileTest()
{
// Creates a parser that continues to consume input as long as the given condition is met and discards the result.
// Works the same as `TakeWhile` but does not collect the result, making it more efficient.
// Parser that continues to consume input as long as the token is lowercase letter.
var parser = SkipWhile(char.IsLower);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void SkipWhile1Test()
{
// Creates a parser that continues to consume input as long as the given condition is met and discards the result.
// If it cannot skip at least one token, it fails.
// Parser that continues to consume input as long as the token is lowercase letter.
var parser = SkipWhile1(char.IsLower);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void SatisfyTest()
{
// Creates a parser that takes one input and succeeds if the condition is met.
// Can be used to construct all parsers that consume input.
var source = "abcdEFGH";
// Parser that matches 'a'.
var parser = Satisfy(x => x == 'a'); // == Char('a');
parser.Parse(source).WillSucceed(value => value.Is('a'));
// Parser that matches any of 'a', 'b', 'c'.
var parser2 = Satisfy("abc".Contains); // == OneOf("abc");
parser2.Parse(source).WillSucceed(value => value.Is('a'));
}
[TestMethod]
public void PureTest()
{
// Creates a parser that returns a success result.
// Used to inject arbitrary values into the parser.
// This parser does not consume input.
var parser = Pure("success!");
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is("success!"));
// Delays the generation of the value until the parser is executed.
var parser2 = Pure(_ => Unit.Instance);
parser2.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void FailTest()
{
// Creates a parser that returns a failure result.
// This parser does not consume input.
var source = "abcdEFGH";
var parser = Fail<Unit>();
parser.Parse(source).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): Unexpected 'a<0x61>'"));
// Overload that allows specifying an error message.
var parser2 = Fail<Unit>("errormessagetest");
parser2.Parse(source).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): errormessagetest"));
// Can handle the state at the time of parse failure.
var parser3 = Fail<Unit>(state => $"errormessagetest, current state: '{state}'");
parser3.Parse(source).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): errormessagetest, current state: 'a<0x61>'"));
}
[TestMethod]
public void AbortTest()
{
// Creates a parser that aborts the parsing process when executed.
// Usually not used directly. Use the `AbortIfEntered` or `AbortWhenFail` combinator.
// Matches `Abort` or `Any`, but the parsing process ends when `Abort` is evaluated.
var parser = Abort<char>(_ => "aborted").Or(Any());
var source = "123456";
parser.Parse(source).WillFail(failure => failure.Message.Is("aborted"));
}
[TestMethod]
public void GetPositionTest()
{
// Creates a parser that retrieves the position of the parse location.
// This parser does not consume input.
// Parser that matches `Any` 3 times and then returns the position at that point.
var parser = Any().Repeat(3).Right(GetPosition());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Column.Is(4));
}
[TestMethod]
public void ChoiceTest()
{
// Creates a parser that applies parsers from the beginning and returns the result of the first one that succeeds.
// If all fail, the last failure is returned as the overall failure.
// Parser that matches 'c', 'b', or 'a'.
var parser = Choice(Char('c'), Char('b'), Char('a'));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void SequenceTest()
{
// Creates a parser that matches parsers in sequence and returns the concatenated result as a sequence.
// Parser that matches 'a' + 'b' + 'c' + 'd' and converts to "abcd".
var parser = Sequence(Char('a'), Char('b'), Char('c'), Char('d')).AsString();
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is("abcd"));
var source2 = "abCDEF";
parser.Parse(source2).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 3): Unexpected 'C<0x43>'"));
// You can pass an arbitrary number of parsers using the `params IEnumerable<T>` overload.
var parser2 = Sequence(Char('a'), Char('b'), Char('c'), Char('d'), Char('E'), Char('F'), Char('G'), Char('H'), Pure('_')).AsString();
parser2.Parse(source).WillSucceed(value => value.Is("abcdEFGH_"));
parser2.Parse(source2).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 3): Unexpected 'C<0x43>'"));
// `Sequence` has overloads to handle parsers with different types, supporting up to 8 parsers.
var parser3 = Sequence(Char('a'), String("bc"), HexDigit(), SkipMany(Upper()), Pure(999), (a, bc, d, _, i) => new { a, bc, d, i });
parser3.Parse(source).WillSucceed(value => value.Is(x => x.a == 'a' && x.bc == "bc" && x.d == 'd' && x.i == 999));
}
[TestMethod]
public void TryTest()
{
// Creates a parser that executes the parse with parser and returns the value of resume if it fails, always succeeding.
// If parser fails to match, it does not consume input.
// Parser that matches 'a' and returns 'a' if successful, 'x' if it fails.
var parser = Try(Char('a'), 'x');
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is('x'));
// Overload that delays the evaluation of resume.
var parser2 = Try(Char('a'), _ => 'x');
parser2.Parse(source).WillSucceed(value => value.Is('a'));
}
[TestMethod]
public void OptionalTest()
{
// Creates a parser that executes the parse with parser and returns a bool indicating whether it matched, always succeeding.
// If the parser fails to match, it does not consume input.
var source = "abcdEFGH";
var source2 = "123456";
// Parser that matches `Digit`, returns boolean value that matches or not, then matches `Any`.
var parser = Optional(Digit()).Right(Any());
parser.Parse(source).WillSucceed(value => value.Is('a'));
parser.Parse(source2).WillSucceed(value => value.Is('2'));
// Overload that returns a specified default value if it fails.
var parser2 = Optional(Lower(), '\n');
parser2.Parse(source).WillSucceed(value => value.Is('a'));
parser2.Parse(source2).WillSucceed(value => value.Is('\n'));
}
[TestMethod]
public void NotTest()
{
// Creates a parser that succeeds if parser fails.
// This parser does not consume input.
// Parser that succeeds if the token is not `Lower`.
var parser = Not(Lower());
var source = "abcdEFGH";
parser.Parse(source).WillFail();
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void LookAheadTest()
{
// Creates a parser that performs a parse with parser without consuming input.
// Parser that matches `Any` then `Letter` without consuming input, then matches `Any` and concatenates the results.
var parser = LookAhead(Any().Right(Letter())).Append(Any());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('b', 'a'));
var source2 = "123456";
parser.Parse(source2).WillFail(failure => failure.ToString().Is("Parser Failure (Line: 1, Column: 1): At LookAhead -> Parser Failure (Line: 1, Column: 2): Unexpected '2<0x32>'"));
}
[TestMethod]
public void ManyTest()
{
// Creates a parser that matches parser 0 or more times and returns the result as a sequence.
// If it does not match even once, the parser returns an empty sequence. In this case, it does not consume input.
// Parser that matches `Lower` 0 or more times.
var parser = Many(Lower());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.IsEmpty());
}
[TestMethod]
public void Many1Test()
{
// Creates a parser that matches parser 1 or more times and returns the result as a sequence.
// If it does not match even once, the parser returns a failure.
// Parser that matches `Lower` 1 or more times.
var parser = Many1(Lower());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd'));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void SkipManyTest()
{
// Creates a parser that matches parser 0 or more times and discards the result.
// If it does not match even once, it does not consume input.
// Parser that matches `Lower` 0 or more times, discards the result, then matches `Any`.
var parser = SkipMany(Lower()).Right(Any());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('E'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is('1'));
}
[TestMethod]
public void SkipMany1Test()
{
// Creates a parser that matches parser 1 or more times and discards the result.
// Parser that matches `Lower` 1 or more times, discards the result, then matches `Any`.
var parser = SkipMany1(Lower()).Right(Any());
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('E'));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void ManyTillTest()
{
// Creates a parser that matches parser repeatedly until terminator is matched and returns the result as a sequence.
// The result of matching terminator is discarded.
var source = "abcdEFGH";
var source2 = "123456";
// Parser that matches `Any` repeatedly until 'F' is matched.
var parser = ManyTill(Any(), Char('F'));
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd', 'E'));
// If terminator is not matched, the parser fails.
parser.Parse(source2).WillFail();
// Use `Many1Till` to ensure that parser matches at least once.
var parser2 = Many1Till(Letter(), EndOfInput());
parser2.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd', 'E', 'F', 'G', 'H'));
// Since it does not match `Letter`, the parser fails.
parser2.Parse(source2).WillFail();
}
[TestMethod]
public void SkipTillTest()
{
// Creates a parser that repeatedly matches parser until it matches terminator and returns the result of matching terminator.
// Parser that skips `Lower` until it matches "cd".
var parser = SkipTill(Lower(), String("cd"));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is("cd"));
// Fails because an uppercase letter exists before "cd".
var source2 = "xyzABcdef";
parser.Parse(source2).WillFail();
// Use `Skip1Till` to ensure that parser matches at least once.
var parser2 = Skip1Till(Letter(), EndOfInput());
parser2.Parse(source).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void TakeTillTest()
{
// Creates a parser that reads input until it matches terminator and returns the result as a sequence.
// The result of matching terminator is discarded. Use `LookAhead` combinator if you do not want to consume it.
// Parser that reads input until it matches 'E'.
var parser = TakeTill(Char('E'));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a', 'b', 'c', 'd'));
// If a terminator that does not match until the end is given, the parser will read the stream to the end,
// which may affect performance.
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void MatchTest()
{
// Creates a parser that skips until it matches parser and returns the result of matching parser.
// Parser that skips until it matches "FG".
var parser = Match(String("FG"));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is("FG"));
var source2 = "123456";
parser.Parse(source2).WillFail();
// Parser that skips until it matches `Lower` + `Upper`.
var parser2 = Match(Sequence(Lower(), Upper())).AsString();
parser2.Parse(source).WillSucceed(value => value.Is("dE"));
}
[TestMethod]
public void QuotedTest()
{
// Creates a parser that retrieves the sequence of tokens between the parsers that match before and after.
// Can be used to retrieve tokens like strings.
// Use the `Quote` extension method if you want to add conditions to the match of the token sequence.
// Parser that retrieves the string between '<' and '>'.
var parser = Quoted(Char('<'), Char('>')).AsString();
var source = "<abcd>";
parser.Parse(source).WillSucceed(value => value.Is("abcd"));
// Parser that retrieves the string between '<' and '>', and then retrieves the string between them.
var parser2 = Quoted(parser).AsString();
var source2 = "<span>test</span>";
parser2.Parse(source2).WillSucceed(value => value.Is("test"));
}
[TestMethod]
public void AtomTest()
{
// Treats the specified parser as the smallest unit of the parser.
// Even if the parsing process fails halfway, it backtracks to the starting point.
// Use in combination with `WithConsume` / `AbortIfEntered`.
var abCD = Sequence(Char('a'), Char('b'), Char('C'), Char('D'));
var parser = Atom(abCD);
var source = "abcdEFGH";
abCD.Parse(source).WillFail(failure => failure.State.Position.Is(position => position.Line == 1 && position.Column == 3));
parser.Parse(source).WillFail(failure => failure.State.Position.Is(position => position.Line == 1 && position.Column == 1));
}
[TestMethod]
public void DelayTest()
{
// Delays the construction of the specified parser until the parsing execution.
// Can also be used as a reference holder, essential for forward references and recursion.
// Parser that matches 'a'. However, it is constructed at the time of parsing execution.
var parser = Delay(() => Char('a'));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
// The `Func<T>` passed to `Delay` is executed only once at the time of parsing execution.
// Therefore, be careful as it may behave unexpectedly if the process contains side effects.
// Reusing this parser object can improve performance.
}
[TestMethod]
public void FixTest()
{
// A helper combinator for constructing self-recursive parsers in local variables or parser definition expressions.
// Due to the specifications of C#, it is necessary to provide type arguments when used alone due to lack of type information.
// Parser that matches a character enclosed in any number of "{}".
var parser = Fix<char>(self => self.Or(Any()).Between(Char('{'), Char('}')));
var source = "{{{{{*}}}}}";
parser.Parse(source).WillSucceed(value => value.Is('*'));
// Overload that takes parameters. Allows flexible description of recursive parsers.
// Famous palindrome parser. S ::= "a" S "a" | "b" S "b" | ""
var parser2 = Fix<IParser<char, Unit>, Unit>((self, rest) =>
Char('a').Right(self(Char('a').Right(rest))) | Char('b').Right(self(Char('b').Right(rest))) | rest);
var source2 = "abbaabba";
parser2(EndOfInput()).Parse(source2).WillSucceed(value => value.Is(Unit.Instance));
}
[TestMethod]
public void NextTest()
{
// A combinator that allows direct description of continuation processing for parser.
// Since it is processed as a continuation, it can be used to avoid performance degradation by defining self-recursive parsers.
// Parser that matches `Letter`, returns the result of matching the next `Letter` if successful, and returns '\n' if it fails.
var parser = Letter().Next(_ => Letter(), '\n');
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('b'));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is('\n'));
// The overall result is failure because the first `Letter` succeeded but the next `Letter` failed.
var source3 = "a123";
parser.Parse(source3).WillFail();
}
[TestMethod]
public void GuardTest()
{
// Branches success and failure based on a condition for the result matched by parser.
// Parser that matches a number and succeeds only if it is less than 1000.
var parser = Many1(DecDigit()).ToInt().Guard(x => x < 1000);
var source = "123456";
parser.Parse(source).WillFail(failure => failure.Message.Is("A value '123456' does not satisfy condition"));
var source2 = "999";
parser.Parse(source2).WillSucceed(value => value.Is(999));
// If the parser does not match, the validation itself is not performed.
var source3 = "abcdEFGH";
parser.Parse(source3).WillFail();
}
[TestMethod]
public void SeparatedByTest()
{
// Creates a parser that matches parser repeated 0 or more times separated by separator.
// The result of matching separator is discarded.
// [ 1*Number *( "," 1*Number ) ]
var parser = Many1(Number()).AsString().SeparatedBy(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456", "789"));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is("123456"));
var source3 = "abcdEFGH";
parser.Parse(source3).WillSucceed(value => value.IsEmpty());
}
[TestMethod]
public void SeparatedBy1Test()
{
// Creates a parser that matches parser repeated 1 or more times separated by separator.
// 1*Number *( "," 1*Number )
var parser = Many1(Number()).AsString().SeparatedBy1(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456", "789"));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is("123456"));
var source3 = "abcdEFGH";
parser.Parse(source3).WillFail();
}
[TestMethod]
public void EndByTest()
{
// Creates a parser that matches parser repeated 0 or more times with separator at the end.
// *( 1*Number "," )
var parser = Many1(Number()).AsString().EndBy(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456"));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.IsEmpty());
}
[TestMethod]
public void EndBy1Test()
{
// Creates a parser that matches parser repeated 1 or more times with separator at the end.
// 1*( 1*Number "," )
var parser = Many1(Number()).AsString().EndBy1(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456"));
var source2 = "123456";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void SeparatedOrEndByTest()
{
// Creates a parser that behaves as either `SeparatedBy` or `EndBy`.
// [ 1*Number *( "," 1*Number ) [ "," ] ]
var parser = Many1(Number()).AsString().SeparatedOrEndBy(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456", "789"));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is("123456"));
var source3 = "123,456,789" + ",";
parser.Parse(source3).WillSucceed(value => value.Is("123", "456", "789"));
}
[TestMethod]
public void SeparatedOrEndBy1Test()
{
// Creates a parser that behaves as either `SeparatedBy1` or `EndBy1`.
// 1*Number *( "," 1*Number ) [ "," ]
var parser = Many1(Number()).AsString().SeparatedOrEndBy1(Char(','));
var source = "123,456,789";
parser.Parse(source).WillSucceed(value => value.Is("123", "456", "789"));
var source2 = "123456";
parser.Parse(source2).WillSucceed(value => value.Is("123456"));
var source3 = "123,456,789" + ",";
parser.Parse(source3).WillSucceed(value => value.Is("123", "456", "789"));
}
[TestMethod]
public void ExceptTest()
{
// Creates a parser with exclusion conditions for the specified parser.
var source = "123456";
// Parser that matches digits except '5'.
var parser = Digit().Except(Char('5'));
parser.Parse(source).WillSucceed(value => value.Is('1'));
// Parser that matches digits except '5' consecutively and returns the result as a string.
var parser2 = Many(parser).AsString();
parser2.Parse(source).WillSucceed(value => value.Is("1234"));
}
[TestMethod]
public void ChainTest()
{
// Creates a recursive parser that starts with a single parser, creates the next parser based on the result, and repeats until it fails.
// Parser that matches any character consecutively, and returns the matched character and its count as a result.
var parser = Any().Map(x => (x, count: 1))
.Chain(match => Char(match.x).Map(_ => (match.x, match.count + 1)))
.Map(match => match.x.ToString() + match.count.ToString());
var source = "aaaaaaaaa";
parser.Parse(source).WillSucceed(value => value.Is("a9"));
var source2 = "aaabbbbcccccdddddd";
Many(parser).Join().Parse(source2).WillSucceed(value => value.Is("a3b4c5d6"));
// Originally, it is not possible to directly describe a parser that references itself first
// (because it would result in infinite recursion).
// A famous left-recursive definition of binary operations.
// expr = expr op digit / digit
static IParser<char, int> Expr()
=> (from x in Expr() // Infinite recursion here
from func in Char('+')
from y in Num()
select x + y)
.Or(Num());
static IParser<char, int> Num()
=> Many1(Digit()).ToInt();
// It is possible to transform this definition to remove left recursion.
// Definition of binary operations after removing left recursion.
// expr = digit *( op digit )
static IParser<char, int> Expr2()
=> Num().Chain(x => Char('+').Right(Num()).Map(y => x + y));
// By using `Chain`, you can directly describe the definition after removing left recursion.
Expr2().Parse("1+2+3+4").Value.Is(1 + 2 + 3 + 4);
}
[TestMethod]
public void ChainLeftTest()
{
// Creates a parser that matches 1 or more values and operators alternately, and applies the specified operation from left to right.
// Parser that matches '+' or '-', and returns a binary operation function (x + y) or (x - y).
// ( "+" / "-" )
var op = Choice(
Char('+').Map(_ => (Func<int, int, int>)((x, y) => x + y)),
Char('-').Map(_ => (Func<int, int, int>)((x, y) => x - y)));
// Parser that matches 1 or more digits and converts them to int.
var num = Many1(Digit()).ToInt();
// num *( op num )
var parser = num.ChainLeft(op);
var source = "10+5-3+1";
parser.Parse(source).WillSucceed(value => value.Is(((10 + 5) - 3) + 1));
var source2 = "100-20-5+50";
parser.Parse(source2).WillSucceed(value => value.Is(((100 - 20) - 5) + 50));
var source3 = "123";
parser.Parse(source3).WillSucceed(value => value.Is(123));
var source4 = "abcdEFGH";
parser.Parse(source4).WillFail();
var source5 = "1-2+3+ABCD";
parser.Parse(source5).WillSucceed(value => value.Is((1 - 2) + 3));
parser.Right(Any()).Parse(source5).WillSucceed(value => value.Is('+'));
}
[TestMethod]
public void ChainRightTest()
{
// Creates a parser that matches 1 or more values and operators alternately, and applies the specified operation from right to left.
// Parser that matches '+' or '-', and returns a binary operation function (x + y) or (x - y).
// ( "+" / "-" )
var op = Choice(
Char('+').Map(_ => (Func<int, int, int>)((x, y) => x + y)),
Char('-').Map(_ => (Func<int, int, int>)((x, y) => x - y)));
// Parser that matches 1 or more digits and converts them to int.
var num = Many1(Digit()).ToInt();
// num *( op num )
var parser = num.ChainRight(op);
var source = "10+5-3+1";
parser.Parse(source).WillSucceed(value => value.Is(10 + (5 - (3 + 1))));
var source2 = "100-20-5+50";
parser.Parse(source2).WillSucceed(value => value.Is(100 - (20 - (5 + 50))));
var source3 = "123";
parser.Parse(source3).WillSucceed(value => value.Is(123));
var source4 = "abcdEFGH";
parser.Parse(source4).WillFail();
var source5 = "1-2+3+ABCD";
parser.Parse(source5).WillSucceed(value => value.Is(1 - (2 + 3)));
parser.Right(Any()).Parse(source5).WillSucceed(value => value.Is('+'));
}
[TestMethod]
public void FoldLeftTest()
{
// Takes an initial value and an aggregation function as arguments, and creates a parser that aggregates the parsed results from left to right.
// Parser that matches 0 or more digits, and repeatedly applies (x => accumulator - x) to the initial value 10 from the left.
var parser = Digit().AsString().ToInt().FoldLeft(10, (x, y) => x - y);
var source = "12345";
parser.Parse(source).WillSucceed(value => value.Is(((((10 - 1) - 2) - 3) - 4) - 5));
// Overload that does not use an initial value.
var parser2 = Digit().AsString().ToInt().FoldLeft((x, y) => x - y);
parser2.Parse(source).WillSucceed(value => value.Is((((1 - 2) - 3) - 4) - 5));
}
[TestMethod]
public void FoldRightTest()
{
// Takes an initial value and an aggregation function as arguments, and creates a parser that aggregates the parsed results from right to left.
// Parser that matches 0 or more digits, and repeatedly applies (x => x - accumulator) to the initial value 10 from the right.
var parser = Digit().AsString().ToInt().FoldRight(10, (x, y) => x - y);
var source = "12345";
parser.Parse(source).WillSucceed(value => value.Is(1 - (2 - (3 - (4 - (5 - 10))))));
// Overload that does not use an initial value.
var parser2 = Digit().AsString().ToInt().FoldRight((x, y) => x - y);
parser2.Parse(source).WillSucceed(value => value.Is(1 - (2 - (3 - (4 - 5)))));
}
[TestMethod]
public void RepeatTest()
{
// Creates a parser that matches parser count times and returns the result as a sequence.
// 2*( 3*Any )
var parser = Any().Repeat(3).AsString().Repeat(2);
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is("abc", "dEF"));
}
[TestMethod]
public void LeftTest()
{
// Creates a parser that matches two parsers in sequence and returns the result of left, discarding the result of right.
// Parser that matches ( "a" "b" ) and returns 'a'.
var parser = Char('a').Left(Char('b'));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('a'));
var source2 = "a";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void RightTest()
{
// Creates a parser that matches two parsers in sequence and returns the result of right, discarding the result of left.
// Parser that matches ( "a" "b" ) and returns 'b'.
var parser = Char('a').Right(Char('b'));
var source = "abcdEFGH";
parser.Parse(source).WillSucceed(value => value.Is('b'));
var source2 = "b";
parser.Parse(source2).WillFail();
}
[TestMethod]
public void BetweenTest()
{
// Creates a parser that matches parser enclosed by open and close.
// The results of open and close are discarded, and only the result of the middle parser is returned.
// Parser that matches 1 or more letters enclosed in "[]".
// ( "[" 1*Letter "]" )
var parser = Many1(Letter()).Between(Char('['), Char(']'));
var source = $"[{"abcdEFGH"}]";