-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathParser.scala
More file actions
1414 lines (1208 loc) · 43.5 KB
/
Parser.scala
File metadata and controls
1414 lines (1208 loc) · 43.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.bykn.bosatsu.parser
import cats.{Eval, Monad, Defer, Alternative, FlatMap, Now, MonoidK, Order}
import cats.data.{Chain, NonEmptyList}
import cats.implicits._
/**
* Following the haskell library trifecta,
* these parsers either parse successfully, parse 0 and fail,
* or parse more than 1 and fail. The "or" operation
* only works for parsing 0 and failing.
*
* We call a failure without parsing anything an epsilon failure.
*
* We can convert a failure after parsing more than one
* to a zero parse with .backtrack. Related to backtracking
* is softProduct, which if the second failure is an espilon
* failure, yields an epsilon failure for the product.
*
* Parses 0 or more characters to return A
*/
sealed abstract class Parser[+A] {
final def parse(str: String): Either[Parser.Error, (String, A)] = {
val state = new Parser.Impl.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))))
}
/**
* Parse all or fail
* same as (this <* Parser.end).map(_._2)
*/
final def parseAll(str: String): Either[Parser.Error, A] = {
val state = new Parser.Impl.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))))
}
/**
* If this returns an epsilon failure, change to success with
* a value of None, else Some for the parsed value
*/
def ? : Parser[Option[A]] =
Parser.oneOf(Parser.map(this)(Some(_)) :: Parser.Impl.optTail)
/**
* Don't capture anything, just do the parsing
* This can be a significant optimization in that
* it removes internal allocations as much as possible.
*
* see also Functor.as(a) which is .void.map(_ => a)
* or a *> b and a <* b which use void to remove allocations
* for the side that is discarded.
*/
def void: Parser[Unit] =
Parser.void(this)
/**
* Discard the value and get the substring that this parser
* matches
*/
def string: Parser[String] =
Parser.string(this)
/**
* If this fails, rewind the offset to the starting point
* so we can be used with oneOf
*/
def backtrack: Parser[A] =
Parser.backtrack(this)
def ~[B](that: Parser[B]): Parser[(A, B)] =
Parser.product(this, that)
/**
* If this parser fails without consuming any input,
* moving on to that. See backtrack to make any failure
* rewind and not consume input
*/
def orElse[A1 >: A](that: Parser[A1]): Parser[A1] =
Parser.oneOf(this :: that :: Nil)
def map[B](fn: A => B): Parser[B] =
Parser.map(this)(fn)
/**
* 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.flatMap(this)(fn)
/**
* Allows us to compose with Parser1 using ~ or flatMap
* to create a Parser1 (which is needed for .rep, for instance)
*/
def with1: Parser.With1[A] =
new Parser.With1(this)
/**
* 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: Parser.Soft[A] =
new Parser.Soft(this)
/**
* A parser that succeeds consuming nothing if this
* current parser would fail
*/
def unary_! : Parser[Unit] =
Parser.not(this)
/**
* Convert this parser to one
* that rewinds on success
*/
def peek: Parser[Unit] =
Parser.peek(this)
protected def parseMut(state: Parser.Impl.State): A
}
/**
* Parses 1 or more characters if it succeeds to return A
*/
sealed abstract class Parser1[+A] extends Parser[A] {
override def void: Parser1[Unit] =
Parser.void1(this)
override def string: Parser1[String] =
Parser.string1(this)
/**
* If this fails, rewind the offset to the starting point
* so we can be used with oneOf
*/
override def backtrack: Parser1[A] =
Parser.backtrack1(this)
override def ~[B](that: Parser[B]): Parser1[(A, B)] =
Parser.product10(this, that)
def *>[B](that: Parser[B]): Parser1[B] =
(void ~ that).map(_._2)
def <*[B](that: Parser[B]): Parser1[A] =
(this ~ that.void).map(_._1)
override def map[B](fn: A => B): Parser1[B] =
Parser.map1(this)(fn)
/**
* 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 ~
*/
override def flatMap[B](fn: A => Parser[B]): Parser1[B] =
Parser.flatMap10(this)(fn)
/**
* If this parser fails without consuming any input,
* moving on to that. See backtrack to make any failure
* rewind and not consume input
*/
def orElse1[A1 >: A](that: Parser1[A1]): Parser1[A1] =
Parser.oneOf1(this :: that :: Nil)
/**
* Repeat zero or more times
*/
def rep: Parser[List[A]] =
Parser.rep(this)
/**
* Repeat min, with min >= 0, or more times
*/
def rep(min: Int): Parser[List[A]] =
if (min == 0) rep
else rep1(min).map(_.toList)
/**
* Repeat one or more times
*/
def rep1: Parser1[NonEmptyList[A]] =
Parser.rep1(this, min = 1)
/**
* Repeat min, with min >= 1, or more times
*/
def rep1(min: Int): Parser1[NonEmptyList[A]] =
Parser.rep1(this, min = min)
/**
* 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
*/
override def soft: Parser.Soft1[A] =
new Parser.Soft1(this)
}
object Parser extends ParserInstances {
sealed abstract class Expectation {
def offset: Int
}
object Expectation {
case class Str(offset: Int, str: 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 oneOf(Nil) at a given location
case class Fail(offset: Int) extends Expectation
implicit val catsOrderExpectation: Order[Expectation] =
new Order[Expectation] {
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 (Str(_, s1), Str(_, s2)) => s1.compare(s2)
case (Str(_, _), _) => -1
case (InRange(_, _, _), Str(_, _)) => 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(_), Str(_, _) | InRange(_, _, _)) => 1
case (StartOfString(_), _) => -1 // if they have the same offset, already handled above
case (EndOfString(_, _), Str(_, _) | InRange(_, _, _) | StartOfString(_)) => 1
case (EndOfString(_, l1), EndOfString(_, l2)) =>
Integer.compare(l1, l2)
case (EndOfString(_, _), _) => -1
case (Length(_, _, _), Str(_, _) | 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(_)) => -1
case (ExpectedFailureAt(_, m1), ExpectedFailureAt(_, m2)) =>
m1.compare(m2)
case (ExpectedFailureAt(_, _), _) => 1
case (Fail(_), _) => 1
}
}
}
}
/**
* 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] = {
// merge all the ranges:
val rangeMerge: List[InRange] =
errors
.toList
.collect { case InRange(o, l, u) => (o, l to u) }
.groupBy(_._1)
.iterator
.flatMap { case (o, ranges) =>
// TODO: this could be optimized to not enumerate the set
// for instance, a cheap thing to do is see if they
// overlap or not
val ary = ranges.iterator.map(_._2).flatten.toArray
java.util.Arrays.sort(ary)
Impl.rangesFor(ary)
.map { case (l, u) => InRange(o, l, u) }
.toList
}
.toList
if (rangeMerge.isEmpty) errors.distinct.sorted
else {
val nonRanges = errors.toList.filterNot(_.isInstanceOf[InRange])
NonEmptyList.fromListUnsafe(
(rangeMerge reverse_::: nonRanges).distinct
)
.sorted
}
}
}
final case class Error(failedAtOffset: Int, expected: NonEmptyList[Expectation]) {
def offsets: NonEmptyList[Int] =
expected.map(_.offset).distinct
}
/**
* Enables syntax to access product01, product10 and flatMap01
*/
final class With1[+A](val parser: Parser[A]) extends AnyVal {
def ~[B](that: Parser1[B]): Parser1[(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 => Parser1[B]): Parser1[B] =
Parser.flatMap01(parser)(fn)
def *>[B](that: Parser1[B]): Parser1[B] =
product01(void(parser), that).map(_._2)
def <*[B](that: Parser1[B]): Parser1[A] =
product01(parser, void1(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)
}
/**
* 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 Soft[+A](parser: Parser[A]) {
def ~[B](that: Parser[B]): Parser[(A, B)] =
softProduct(parser, that)
def *>[B](that: Parser[B]): Parser[B] =
softProduct(void(parser), that).map(_._2)
def <*[B](that: Parser[B]): Parser[A] =
softProduct(parser, void(that)).map(_._1)
}
final class Soft1[+A](parser: Parser1[A]) extends Soft(parser) {
override def ~[B](that: Parser[B]): Parser1[(A, B)] =
softProduct10(parser, that)
override def *>[B](that: Parser[B]): Parser1[B] =
softProduct10(void1(parser), that).map(_._2)
override def <*[B](that: Parser[B]): Parser1[A] =
softProduct10(parser, void(that)).map(_._1)
}
final class Soft01[+A](val parser: Parser[A]) extends AnyVal {
def ~[B](that: Parser1[B]): Parser1[(A, B)] =
softProduct01(parser, that)
def *>[B](that: Parser1[B]): Parser1[B] =
softProduct01(void(parser), that).map(_._2)
def <*[B](that: Parser1[B]): Parser1[A] =
softProduct01(parser, void1(that)).map(_._1)
}
def pure[A](a: A): Parser[A] =
Impl.Pure(a)
/**
* Parse a given string or
* fail. This backtracks on failure
* this is an error if the string is empty
*/
def string1(str: String): Parser1[Unit] =
if (str.length == 1) char(str.charAt(0))
else Impl.Str(str)
/**
* Parse a potentially empty string or
* fail. This backtracks on failure
*/
def string(str: String): Parser[Unit] =
if (str.length == 0) unit
else string1(str)
def oneOf1[A](parsers: List[Parser1[A]]): Parser1[A] = {
@annotation.tailrec
def flatten(ls: List[Parser1[A]], acc: List[Parser1[A]]): List[Parser1[A]] =
ls match {
case Nil => acc.reverse.distinct
case Impl.OneOf1(ps) :: rest =>
flatten(ps ::: rest, acc)
case Impl.Fail() :: rest =>
flatten(rest, acc)
case notOneOf :: rest =>
flatten(rest, notOneOf :: acc)
}
val flat = flatten(parsers, Nil)
Impl.mergeCharIn[A, Parser1[A]](flat) match {
case Nil => fail
case p :: Nil => p
case two => Impl.OneOf1(two)
}
}
def oneOf[A](ps: List[Parser[A]]): Parser[A] = {
@annotation.tailrec
def flatten(ls: List[Parser[A]], acc: List[Parser[A]]): List[Parser[A]] =
ls match {
case Nil => acc.reverse.distinct
case Impl.OneOf(ps) :: rest =>
flatten(ps ::: rest, acc)
case Impl.OneOf1(ps) :: rest =>
flatten(ps ::: rest, acc)
case Impl.Fail() :: rest =>
flatten(rest, acc)
case notOneOf :: rest =>
flatten(rest, notOneOf :: acc)
}
val flat = flatten(ps, Nil)
Impl.mergeCharIn[A, Parser[A]](flat) match {
case Nil => fail
case p :: Nil => p
case two => Impl.OneOf(two)
}
}
/**
* if len < 1, the same as pure("")
* else length1(len)
*/
def length(len: Int): Parser[String] =
if (len > 0) length1(len) else pure("")
/**
* Parse the next len characters where len > 0
* if (len < 1) throw IllegalArgumentException
*/
def length1(len: Int): Parser1[String] =
Impl.Length(len)
/**
* Repeat this parser 0 or more times
* note: this can wind up parsing nothing
*/
def rep[A](p1: Parser1[A]): Parser[List[A]] =
Impl.Rep(p1)
/**
* Repeat this parser 1 or more times
*/
def rep1[A](p1: Parser1[A], min: Int): Parser1[NonEmptyList[A]] =
Impl.Rep1(p1, min)
/**
*
* Repeat 1 or more times with a separator
*/
def rep1Sep[A](p1: Parser1[A], min: Int, sep: Parser[Any]): Parser1[NonEmptyList[A]] = {
if (min <= 0) throw new IllegalArgumentException(s"require min > 0, found: $min")
val rest = (sep.void.with1.soft *> p1).rep(min - 1)
(p1 ~ rest).map { case (h, t) => NonEmptyList(h, t) }
}
/**
* Repeat 0 or more times with a separator
*/
def repSep[A](p1: Parser1[A], min: Int, sep: Parser[Any]): Parser[List[A]] = {
if (min <= 0) rep1Sep(p1, 1, sep).?.map {
case None => Nil
case Some(nel) => nel.toList
}
else rep1Sep(p1, min, sep).map(_.toList)
}
def product10[A, B](first: Parser1[A], second: Parser[B]): Parser1[(A, B)] =
Impl.Prod1(first, second)
def product01[A, B](first: Parser[A], second: Parser1[B]): Parser1[(A, B)] =
Impl.Prod1(first, second)
def product[A, B](first: Parser[A], second: Parser[B]): Parser[(A, B)] =
Impl.Prod(first, second)
def softProduct10[A, B](first: Parser1[A], second: Parser[B]): Parser1[(A, B)] =
Impl.SoftProd1(first, second)
def softProduct01[A, B](first: Parser[A], second: Parser1[B]): Parser1[(A, B)] =
Impl.SoftProd1(first, second)
def softProduct[A, B](first: Parser[A], second: Parser[B]): Parser[(A, B)] =
Impl.SoftProd(first, second)
def map[A, B](p: Parser[A])(fn: A => B): Parser[B] =
Impl.Map(p, fn)
def map1[A, B](p: Parser1[A])(fn: A => B): Parser1[B] =
Impl.Map1(p, fn)
def flatMap[A, B](pa: Parser[A])(fn: A => Parser[B]): Parser[B] =
Impl.FlatMap(pa, fn)
def flatMap10[A, B](pa: Parser1[A])(fn: A => Parser[B]): Parser1[B] =
Impl.FlatMap1(pa, fn)
def flatMap01[A, B](pa: Parser[A])(fn: A => Parser1[B]): Parser1[B] =
Impl.FlatMap1(pa, fn)
def tailRecM[A, B](init: A)(fn: A => Parser[Either[A, B]]): Parser[B] =
Impl.TailRecM(init, fn)
def tailRecM1[A, B](init: A)(fn: A => Parser1[Either[A, B]]): Parser1[B] =
Impl.TailRecM1(init, fn)
def defer1[A](pa: => Parser1[A]): Parser1[A] =
Impl.Defer1(() => pa)
def defer[A](pa: => Parser[A]): Parser[A] =
Impl.Defer(() => pa)
val Fail: Parser1[Nothing] = Impl.Fail()
def fail[A]: Parser1[A] = Fail
val unit: Parser[Unit] = pure(())
/**
* Parse 1 character from the string
*/
def anyChar: Parser1[Char] =
Impl.AnyChar
/**
* An empty iterable is the same as fail
*/
def charIn(cs: Iterable[Char]): Parser1[Char] =
if (cs.isEmpty) fail
else {
val ary = cs.toArray
java.util.Arrays.sort(ary)
Impl.rangesFor(ary) match {
case NonEmptyList((low, high), Nil) if low == Char.MinValue && high == Char.MaxValue =>
anyChar
case notAnyChar =>
Impl.CharIn(ary(0).toInt, BitSetUtil.bitSetFor(ary), notAnyChar)
}
}
@inline
private[this] def charImpl(c: Char): Parser1[Unit] =
charIn(c :: Nil).void
// Cache the common parsers to reduce allocations
private[this] val charArray: Array[Parser1[Unit]] =
(32 to 126).map { idx => charImpl(idx.toChar) }.toArray
def char(c: Char): Parser1[Unit] = {
val cidx = c.toInt - 32
if ((cidx >= 0) && (cidx < charArray.length)) charArray(cidx)
else charImpl(c)
}
def charIn(c0: Char, cs: Char*): Parser1[Char] =
charIn(c0 :: cs.toList)
def charWhere(fn: Char => Boolean): Parser1[Char] =
charIn(Impl.allChars.filter(fn))
/**
* Parse a string while the given function is true
*/
def charsWhile(fn: Char => Boolean): Parser[String] =
charWhere(fn).rep.string
/**
* Parse a string while the given function is true
* parses at least one character
*/
def charsWhile1(fn: Char => Boolean): Parser1[String] =
charWhere(fn).rep1.string
def until(p: Parser[Any]): Parser[String] =
(not(p).with1 ~ anyChar).rep.string
def void[A](pa: Parser[A]): Parser[Unit] =
pa match {
case v@Impl.Void(_) => v
case Impl.StartParser => Impl.StartParser
case Impl.EndParser => Impl.EndParser
case n@Impl.Not(_) => n
case p@Impl.Peek(_) => p
case p1: Parser1[A] => void1(p1)
case notVoid => Impl.Void(Impl.unmap(pa))
}
def void1[A](pa: Parser1[A]): Parser1[Unit] =
pa match {
case v@Impl.Void1(_) => v
case p: Impl.Str => p
case notVoid => Impl.Void1(Impl.unmap1(pa))
}
def string[A](pa: Parser[A]): Parser[String] =
pa match {
case str@Impl.StringP(_) => str
case s1: Parser1[A] => string1(s1)
case notStr => Impl.StringP(Impl.unmap(pa))
}
def string1[A](pa: Parser1[A]): Parser1[String] =
pa match {
case str@Impl.StringP1(_) => str
case len@Impl.Length(_) => len
case notStr => Impl.StringP1(Impl.unmap1(pa))
}
/**
* returns a parser that succeeds if the
* current parser fails.
*/
def not(pa: Parser[Any]): Parser[Unit] =
Impl.Not(void(pa))
/**
* a parser that consumes nothing when
* it succeeds, basically rewind on success
*/
def peek(pa: Parser[Any]): Parser[Unit] =
// TODO: we can adjust Rep/Rep1 to do minimal
// work since we rewind after we are sure there is
// a match
Impl.Peek(void(pa))
/**
* return the current position in the string
* we are parsing. This lets you record position information
* in your ASTs you are parsing
*/
def index: Parser[Int] = Impl.Index
// succeeds when we are at the start
def start: Parser[Unit] = Impl.StartParser
// succeeds when we are at the end
def end: Parser[Unit] = Impl.EndParser
/**
* If we fail, rewind the offset back so that
* we can try other branches. This tends
* to harm debuggability and ideally should be
* minimized
*/
def backtrack[A](pa: Parser[A]): Parser[A] =
pa match {
case p1: Parser1[A] => backtrack1(p1)
case pa if Impl.doesBacktrack(pa) => pa
case nbt => Impl.Backtrack(nbt)
}
/**
* If we fail, rewind the offset back so that
* we can try other branches. This tends
* to harm debuggability and ideally should be
* minimized
*/
def backtrack1[A](pa: Parser1[A]): Parser1[A] =
pa match {
case pa if Impl.doesBacktrack(pa) => pa
case nbt => Impl.Backtrack1(nbt)
}
implicit val catsInstancesParser1: FlatMap[Parser1] with Defer[Parser1] with MonoidK[Parser1]=
new FlatMap[Parser1] with Defer[Parser1] with MonoidK[Parser1] {
def empty[A] = Fail
def defer[A](pa: => Parser1[A]): Parser1[A] =
defer1(pa)
def map[A, B](fa: Parser1[A])(fn: A => B): Parser1[B] =
map1(fa)(fn)
def flatMap[A, B](fa: Parser1[A])(fn: A => Parser1[B]): Parser1[B] =
flatMap10(fa)(fn)
override def product[A, B](pa: Parser1[A], pb: Parser1[B]): Parser1[(A, B)] =
product10(pa, pb)
override def map2[A, B, C](pa: Parser1[A], pb: Parser1[B])(fn: (A, B) => C): Parser1[C] =
map(product(pa, pb)) { case (a, b) => fn(a, b) }
override def map2Eval[A, B, C](pa: Parser1[A], pb: Eval[Parser1[B]])(fn: (A, B) => C): Eval[Parser1[C]] =
Now(pb match {
case Now(pb) => map2(pa, pb)(fn)
case later => map2(pa, defer(later.value))(fn)
})
def tailRecM[A, B](init: A)(fn: A => Parser1[Either[A, B]]): Parser1[B] =
tailRecM1(init)(fn)
def combineK[A](pa: Parser1[A], pb: Parser1[A]): Parser1[A] =
Parser.oneOf1(pa :: pb :: Nil)
override def void[A](pa: Parser1[A]): Parser1[Unit] =
pa.void
override def as[A, B](pa: Parser1[A], b: B): Parser1[B] =
pa.void.map(_ => b)
override def productL[A, B](pa: Parser1[A])(pb: Parser1[B]): Parser1[A] =
map(product(pa, pb.void)) { case (a, _) => a }
override def productR[A, B](pa: Parser1[A])(pb: Parser1[B]): Parser1[B] =
map(product(pa.void, pb)) { case (_, b) => b }
}
private object Impl {
val allChars = Char.MinValue to Char.MaxValue
val optTail: List[Parser[Option[Nothing]]] = Parser.pure(None) :: Nil
final def doesBacktrackCheat(p: Parser[Any]): Boolean =
doesBacktrack(p)
@annotation.tailrec
final def doesBacktrack(p: Parser[Any]): Boolean =
p match {
case Backtrack(_) | Backtrack1(_) | AnyChar | CharIn(_, _, _) | Str(_) | Length(_) |
StartParser | EndParser | Index | Pure(_) => true
case Map(p, _) => doesBacktrack(p)
case Map1(p, _) => doesBacktrack(p)
case SoftProd(a, b) => doesBacktrackCheat(a) && doesBacktrack(b)
case SoftProd1(a, b) => doesBacktrackCheat(a) && doesBacktrack(b)
case _ => false
}
/**
* This removes any trailing map functions which
* can cause wasted allocations if we are later going
* to void or return strings. This stops
* at StringP or VoidP since those are markers
* that anything below has already been transformed
*/
def unmap[A](pa: Parser[A]): Parser[Any] =
pa match {
case p1: Parser1[Any] => unmap1(p1)
case Map(p, _) =>
// we discard any allocations done by fn
unmap(p)
case StringP(s) =>
// StringP is added privately, and only after unmap
s
case Void(v) =>
// Void is added privately, and only after unmap
v
case n@Not(_) =>
// not is already voided
n
case p@Peek(_) =>
// peek is already voided
p
case Backtrack(p) =>
// unmap may simplify enough
// to remove the backtrack wrapper
Parser.backtrack(unmap(p))
case OneOf(ps) => OneOf(ps.map(unmap))
case Prod(p1, p2) =>
val u1 = unmap(p1)
val u2 = unmap(p2)
if (u1 eq Parser.unit) u2
else if (u2 eq Parser.unit) u1
else Prod(u1, u2)
case SoftProd(p1, p2) =>
val u1 = unmap(p1)
val u2 = unmap(p2)
if (u1 eq Parser.unit) u2
else if (u2 eq Parser.unit) u1
else SoftProd(u1, u2)
case Defer(fn) =>
Defer(() => unmap(compute(fn)))
case Rep(p) => Rep(unmap1(p))
case Pure(_) => Parser.unit
case Index | StartParser | EndParser | TailRecM(_, _) | FlatMap(_, _) =>
// we can't transform this significantly
pa
}
/**
* This removes any trailing map functions which
* can cause wasted allocations if we are later going
* to void or return strings. This stops
* at StringP or VoidP since those are markers
* that anything below has already been transformed
*/
def unmap1[A](pa: Parser1[A]): Parser1[Any] =
pa match {
case Map1(p, _) =>
// we discard any allocations done by fn
unmap1(p)
case StringP1(s) =>
// StringP is added privately, and only after unmap
s
case Void1(v) =>
// Void is added privately, and only after unmap
v
case Backtrack1(p) =>
// unmap may simplify enough
// to remove the backtrack wrapper
Parser.backtrack1(unmap1(p))
case OneOf1(ps) => OneOf1(ps.map(unmap1))
case Prod1(p1, p2) => Prod1(unmap(p1), unmap(p2))
case SoftProd1(p1, p2) => SoftProd1(unmap(p1), unmap(p2))
case Defer1(fn) =>
Defer1(() => unmap1(compute1(fn)))
case Rep1(p, m) => Rep1(unmap1(p), m)
case AnyChar | CharIn(_, _, _) | Str(_) | Fail() | Length(_) | TailRecM1(_, _) | FlatMap1(_, _) =>
// we can't transform this significantly
pa
}
final class State(val str: String) {
var offset: Int = 0
var error: Chain[Expectation] = null
var capture: Boolean = true
}
case class Pure[A](result: A) extends Parser[A] {
override def parseMut(state: State): A = result
}
case class Length(len: Int) extends Parser1[String] {
if (len < 1) throw new IllegalArgumentException(s"required length > 0, found $len")
override def parseMut(state: State): String = {
val offset = state.offset
val end = offset + len
if (end <= state.str.length) {
val res = if (state.capture) state.str.substring(offset, end) else null
state.offset = end
res
}
else {
state.error = Chain.one(Expectation.Length(offset, len, state.str.length - offset))
null
}
}
}
def void[A](pa: Parser[A], state: State): Unit = {
val s0 = state.capture
state.capture = false
pa.parseMut(state)
state.capture = s0
()
}
case class Void[A](parser: Parser[A]) extends Parser[Unit] {
override def parseMut(state: State): Unit =
Impl.void(parser, state)
}
case class Void1[A](parser: Parser1[A]) extends Parser1[Unit] {
override def parseMut(state: State): Unit =
Impl.void(parser, state)
}
def string[A](pa: Parser[A], state: State): String = {
val s0 = state.capture
state.capture = false
val init = state.offset
pa.parseMut(state)
val str = state.str.substring(init, state.offset)
state.capture = s0
str
}
case class StringP[A](parser: Parser[A]) extends Parser[String] {
override def parseMut(state: State): String =
Impl.string(parser, state)
}
case class StringP1[A](parser: Parser1[A]) extends Parser1[String] {
override def parseMut(state: State): String =
Impl.string(parser, state)
}
case object StartParser extends Parser[Unit] {
override def parseMut(state: State): Unit = {
if (state.offset != 0) {
state.error = Chain.one(Expectation.StartOfString(state.offset))
}
()
}
}
case object EndParser extends Parser[Unit] {
override def parseMut(state: State): Unit = {
if (state.offset != state.str.length) {
state.error = Chain.one(Expectation.EndOfString(state.offset, state.str.length))
}
()
}
}
case object Index extends Parser[Int] {
override def parseMut(state: State): Int = state.offset
}
final def backtrack[A](pa: Parser[A], state: State): A = {
val offset = state.offset
val a = pa.parseMut(state)
if (state.error ne null) {
state.offset = offset
}
a
}
case class Backtrack[A](parser: Parser[A]) extends Parser[A] {
override def parseMut(state: State): A =
Impl.backtrack(parser, state)
}
case class Backtrack1[A](parser: Parser1[A]) extends Parser1[A] {
override def parseMut(state: State): A =
Impl.backtrack(parser, state)
}
case class Str(message: String) extends Parser1[Unit] {
if (message.isEmpty) throw new IllegalArgumentException("we need a non-empty string to expect a message")
override def parseMut(state: State): Unit = {
val offset = state.offset
if (state.str.regionMatches(offset, message, 0, message.length)) {
state.offset += message.length
()
}
else {
state.error = Chain.one(Expectation.Str(offset, message))
()
}
}
}
case class Fail[A]() extends Parser1[A] {
override def parseMut(state: State): A = {
state.error = Chain.one(Expectation.Fail(state.offset));
null.asInstanceOf[A]
}
}
final def oneOf[A](all: List[Parser[A]], state: State): A = {
var ps = all
val offset = state.offset
var errs: Chain[Expectation] = Chain.nil
while (ps.nonEmpty) {
val thisParser = ps.head
ps = ps.tail
val res = thisParser.parseMut(state)
// we stop if there was no error
// or if we consumed some input
if ((state.error eq null) || (state.offset != offset)) {
return res
}
else {
// we failed to parse, but didn't consume input
// is unchanged we continue
// else we stop
errs = errs ++ state.error
state.error = null
}