-
Notifications
You must be signed in to change notification settings - Fork 53
/
Parser.scala
2950 lines (2606 loc) · 99.3 KB
/
Parser.scala
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
/*
* Copyright (c) 2021 Typelevel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package cats.parse
import cats.{Eval, FunctorFilter, Monad, Defer, Alternative, FlatMap, Now, MonoidK, Order}
import cats.data.{AndThen, Chain, NonEmptyList}
import cats.implicits._
import scala.collection.immutable.SortedSet
import scala.collection.mutable.ListBuffer
import java.util.Arrays
/** Parser0[A] attempts to extract an `A` value from the given input,
* potentially moving its offset forward in the process.
*
* When calling `parse`, one of three outcomes occurs:
*
* - Success: The parser consumes zero-or-more characters of input
* and successfully extracts a value. The input offset will be
* moved forward by the number of characters consumed.
*
* - Epsilon failure: The parser fails to extract a value without
* consuming any characters of input. The input offset will not be
* changed.
*
* - Arresting failure: The parser fails to extract a value but does
* consume one-or-more characters of input. The input offset will
* be moved forward by the number of characters consumed and all
* parsing will stop (unless a higher-level parser backtracks).
*
* Operations such as `x.orElse(y)` will only consider parser `y` if
* `x` returns an epsilon failure; these methods cannot recover from
* an arresting failure. Arresting failures can be "rewound" using
* methods such as `x.backtrack` (which converts arresting failures
* from `x` into epsilon failures), or `softProduct(x, y)` (which can
* rewind successful parses by `x` that are followed by epsilon
* failures for `y`).
*
* Rewinding tends to make error reporting more difficult and can lead
* to exponential parser behavior it is not the default behavior.
*/
sealed abstract class Parser0[+A] { self: Product =>
/** Attempt to parse an `A` value out of `str`.
*
* This method will either return a failure, or else the remaining
* string and the parsed value.
*
* To require the entire input to be consumed, see `parseAll`.
*/
final def parse(str: String): Either[Parser.Error, (String, A)] = {
val state = new Parser.State(str)
val result = parseMut(state)
val err = state.error
val offset = state.offset
if (err eq null) Right((str.substring(offset), result))
else
Left(Parser.Error(offset, Parser.Expectation.unify(NonEmptyList.fromListUnsafe(err.toList))))
}
/** Attempt to parse all of the input `str` into an `A` value.
*
* This method will return a failure unless all of `str` is consumed
* during parsing.
*
* `p.parseAll(s)` is equivalent to `(p <* Parser.end).parse(s).map(_._2)`.
*/
final def parseAll(str: String): Either[Parser.Error, A] = {
val state = new Parser.State(str)
val result = parseMut(state)
val err = state.error
val offset = state.offset
if (err eq null) {
if (offset == str.length) Right(result)
else
Left(
Parser.Error(
offset,
NonEmptyList(Parser.Expectation.EndOfString(offset, str.length), Nil)
)
)
} else
Left(Parser.Error(offset, Parser.Expectation.unify(NonEmptyList.fromListUnsafe(err.toList))))
}
/** Convert epsilon failures into None values.
*
* Normally if a parser fails to consume any input it fails with an
* epsilon failure. The `?` method converts these failures into
* None values (and wraps other values in `Some(_)`).
*
* If the underlying parser failed with other errors, this parser
* will still fail.
*/
def ? : Parser0[Option[A]] =
Parser.oneOf0(Parser.map0(this)(Some(_)) :: Parser.optTail)
/** If this parser fails to parse its input with an epsilon error,
* try the given parser instead.
*
* If this parser fails with an arresting error, the next parser
* won't be tried.
*
* Backtracking may be used on the left parser to allow the right
* one to pick up after any error, resetting any state that was
* modified by the left parser.
*
* This method is similar to Parser#orElse but returns Either.
*/
def eitherOr[B](pb: Parser0[B]): Parser0[Either[B, A]] =
Parser.eitherOr0(this, pb)
/** Parse without capturing values.
*
* Calling `void` on a parser can be a significant optimization --
* it allows the parser to avoid allocating results to return.
*
* Other methods like `as`, `*>`, and `<*` use `void` internally to
* discard allocations, since they will ignore the original parsed
* result.
*/
def void: Parser0[Unit] =
Parser.void0(this)
/** Return the string matched by this parser.
*
* When parsing an input string that the underlying parser matches,
* this parser will return the matched substring instead of any
* value that the underlying parser would have returned. It will
* still match exactly the same inputs as the original parser.
*
* This method is very efficient: similarly to `void`, we can avoid
* allocating results to return.
*/
def string: Parser0[String] =
Parser.string0(this)
/** If this parser fails to match, rewind the offset to the starting
* point before moving on to other parser.
*
* This method converts arresting failures into epsilon failures,
* which includes rewinding the offset to that used before parsing
* began.
*
* This method will most often be used before calling methods such
* as `orElse`, `~`, or `flatMap` which involve a subsequent parser
* picking up where this one left off.
*/
def backtrack: Parser0[A] =
Parser.backtrack0(this)
/** Sequence another parser after this one, combining both results
* into a tuple.
*
* This combinator returns a product of parsers. If this parser
* successfully produces an `A` value, the other parser is run on
* the remaining input to try to produce a `B` value.
*
* If either parser produces an error the result is an error.
* Otherwise both extracted values are combined into a tuple.
*/
def ~[B](that: Parser0[B]): Parser0[(A, B)] =
Parser.product0(this, that)
/** Compose two parsers, ignoring the values extracted by the
* left-hand parser.
*
* `x *> y` is equivalent to `(x.void ~ y).map(_._2)`.
*/
def *>[B](that: Parser0[B]): Parser0[B] =
(void ~ that).map(_._2)
/** Compose two parsers, ignoring the values extracted by the
* right-hand parser.
*
* `x <* y` is equivalent to `(x ~ y.void).map(_._1)`.
*/
def <*[B](that: Parser0[B]): Parser0[A] =
(this ~ that.void).map(_._1)
/** If this parser fails to parse its input with an epsilon error,
* try the given parser instead.
*
* If this parser fails with an arresting error, the next parser
* won't be tried.
*
* Backtracking may be used on the left parser to allow the right
* one to pick up after any error, resetting any state that was
* modified by the left parser.
*/
def orElse[A1 >: A](that: Parser0[A1]): Parser0[A1] =
Parser.oneOf0(this :: that :: Nil)
/** Synonym for orElse
* Note this is not commutative: if this has an arresting failure we
* do not continue onto the next.
*/
def |[A1 >: A](that: Parser0[A1]): Parser0[A1] =
orElse(that)
/** Transform parsed values using the given function.
*
* This parser will match the same inputs as the underlying parser,
* using the given function `f` to transform the values the
* underlying parser produces.
*
* If the underlying value is ignored (e.g. `map(_ => ...)`) calling
* `void` before `map` will improve the efficiency of the parser.
*/
def map[B](fn: A => B): Parser0[B] =
Parser.map0(this)(fn)
/** Transform parsed values using the given function, or fail on None
*
* When the function return None, this parser fails
* This is implemented with select, which makes it more efficient
* than using flatMap
*/
def mapFilter[B](fn: A => Option[B]): Parser0[B] = {
val leftUnit = Left(())
val first = map { a =>
fn(a) match {
case Some(b) => Right(b)
case None => leftUnit
}
}
Parser.select0(first)(Parser.Fail)
}
/** Transform parsed values using the given function, or fail when not defined
*
* When the function is not defined, this parser fails
* This is implemented with select, which makes it more efficient
* than using flatMap
*/
def collect[B](fn: PartialFunction[A, B]): Parser0[B] =
mapFilter(fn.lift)
/** If the predicate is not true, fail
* you may want .filter(fn).backtrack so if the filter fn
* fails you can fall through in an oneOf0 or orElse
*
* Without the backtrack, a failure of the function will
* be an arresting failure.
*/
def filter(fn: A => Boolean): Parser0[A] = {
val leftUnit = Left(())
Parser.select0(this.map { a =>
if (fn(a)) Right(a)
else leftUnit
})(Parser.Fail)
}
/** Dynamically construct the next parser based on the previously
* parsed value.
*
* Using `flatMap` is very expensive. When possible, you should
* prefer to use methods such as `~`, `*>`, or `<*` when possible,
* since these are much more efficient.
*/
def flatMap[B](fn: A => Parser0[B]): Parser0[B] =
Parser.flatMap0(this)(fn)
/** Replaces parsed values with the given value.
*/
def as[B](b: B): Parser0[B] =
Parser.as0(this, b)
/** Wrap this parser in a helper class, enabling better composition
* with `Parser` values.
*
* For example, with `p: Parser0[Int]` and `p1: Parser0[Double]`:
*
* val a1: Parser0[(Int, Double)] = p ~ p1
* val a2: Parser[(Int, Double)] = p.with1 ~ p1
*
* val b1: Parser0[Double] = p *> p1
* val b2: Parser[Double] = p.with1 *> p1
*
* val c1: Parser0[Int] = p <* p1
* val c2: Parser[Int] = p.with1 <* p1
*
* Without using `with1`, these methods will return `Parser0` values
* since they are not known to return `Parser` values instead.
*/
def with1: Parser.With1[A] =
new Parser.With1(this)
/** Wrap this parser in a helper class, to enable backtracking during
* composition.
*
* This wrapper changes the behavior of `~`, `<*` and `*>`. Normally
* no backtracking occurs. Using `soft` on the left-hand side will
* enable backtracking if the right-hand side returns an epsilon
* failure (but not in any other case).
*
* For example, `(x ~ y)` will never backtrack. But with `(x.soft ~
* y)`, if `x` parses successfully, and `y` returns an epsilon
* failure, the parser will "rewind" to the point before `x` began.
*/
def soft: Parser.Soft0[A] =
new Parser.Soft0(this)
/** Return a parser that succeeds (consuming nothing, and extracting
* nothing) if the current parser would fail.
*
* This parser expects the underlying parser to fail, and will
* unconditionally backtrack after running it.
*/
def unary_! : Parser0[Unit] =
Parser.not(this)
/** Return a parser that succeeds (consuming nothing and extracting
* nothing) if the current parser would also succeed.
*
* This parser expects the underlying parser to succeed, and will
* unconditionally backtrack after running it.
*/
def peek: Parser0[Unit] =
Parser.peek(this)
/** Use this parser to parse between values.
*
* Parses `b` followed by `this` and `c`.
* Returns only the values extracted by `this` parser.
*/
def between(b: Parser0[Any], c: Parser0[Any]): Parser0[A] =
(b.void ~ (this ~ c.void)).map { case (_, (a, _)) => a }
/** Use this parser to parse surrounded by values.
*
* This is the same as `between(b, b)`
*/
def surroundedBy(b: Parser0[Any]): Parser0[A] =
between(b, b)
/** Add a string context to any Errors on parsing
* this is useful for debugging failing parsers.
*/
def withContext(str: String): Parser0[A] =
Parser.withContext0(this, str)
/** Internal (mutable) parsing method.
*
* This method should only be called internally by parser instances.
*/
private[parse] def parseMut(state: Parser.State): A
/** This method overrides `Object#hashCode` to cache its result for performance reasons.
*/
override lazy val hashCode: Int = scala.runtime.ScalaRunTime._hashCode(this)
}
/** Parser[A] is a Parser0[A] that will always consume one-or-more
* characters on a successful parse.
*
* Since Parser is guaranteed to consume input it provides additional
* methods which would be unsafe when used on parsers that succeed
* without consuming input, such as `rep0`.
*
* When a Parser is composed with a Parser0 the result is usually a
* Parser. Parser overrides many of Parser0's methods to refine the
* return type. In other cases, callers may need to use the `with1`
* helper method to refine the type of their expressions.
*
* Parser doesn't provide any additional guarantees over Parser0 on
* what kind of parsing failures it can return.
*/
sealed abstract class Parser[+A] extends Parser0[A] { self: Product =>
/** This method overrides `Parser0#filter` to refine the return type.
*/
override def filter(fn: A => Boolean): Parser[A] = {
val leftUnit = Left(())
Parser.select(this.map { a =>
if (fn(a)) Right(a)
else leftUnit
})(Parser.Fail)
}
/** This method overrides `Parser0#void` to refine the return type.
*/
override def void: Parser[Unit] =
Parser.void(this)
/** This method overrides `Parser0#string` to refine the return type.
*/
override def string: Parser[String] =
Parser.string(this)
/** This method overrides `Parser0#backtrack` to refine the return type.
*/
override def backtrack: Parser[A] =
Parser.backtrack(this)
/** a version of eitherOr when both sides are not Parser0
*/
def eitherOr[B](pb: Parser[B]): Parser[Either[B, A]] =
Parser.eitherOr(this, pb)
/** This method overrides `Parser0#~` to refine the return type.
*/
override def ~[B](that: Parser0[B]): Parser[(A, B)] =
Parser.product10(this, that)
/** This method overrides `Parser0#*>` to refine the return type.
*/
override def *>[B](that: Parser0[B]): Parser[B] =
(void ~ that).map(_._2)
/** This method overrides `Parser0#<*` to refine the return type.
*/
override def <*[B](that: Parser0[B]): Parser[A] =
(this ~ that.void).map(_._1)
/** This method overrides `Parser0#collect` to refine the return type.
*/
override def collect[B](fn: PartialFunction[A, B]): Parser[B] =
mapFilter(fn.lift)
/** This method overrides `Parser0#map` to refine the return type.
*/
override def map[B](fn: A => B): Parser[B] =
Parser.map(this)(fn)
/** This method overrides `Parser0#mapFilter` to refine the return type.
*/
override def mapFilter[B](fn: A => Option[B]): Parser[B] = {
val leftUnit = Left(())
val first = map { a =>
fn(a) match {
case Some(b) => Right(b)
case None => leftUnit
}
}
Parser.select(first)(Parser.Fail)
}
/** This method overrides `Parser0#flatMap` to refine the return type.
*/
override def flatMap[B](fn: A => Parser0[B]): Parser[B] =
Parser.flatMap10(this)(fn)
/** This method overrides `Parser0#as` to refine the return type.
*/
override def as[B](b: B): Parser[B] =
Parser.as(this, b)
/** If this parser fails to parse its input with an epsilon error,
* try the given parser instead.
*
* This method is similar to Parser0#orElse, but since both arguments
* are known to be Parser values, the result is known to be a
* Parser as well.
*/
def orElse[A1 >: A](that: Parser[A1]): Parser[A1] =
Parser.oneOf(this :: that :: Nil)
/** Synonym for orElse
* Note this is not commutative: if this has an arresting failure we
* do not continue onto the next.
*/
def |[A1 >: A](that: Parser[A1]): Parser[A1] =
orElse(that)
/** Use this parser to parse zero-or-more values.
*
* This parser may succeed without consuming input in the case where
* zero values are parsed.
*
* If the underlying parser hits an arresting failure, the entire
* parse is also an arresting failure. If the underlying parser hits
* an epsilon failure, the parsed values (if any) are returned in a
* list as a successful parse.
*/
def rep0: Parser0[List[A]] = repAs0
/** Use this parser to parse at least `min` values (where `min >= 0`).
*
* If `min` is zero, this parser may succeed without consuming
* input in the case where zero values are parsed. If `min` is
* known to be greater than zero, consider using `rep(min)`
* instead.
*
* Like `rep0`, arresting failures in the underlying parser will
* result in an arresting failure. Unlike `rep0`, this method may
* also return an arresting failure if it has not parsed at least
* `min` values (but has consumed input).
*/
def rep0(min: Int): Parser0[List[A]] =
if (min == 0) rep0
else repAs(min)
/** Repeat the parser `min` or more times, but no more than `max`
*
* The parser fails if it can't match at least `min` times
* After repeating the parser `max` times, the parser completes successfully
*
* @throws java.lang.IllegalArgumentException if min < 0 or max < min
*/
def rep0(min: Int, max: Int): Parser0[List[A]] =
if (min == 0) repAs0(max)
else repAs(min, max)
/** Use this parser to parse one-or-more values.
*
* This parser behaves like `rep0`, except that it must produce at
* least one value, and is guaranteed to consume input on successful
* parses.
*/
def rep: Parser[NonEmptyList[A]] = repAs
/** Use this parser to parse at least `min` values (where `min >= 1`).
*
* This method behaves likes `rep`, except that if fewer than `min`
* values are produced an arresting failure will be returned.
*/
def rep(min: Int): Parser[NonEmptyList[A]] =
repAs(min = min)
/** Repeat the parser `min` or more times, but no more than `max`
*
* The parser fails if it can't match at least `min` times
* After repeating the parser `max` times, the parser completes successfully
*
* @throws java.lang.IllegalArgumentException if min < 1 or max < min
*/
def rep(min: Int, max: Int): Parser[NonEmptyList[A]] =
repAs(min = min, max = max)
/** Repeat the parser 0 or more times
*
* @note this can wind up parsing nothing
*/
def repAs0[B](implicit acc: Accumulator0[A, B]): Parser0[B] =
Parser.repAs0(this)(acc)
/** Repeat the parser 0 or more times, but no more than `max`
*
* It may seem weird to accept 0 here, but without, composing
* this method becomes more complex.
* Since and empty parse is possible for this method, we do
* allow max = 0
*
* @throws java.lang.IllegalArgumentException if max < 0
*
* @note this can wind up parsing nothing
*/
def repAs0[B](max: Int)(implicit acc: Accumulator0[A, B]): Parser0[B] =
Parser.repAs0(this, max = max)(acc)
/** Repeat the parser 1 or more times
*/
def repAs[B](implicit acc: Accumulator[A, B]): Parser[B] =
repAs(min = 1)
/** Repeat the parser `min` or more times
*
* The parser fails if it can't match at least `min` times
*
* @throws java.lang.IllegalArgumentException if min < 1
*/
def repAs[B](min: Int)(implicit acc: Accumulator[A, B]): Parser[B] =
Parser.repAs(this, min = min)(acc)
/** Repeat the parser `min` or more times, but no more than `max`
*
* The parser fails if it can't match at least `min` times
* After repeating the parser `max` times, the parser completes successfully
*
* @throws java.lang.IllegalArgumentException if min < 1 or max < min
*/
def repAs[B](min: Int, max: Int)(implicit acc: Accumulator[A, B]): Parser[B] =
Parser.repAs(this, min = min, max = max)(acc)
/** Repeat the parser exactly `times` times
*
* @throws java.lang.IllegalArgumentException if times < 1
*/
def repExactlyAs[B](times: Int)(implicit acc: Accumulator[A, B]): Parser[B] =
Parser.repExactlyAs(this, times = times)(acc)
/** Repeat 0 or more times with a separator
*/
def repSep0(sep: Parser0[Any]): Parser0[List[A]] =
Parser.repSep0(this, sep)
/** Repeat `min` or more times with a separator.
*
* @throws java.lang.IllegalArgumentException if `min < 0`
*/
def repSep0(min: Int, sep: Parser0[Any]): Parser0[List[A]] =
Parser.repSep0(this, min = min, sep = sep)
/** Repeat `min` or more, up to `max` times with a separator.
*
* @throws java.lang.IllegalArgumentException if `min < 0` or `max < min`
*/
def repSep0(min: Int, max: Int, sep: Parser0[Any]): Parser0[List[A]] =
Parser.repSep0(this, min = min, max = max, sep = sep)
/** Repeat 1 or more times with a separator
*/
def repSep(sep: Parser0[Any]): Parser[NonEmptyList[A]] =
Parser.repSep(this, sep)
/** Repeat `min` or more times with a separator, at least once.
*
* @throws java.lang.IllegalArgumentException if `min <= 0`
*/
def repSep(min: Int, sep: Parser0[Any]): Parser[NonEmptyList[A]] =
Parser.repSep(this, min = min, sep = sep)
/** Repeat `min` or more, up to `max` times with a separator, at least once.
*
* @throws java.lang.IllegalArgumentException if `min <= 0` or `max < min`
*/
def repSep(min: Int, max: Int, sep: Parser0[Any]): Parser[NonEmptyList[A]] =
Parser.repSep(this, min = min, max = max, sep = sep)
/** Repeat this parser 0 or more times until `end` Parser succeeds.
*/
def repUntil0(end: Parser0[Any]): Parser0[List[A]] =
Parser.repUntil0(this, end)
/** Repeat this parser 1 or more times until `end` Parser succeeds.
*/
def repUntil(end: Parser0[Any]): Parser[NonEmptyList[A]] =
Parser.repUntil(this, end)
/** Repeat this parser 0 or more times until `end` Parser succeeds.
*/
def repUntilAs0[B](end: Parser0[Any])(implicit acc: Accumulator0[A, B]): Parser0[B] =
Parser.repUntilAs0(this, end)
/** Repeat this parser 1 or more times until `end` Parser succeeds.
*/
def repUntilAs[B](end: Parser0[Any])(implicit acc: Accumulator[A, B]): Parser[B] =
Parser.repUntilAs(this, end)
/** This method overrides `Parser0#between` to refine the return type
*/
override def between(b: Parser0[Any], c: Parser0[Any]): Parser[A] =
(b.void.with1 ~ (this ~ c.void)).map { case (_, (a, _)) => a }
/** This method overrides `Parser0#surroundedBy` to refine the return type
*/
override def surroundedBy(b: Parser0[Any]): Parser[A] =
between(b, b)
/** This method overrides `Parser0#soft` to refine the return type.
*/
override def soft: Parser.Soft[A] =
new Parser.Soft(this)
/** This method overrides `Parser0#withContext` to refine the return type.
* add a string context to any Errors on parsing
* this is useful for debugging failing parsers.
*/
override def withContext(str: String): Parser[A] =
Parser.withContext(this, str)
}
object Parser {
/** An expectation reports the kind or parsing error
* and where it occured.
*/
sealed abstract class Expectation {
def offset: Int
/** This is a reverse order stack (most recent context first)
* of this parsing error
*/
def context: List[String] =
this match {
case Expectation.WithContext(ctx, inner) =>
ctx :: inner.context
case _ => Nil
}
}
object Expectation {
case class OneOfStr(offset: Int, strs: List[String]) extends Expectation
// expected a character in a given range
case class InRange(offset: Int, lower: Char, upper: Char) extends Expectation
case class StartOfString(offset: Int) extends Expectation
case class EndOfString(offset: Int, length: Int) extends Expectation
case class Length(offset: Int, expected: Int, actual: Int) extends Expectation
case class ExpectedFailureAt(offset: Int, matched: String) extends Expectation
// this is the result of oneOf0(Nil) at a given location
case class Fail(offset: Int) extends Expectation
case class FailWith(offset: Int, message: String) extends Expectation
case class WithContext(contextStr: String, expect: Expectation) extends Expectation {
def offset: Int = expect.offset
}
implicit val catsOrderExpectation: Order[Expectation] =
new Order[Expectation] {
override def compare(left: Expectation, right: Expectation): Int = {
val c = Integer.compare(left.offset, right.offset)
if (c != 0) c
else if (left == right) 0
else {
// these are never equal
(left, right) match {
case (OneOfStr(_, s1), OneOfStr(_, s2)) => s1.compare(s2)
case (OneOfStr(_, _), _) => -1
case (InRange(_, _, _), OneOfStr(_, _)) => 1
case (InRange(_, l1, u1), InRange(_, l2, u2)) =>
val c1 = Character.compare(l1, l2)
if (c1 == 0) Character.compare(u1, u2)
else c1
case (InRange(_, _, _), _) => -1
case (StartOfString(_), OneOfStr(_, _) | InRange(_, _, _)) => 1
case (StartOfString(_), _) =>
-1 // if they have the same offset, already handled above
case (
EndOfString(_, _),
OneOfStr(_, _) | InRange(_, _, _) | StartOfString(_)
) =>
1
case (EndOfString(_, l1), EndOfString(_, l2)) =>
Integer.compare(l1, l2)
case (EndOfString(_, _), _) => -1
case (
Length(_, _, _),
OneOfStr(_, _) | InRange(_, _, _) | StartOfString(_) | EndOfString(_, _)
) =>
1
case (Length(_, e1, a1), Length(_, e2, a2)) =>
val c1 = Integer.compare(e1, e2)
if (c1 == 0) Integer.compare(a1, a2)
else c1
case (Length(_, _, _), _) => -1
case (ExpectedFailureAt(_, _), Fail(_) | FailWith(_, _) | WithContext(_, _)) => -1
case (ExpectedFailureAt(_, m1), ExpectedFailureAt(_, m2)) =>
m1.compare(m2)
case (ExpectedFailureAt(_, _), _) => 1
case (Fail(_), FailWith(_, _) | WithContext(_, _)) => -1
case (Fail(_), _) => 1
case (FailWith(_, _), WithContext(_, _)) => -1
case (FailWith(_, s1), FailWith(_, s2)) =>
s1.compare(s2)
case (FailWith(_, _), _) => 1
case (WithContext(lctx, lexp), WithContext(rctx, rexp)) =>
val c = compare(lexp, rexp)
if (c != 0) c
else lctx.compareTo(rctx)
case (WithContext(_, _), _) => 1
}
}
}
}
private def mergeInRange(irs: List[InRange]): List[InRange] = {
@annotation.tailrec
def merge(rs: List[InRange], aux: Chain[InRange] = Chain.empty): Chain[InRange] =
rs match {
case x :: y :: rest =>
if (y.lower.toInt > x.upper.toInt + 1) merge(y :: rest, aux :+ x)
else merge(InRange(x.offset, x.lower, x.upper max y.upper) :: rest, aux)
case _ =>
aux ++ Chain.fromSeq(rs.reverse)
}
merge(irs.sortBy(_.lower)).toList
}
private def mergeOneOfStr(ooss: List[OneOfStr]): Option[OneOfStr] =
if (ooss.isEmpty) None
else {
val ssb = SortedSet.newBuilder[String]
ooss.foreach(ssb ++= _.strs)
Some(OneOfStr(ooss.head.offset, ssb.result().toList))
}
@annotation.tailrec
private def stripContext(ex: Expectation): Expectation =
ex match {
case WithContext(_, inner) => stripContext(inner)
case _ => ex
}
@annotation.tailrec
private def addContext(revCtx: List[String], ex: Expectation): Expectation =
revCtx match {
case Nil => ex
case h :: tail => addContext(tail, WithContext(h, ex))
}
/** Sort, dedup and unify ranges for the errors accumulated
* This is called just before finally returning an error in Parser.parse
*/
def unify(errors: NonEmptyList[Expectation]): NonEmptyList[Expectation] = {
val result = errors
.groupBy { ex => (ex.offset, ex.context) }
.iterator
.flatMap { case ((_, ctx), list) =>
val rm = ListBuffer.empty[InRange]
val om = ListBuffer.empty[OneOfStr]
val fails = ListBuffer.empty[Fail]
val others = ListBuffer.empty[Expectation]
var items = list.toList
while (items.nonEmpty) {
stripContext(items.head) match {
case ir: InRange => rm += ir
case os: OneOfStr => om += os
case fail: Fail => fails += fail
case other => others += other
}
items = items.tail
}
// merge all the ranges:
val rangeMerge = mergeInRange(rm.toList)
// merge the OneOfStr
val oossMerge = mergeOneOfStr(om.toList)
val errors = others.toList reverse_::: (oossMerge ++: rangeMerge)
val finals = if (errors.isEmpty) fails.toList else errors
if (ctx.nonEmpty) {
val revCtx = ctx.reverse
finals.map(addContext(revCtx, _))
} else finals
}
.toList
NonEmptyList.fromListUnsafe(result.distinct.sorted)
}
}
/** Represents where a failure occurred and all the expectations that were broken
*/
final case class Error(failedAtOffset: Int, expected: NonEmptyList[Expectation]) {
def offsets: NonEmptyList[Int] =
expected.map(_.offset).distinct
}
/** Enables syntax to access product01, product and flatMap01
* This helps us build Parser instances when starting from
* a Parser0
*/
final class With1[+A](val parser: Parser0[A]) extends AnyVal {
/** parser then that.
* Since that is a Parser the result is
*/
def ~[B](that: Parser[B]): Parser[(A, B)] =
Parser.product01(parser, that)
/** This is the usual monadic composition, but you
* should much prefer to use ~ or Apply.product, *>, <*, etc
* if you can since it is much more efficient. This
* has to call fn on each parse, which could be a lot
* of extra work is you already know the result as is
* the case for ~
*/
def flatMap[B](fn: A => Parser[B]): Parser[B] =
Parser.flatMap01(parser)(fn)
/** parser then that.
* Since that is a Parser the result is
*/
def *>[B](that: Parser[B]): Parser[B] =
product01(void0(parser), that).map(_._2)
/** parser then that.
* Since that is a Parser the result is
*/
def <*[B](that: Parser[B]): Parser[A] =
product01(parser, void(that)).map(_._1)
/** If we can parse this then that, do so,
* if we fail that without consuming, rewind
* before this without consuming.
* If either consume 1 or more, do not rewind
*/
def soft: Soft01[A] =
new Soft01(parser)
/** parse between values.
* Since values are `Parser` the result is
*/
def between(b: Parser[Any], c: Parser[Any]): Parser[A] =
(b.void ~ (parser ~ c.void)).map { case (_, (a, _)) => a }
/** parse surrounded by that.
* Since that is a Parser the result is
*/
def surroundedBy(that: Parser[Any]): Parser[A] =
between(that, that)
}
/** If we can parse this then that, do so,
* if we fail that without consuming, rewind
* before this without consuming.
* If either consume 1 or more, do not rewind
*/
sealed class Soft0[+A](parser: Parser0[A]) {
def ~[B](that: Parser0[B]): Parser0[(A, B)] =
softProduct0(parser, that)
def *>[B](that: Parser0[B]): Parser0[B] =
softProduct0(void0(parser), that).map(_._2)
def <*[B](that: Parser0[B]): Parser0[A] =
softProduct0(parser, void0(that)).map(_._1)
/** If we can parse this then that, do so,
* if we fail that without consuming, rewind
* before this without consuming.
* If either consume 1 or more, do not rewind
*/
def with1: Soft01[A] =
new Soft01(parser)
}
/** If we can parse this then that, do so,
* if we fail that without consuming, rewind
* before this without consuming.
* If either consume 1 or more, do not rewind
*/
final class Soft[+A](parser: Parser[A]) extends Soft0(parser) {
override def ~[B](that: Parser0[B]): Parser[(A, B)] =
softProduct10(parser, that)
override def *>[B](that: Parser0[B]): Parser[B] =
softProduct10(void(parser), that).map(_._2)
override def <*[B](that: Parser0[B]): Parser[A] =
softProduct10(parser, void0(that)).map(_._1)
}
/** If we can parse this then that, do so,
* if we fail that without consuming, rewind
* before this without consuming.
* If either consume 1 or more, do not rewind
*/
final class Soft01[+A](val parser: Parser0[A]) extends AnyVal {
def ~[B](that: Parser[B]): Parser[(A, B)] =
softProduct01(parser, that)
def *>[B](that: Parser[B]): Parser[B] =
softProduct01(void0(parser), that).map(_._2)
def <*[B](that: Parser[B]): Parser[A] =
softProduct01(parser, void(that)).map(_._1)
}
/** Don't advance in the parsed string, just return a
* This is used by the Applicative typeclass.
*/
def pure[A](a: A): Parser0[A] =
Impl.Pure(a)
/** Parse a given string, in a case-insensitive manner,
* or fail. This backtracks on failure
* this is an error if the string is empty
*/
def ignoreCase(str: String): Parser[Unit] =
if (str.length == 1) {
ignoreCaseChar(str.charAt(0))
} else Impl.IgnoreCase(str.toLowerCase)
/** Ignore the case of a single character
* If you want to know if it is upper or
* lower, use .string to capture the string
* and then map to process the result.
*/
def ignoreCaseChar(c: Char): Parser[Unit] =
charIn(c.toLower, c.toUpper).void
/** Parse a given string or
* fail. This backtracks on failure
* this is an error if the string is empty
*/
def string(str: String): Parser[Unit] =
if (str.length == 1) char(str.charAt(0))