-
Notifications
You must be signed in to change notification settings - Fork 83
/
Megaparsec.hs
1618 lines (1413 loc) · 57.5 KB
/
Megaparsec.hs
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
-- |
-- Module : Text.Megaparsec
-- Copyright : © 2015–2018 Megaparsec contributors
-- © 2007 Paolo Martini
-- © 1999–2001 Daan Leijen
-- License : FreeBSD
--
-- Maintainer : Mark Karpov <markkarpov92@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- This module includes everything you need to get started writing a parser.
-- If you are new to Megaparsec and don't know where to begin, take a look
-- at the tutorials <https://markkarpov.com/learn-haskell.html#megaparsec-tutorials>.
--
-- In addition to the "Text.Megaparsec" module, which exports and re-exports
-- most everything that you may need, we advise to import
-- "Text.Megaparsec.Char" if you plan to work with a stream of 'Char' tokens
-- or "Text.Megaparsec.Byte" if you intend to parse binary data.
--
-- It is common to start working with the library by defining a type synonym
-- like this:
--
-- > type Parser = Parsec Void Text
-- > ^ ^
-- > | |
-- > Custom error component Type of input
--
-- Then you can write type signatures like @Parser Int@—for a parser that
-- returns an 'Int' for example.
--
-- Similarly (since it's known to cause confusion), you should use
-- 'ParseError' type parametrized like this:
--
-- > ParseError Char Void
-- > ^ ^
-- > | |
-- > Token type Custom error component (the same you used in Parser)
--
-- Token type for 'String' and 'Data.Text.Text' (strict and lazy) is 'Char',
-- for 'Data.ByteString.ByteString's it's 'Data.Word.Word8'.
--
-- Megaparsec uses some type-level machinery to provide flexibility without
-- compromising on type safety. Thus type signatures are sometimes necessary
-- to avoid ambiguous types. If you're seeing a error message that reads
-- like “Type variable @e0@ is ambiguous …”, you need to give an explicit
-- signature to your parser to resolve the ambiguity. It's a good idea to
-- provide type signatures for all top-level definitions.
--
-- Megaparsec is capable of a lot. Apart from this standard functionality
-- you can parse permutation phrases with "Text.Megaparsec.Perm",
-- expressions with "Text.Megaparsec.Expr", do lexing with
-- "Text.Megaparsec.Char.Lexer" and "Text.Megaparsec.Byte.Lexer". These
-- modules should be imported explicitly along with the modules mentioned
-- above.
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Text.Megaparsec
( -- * Re-exports
-- $reexports
module Text.Megaparsec.Pos
, module Text.Megaparsec.Error
, module Text.Megaparsec.Stream
, module Control.Monad.Combinators
-- * Data types
, State (..)
, Parsec
, ParsecT
-- * Running parser
, parse
, parseMaybe
, parseTest
, parseTest'
, runParser
, runParser'
, runParserT
, runParserT'
-- * Primitive combinators
, MonadParsec (..)
-- * Derivatives of primitive combinators
, (<?>)
, unexpected
, customFailure
, match
, region
, takeRest
, atEnd
-- * Parser state combinators
, getInput
, setInput
, getPosition
, getNextTokenPosition
, setPosition
, pushPosition
, popPosition
, getTokensProcessed
, setTokensProcessed
, getTabWidth
, setTabWidth
, setParserState
-- * Debugging
, dbg )
where
import Control.DeepSeq
import Control.Monad
import Control.Monad.Combinators
import Control.Monad.Cont.Class
import Control.Monad.Error.Class
import Control.Monad.Identity
import Control.Monad.Reader.Class
import Control.Monad.State.Class hiding (state)
import Control.Monad.Trans
import Control.Monad.Trans.Identity
import Data.Data (Data)
import Data.List.NonEmpty (NonEmpty (..))
import Data.Maybe (fromJust)
import Data.Proxy
import Data.Semigroup hiding (option)
import Data.Set (Set)
import Data.String (IsString (..))
import Data.Typeable (Typeable)
import Debug.Trace
import GHC.Generics
import Text.Megaparsec.Error
import Text.Megaparsec.Pos
import Text.Megaparsec.Stream
import qualified Control.Applicative as A
import qualified Control.Monad.Fail as Fail
import qualified Control.Monad.RWS.Lazy as L
import qualified Control.Monad.RWS.Strict as S
import qualified Control.Monad.Trans.Reader as L
import qualified Control.Monad.Trans.State.Lazy as L
import qualified Control.Monad.Trans.State.Strict as S
import qualified Control.Monad.Trans.Writer.Lazy as L
import qualified Control.Monad.Trans.Writer.Strict as S
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as E
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
#endif
-- $reexports
--
-- Also note that you can import "Control.Monad.Combinators.NonEmpty" if you
-- wish that combinators like 'some' return 'NonEmpty' lists. The module
-- lives in the @parser-combinators@ package (you need at least version
-- /0.4.0/).
--
-- This module is intended to be imported qualified:
--
-- > import qualified Control.Monad.Combinators.NonEmpty as NE
----------------------------------------------------------------------------
-- Data types
-- | This is the Megaparsec's state parametrized over stream type @s@.
data State s = State
{ stateInput :: s
-- ^ The rest of input to process
, statePos :: NonEmpty SourcePos
-- ^ Current position (column + line number) with support for include files
, stateTokensProcessed :: {-# UNPACK #-} !Int
-- ^ Number of processed tokens so far
--
-- @since 5.2.0
, stateTabWidth :: Pos
-- ^ Tab width to use
} deriving (Show, Eq, Data, Typeable, Generic)
instance NFData s => NFData (State s)
-- | All information available after parsing. This includes consumption of
-- input, success (with returned value) or failure (with parse error), and
-- parser state at the end of parsing.
--
-- See also: 'Consumption', 'Result'.
data Reply e s a = Reply (State s) Consumption (Result (Token s) e a)
-- | This data structure represents an aspect of result of parser's work.
--
-- See also: 'Result', 'Reply'.
data Consumption
= Consumed -- ^ Some part of input stream was consumed
| Virgin -- ^ No input was consumed
-- | This data structure represents an aspect of result of parser's work.
--
-- See also: 'Consumption', 'Reply'.
data Result t e a
= OK a -- ^ Parser succeeded
| Error (ParseError t e) -- ^ Parser failed
-- | 'Hints' represent a collection of 'ErrorItem's to be included into
-- 'ParserError' (when it's a 'TrivialError') as “expected” message items
-- when a parser fails without consuming input right after successful parser
-- that produced the hints.
--
-- For example, without hints you could get:
--
-- >>> parseTest (many (char 'r') <* eof) "ra"
-- 1:2:
-- unexpected 'a'
-- expecting end of input
--
-- We're getting better error messages with help of hints:
--
-- >>> parseTest (many (char 'r') <* eof) "ra"
-- 1:2:
-- unexpected 'a'
-- expecting 'r' or end of input
newtype Hints t = Hints [Set (ErrorItem t)]
deriving (Semigroup, Monoid)
-- | Convert 'ParseError' record into 'Hints'.
toHints :: NonEmpty SourcePos -> ParseError t e -> Hints t
toHints streamPos = \case
TrivialError errPos _ ps ->
-- NOTE This is important to check here that the error indeed has
-- happened at the same position as current position of stream because
-- there might have been backtracking with 'try' and in that case we
-- must not convert such a parse error to hints.
if streamPos == errPos
then Hints (if E.null ps then [] else [ps])
else mempty
FancyError _ _ -> mempty
{-# INLINE toHints #-}
-- | @withHints hs c@ makes “error” continuation @c@ use given hints @hs@.
--
-- Note that if resulting continuation gets 'ParseError' that has custom
-- data in it, hints are ignored.
withHints :: Ord (Token s)
=> Hints (Token s) -- ^ Hints to use
-> (ParseError (Token s) e -> State s -> m b) -- ^ Continuation to influence
-> ParseError (Token s) e -- ^ First argument of resulting continuation
-> State s -- ^ Second argument of resulting continuation
-> m b
withHints (Hints ps') c e =
case e of
TrivialError pos us ps -> c (TrivialError pos us (E.unions (ps : ps')))
_ -> c e
{-# INLINE withHints #-}
-- | @accHints hs c@ results in “OK” continuation that will add given hints
-- @hs@ to third argument of original continuation @c@.
accHints
:: Hints t -- ^ 'Hints' to add
-> (a -> State s -> Hints t -> m b) -- ^ An “OK” continuation to alter
-> a -- ^ First argument of resulting continuation
-> State s -- ^ Second argument of resulting continuation
-> Hints t -- ^ Third argument of resulting continuation
-> m b
accHints hs1 c x s hs2 = c x s (hs1 <> hs2)
{-# INLINE accHints #-}
-- | Replace the most recent group of hints (if any) with the given
-- 'ErrorItem' (or delete it if 'Nothing' is given). This is used in 'label'
-- primitive.
refreshLastHint :: Hints t -> Maybe (ErrorItem t) -> Hints t
refreshLastHint (Hints []) _ = Hints []
refreshLastHint (Hints (_:xs)) Nothing = Hints xs
refreshLastHint (Hints (_:xs)) (Just m) = Hints (E.singleton m : xs)
{-# INLINE refreshLastHint #-}
-- | 'Parsec' is a non-transformer variant of the more general 'ParsecT'
-- monad transformer.
type Parsec e s = ParsecT e s Identity
-- | @'ParsecT' e s m a@ is a parser with custom data component of error
-- @e@, stream type @s@, underlying monad @m@ and return type @a@.
newtype ParsecT e s m a = ParsecT
{ unParser
:: forall b. State s
-> (a -> State s -> Hints (Token s) -> m b) -- consumed-OK
-> (ParseError (Token s) e -> State s -> m b) -- consumed-error
-> (a -> State s -> Hints (Token s) -> m b) -- empty-OK
-> (ParseError (Token s) e -> State s -> m b) -- empty-error
-> m b }
-- | @since 5.3.0
instance (Stream s, Semigroup a) => Semigroup (ParsecT e s m a) where
(<>) = A.liftA2 (<>)
{-# INLINE (<>) #-}
#if MIN_VERSION_base(4,8,0)
sconcat = fmap sconcat . sequence
#else
sconcat = fmap (sconcat . NE.fromList) . sequence . NE.toList
#endif
{-# INLINE sconcat #-}
-- | @since 5.3.0
instance (Stream s, Monoid a) => Monoid (ParsecT e s m a) where
mempty = pure mempty
{-# INLINE mempty #-}
mappend = A.liftA2 mappend
{-# INLINE mappend #-}
mconcat = fmap mconcat . sequence
{-# INLINE mconcat #-}
-- | @since 6.3.0
instance (a ~ Tokens s, IsString a, Eq a, Stream s, Ord e)
=> IsString (ParsecT e s m a) where
fromString s = tokens (==) (fromString s)
instance Functor (ParsecT e s m) where
fmap = pMap
pMap :: (a -> b) -> ParsecT e s m a -> ParsecT e s m b
pMap f p = ParsecT $ \s cok cerr eok eerr ->
unParser p s (cok . f) cerr (eok . f) eerr
{-# INLINE pMap #-}
-- | 'pure' returns a parser that __succeeds__ without consuming input.
instance Stream s => A.Applicative (ParsecT e s m) where
pure = pPure
(<*>) = pAp
p1 *> p2 = p1 `pBind` const p2
p1 <* p2 = do { x1 <- p1 ; void p2 ; return x1 }
pAp :: Stream s
=> ParsecT e s m (a -> b)
-> ParsecT e s m a
-> ParsecT e s m b
pAp m k = ParsecT $ \s cok cerr eok eerr ->
let mcok x s' hs = unParser k s' (cok . x) cerr
(accHints hs (cok . x)) (withHints hs cerr)
meok x s' hs = unParser k s' (cok . x) cerr
(accHints hs (eok . x)) (withHints hs eerr)
in unParser m s mcok cerr meok eerr
{-# INLINE pAp #-}
-- | 'A.empty' is a parser that __fails__ without consuming input.
instance (Ord e, Stream s) => A.Alternative (ParsecT e s m) where
empty = mzero
(<|>) = mplus
-- | 'return' returns a parser that __succeeds__ without consuming input.
instance Stream s => Monad (ParsecT e s m) where
return = pure
(>>=) = pBind
fail = Fail.fail
pPure :: a -> ParsecT e s m a
pPure x = ParsecT $ \s _ _ eok _ -> eok x s mempty
{-# INLINE pPure #-}
pBind :: Stream s
=> ParsecT e s m a
-> (a -> ParsecT e s m b)
-> ParsecT e s m b
pBind m k = ParsecT $ \s cok cerr eok eerr ->
let mcok x s' hs = unParser (k x) s' cok cerr
(accHints hs cok) (withHints hs cerr)
meok x s' hs = unParser (k x) s' cok cerr
(accHints hs eok) (withHints hs eerr)
in unParser m s mcok cerr meok eerr
{-# INLINE pBind #-}
instance Stream s => Fail.MonadFail (ParsecT e s m) where
fail = pFail
pFail :: String -> ParsecT e s m a
pFail msg = ParsecT $ \s@(State _ pos _ _) _ _ _ eerr ->
let d = E.singleton (ErrorFail msg)
in eerr (FancyError pos d) s
{-# INLINE pFail #-}
mkPT :: Monad m => (State s -> m (Reply e s a)) -> ParsecT e s m a
mkPT k = ParsecT $ \s cok cerr eok eerr -> do
(Reply s' consumption result) <- k s
case consumption of
Consumed ->
case result of
OK x -> cok x s' mempty
Error e -> cerr e s'
Virgin ->
case result of
OK x -> eok x s' mempty
Error e -> eerr e s'
instance (Stream s, MonadIO m) => MonadIO (ParsecT e s m) where
liftIO = lift . liftIO
instance (Stream s, MonadReader r m) => MonadReader r (ParsecT e s m) where
ask = lift ask
local f p = mkPT $ \s -> local f (runParsecT p s)
instance (Stream s, MonadState st m) => MonadState st (ParsecT e s m) where
get = lift get
put = lift . put
instance (Stream s, MonadCont m) => MonadCont (ParsecT e s m) where
callCC f = mkPT $ \s ->
callCC $ \c ->
runParsecT (f (\a -> mkPT $ \s' -> c (pack s' a))) s
where pack s a = Reply s Virgin (OK a)
instance (Stream s, MonadError e' m) => MonadError e' (ParsecT e s m) where
throwError = lift . throwError
p `catchError` h = mkPT $ \s ->
runParsecT p s `catchError` \e ->
runParsecT (h e) s
-- | 'mzero' is a parser that __fails__ without consuming input.
instance (Ord e, Stream s) => MonadPlus (ParsecT e s m) where
mzero = pZero
mplus = pPlus
pZero :: ParsecT e s m a
pZero = ParsecT $ \s@(State _ pos _ _) _ _ _ eerr ->
eerr (TrivialError pos Nothing E.empty) s
{-# INLINE pZero #-}
pPlus :: (Ord e, Stream s)
=> ParsecT e s m a
-> ParsecT e s m a
-> ParsecT e s m a
pPlus m n = ParsecT $ \s cok cerr eok eerr ->
let meerr err ms =
let ncerr err' s' = cerr (err' <> err) (longestMatch ms s')
neok x s' hs = eok x s' (toHints (statePos s') err <> hs)
neerr err' s' = eerr (err' <> err) (longestMatch ms s')
in unParser n s cok ncerr neok neerr
in unParser m s cok cerr eok meerr
{-# INLINE pPlus #-}
-- | @since 6.0.0
instance (Stream s, MonadFix m) => MonadFix (ParsecT e s m) where
mfix f = mkPT $ \s -> mfix $ \(~(Reply _ _ result)) -> do
let
a = case result of
OK a' -> a'
Error _ -> error "mfix ParsecT"
runParsecT (f a) s
-- | From two states, return the one with the greater number of processed
-- tokens. If the numbers of processed tokens are equal, prefer the second
-- state.
longestMatch :: State s -> State s -> State s
longestMatch s1@(State _ _ tp1 _) s2@(State _ _ tp2 _) =
case tp1 `compare` tp2 of
LT -> s2
EQ -> s2
GT -> s1
{-# INLINE longestMatch #-}
instance MonadTrans (ParsecT e s) where
lift amb = ParsecT $ \s _ _ eok _ ->
amb >>= \a -> eok a s mempty
----------------------------------------------------------------------------
-- Running a parser
-- | @'parse' p file input@ runs parser @p@ over 'Identity' (see 'runParserT'
-- if you're using the 'ParsecT' monad transformer; 'parse' itself is just a
-- synonym for 'runParser'). It returns either a 'ParseError' ('Left') or a
-- value of type @a@ ('Right'). 'parseErrorPretty' can be used to turn
-- 'ParseError' into the string representation of the error message. See
-- "Text.Megaparsec.Error" if you need to do more advanced error analysis.
--
-- > main = case (parse numbers "" "11,2,43") of
-- > Left err -> putStr (parseErrorPretty err)
-- > Right xs -> print (sum xs)
-- >
-- > numbers = integer `sepBy` char ','
parse
:: Parsec e s a -- ^ Parser to run
-> String -- ^ Name of source file
-> s -- ^ Input for parser
-> Either (ParseError (Token s) e) a
parse = runParser
-- | @'parseMaybe' p input@ runs the parser @p@ on @input@ and returns the
-- result inside 'Just' on success and 'Nothing' on failure. This function
-- also parses 'eof', so if the parser doesn't consume all of its input, it
-- will fail.
--
-- The function is supposed to be useful for lightweight parsing, where
-- error messages (and thus file name) are not important and entire input
-- should be parsed. For example, it can be used when parsing of a single
-- number according to a specification of its format is desired.
parseMaybe :: (Ord e, Stream s) => Parsec e s a -> s -> Maybe a
parseMaybe p s =
case parse (p <* eof) "" s of
Left _ -> Nothing
Right x -> Just x
-- | The expression @'parseTest' p input@ applies the parser @p@ against
-- input @input@ and prints the result to stdout. Useful for testing.
parseTest :: ( ShowErrorComponent e
, Ord (Token s)
, ShowToken (Token s)
, Show a )
=> Parsec e s a -- ^ Parser to run
-> s -- ^ Input for parser
-> IO ()
parseTest p input =
case parse p "" input of
Left e -> putStr (parseErrorPretty e)
Right x -> print x
-- | A version of 'parseTest' that also prints offending line in parse
-- errors.
--
-- @since 6.0.0
parseTest' :: ( ShowErrorComponent e
, ShowToken (Token s)
, LineToken (Token s)
, Show a
, Stream s )
=> Parsec e s a -- ^ Parser to run
-> s -- ^ Input for parser
-> IO ()
parseTest' p input =
case parse p "" input of
Left e -> putStr (parseErrorPretty' input e)
Right x -> print x
-- | @'runParser' p file input@ runs parser @p@ on the input stream of
-- tokens @input@, obtained from source @file@. The @file@ is only used in
-- error messages and may be the empty string. Returns either a 'ParseError'
-- ('Left') or a value of type @a@ ('Right').
--
-- > parseFromFile p file = runParser p file <$> readFile file
runParser
:: Parsec e s a -- ^ Parser to run
-> String -- ^ Name of source file
-> s -- ^ Input for parser
-> Either (ParseError (Token s) e) a
runParser p name s = snd $ runParser' p (initialState name s)
-- | The function is similar to 'runParser' with the difference that it
-- accepts and returns parser state. This allows to specify arbitrary
-- textual position at the beginning of parsing, for example. This is the
-- most general way to run a parser over the 'Identity' monad.
--
-- @since 4.2.0
runParser'
:: Parsec e s a -- ^ Parser to run
-> State s -- ^ Initial state
-> (State s, Either (ParseError (Token s) e) a)
runParser' p = runIdentity . runParserT' p
-- | @'runParserT' p file input@ runs parser @p@ on the input list of tokens
-- @input@, obtained from source @file@. The @file@ is only used in error
-- messages and may be the empty string. Returns a computation in the
-- underlying monad @m@ that returns either a 'ParseError' ('Left') or a
-- value of type @a@ ('Right').
runParserT :: Monad m
=> ParsecT e s m a -- ^ Parser to run
-> String -- ^ Name of source file
-> s -- ^ Input for parser
-> m (Either (ParseError (Token s) e) a)
runParserT p name s = snd `liftM` runParserT' p (initialState name s)
-- | This function is similar to 'runParserT', but like 'runParser'' it
-- accepts and returns parser state. This is thus the most general way to
-- run a parser.
--
-- @since 4.2.0
runParserT' :: Monad m
=> ParsecT e s m a -- ^ Parser to run
-> State s -- ^ Initial state
-> m (State s, Either (ParseError (Token s) e) a)
runParserT' p s = do
(Reply s' _ result) <- runParsecT p s
case result of
OK x -> return (s', Right x)
Error e -> return (s', Left e)
-- | Low-level unpacking of the 'ParsecT' type. 'runParserT' and 'runParser'
-- are built upon this.
runParsecT :: Monad m
=> ParsecT e s m a -- ^ Parser to run
-> State s -- ^ Initial state
-> m (Reply e s a)
runParsecT p s = unParser p s cok cerr eok eerr
where cok a s' _ = return $ Reply s' Consumed (OK a)
cerr err s' = return $ Reply s' Consumed (Error err)
eok a s' _ = return $ Reply s' Virgin (OK a)
eerr err s' = return $ Reply s' Virgin (Error err)
-- | Given name of source file and input construct initial state for parser.
initialState :: String -> s -> State s
initialState name s = State
{ stateInput = s
, statePos = initialPos name :| []
, stateTokensProcessed = 0
, stateTabWidth = defaultTabWidth }
----------------------------------------------------------------------------
-- Primitive combinators
-- | Type class describing monads that implement the full set of primitive
-- parsers.
--
-- __Note carefully__ that the following primitives are “fast” and should be
-- taken advantage of as much as possible if your aim is a fast parser:
-- 'tokens', 'takeWhileP', 'takeWhile1P', and 'takeP'.
class (Stream s, A.Alternative m, MonadPlus m)
=> MonadParsec e s m | m -> e s where
-- | The most general way to stop parsing and report a trivial
-- 'ParseError'.
--
-- @since 6.0.0
failure
:: Maybe (ErrorItem (Token s)) -- ^ Unexpected item (if any)
-> Set (ErrorItem (Token s)) -- ^ Expected items
-> m a
-- | The most general way to stop parsing and report a fancy 'ParseError'.
-- To report a single custom parse error, see 'customFailure'.
--
-- @since 6.0.0
fancyFailure
:: Set (ErrorFancy e) -- ^ Fancy error components
-> m a
-- | The parser @'label' name p@ behaves as parser @p@, but whenever the
-- parser @p@ fails /without consuming any input/, it replaces names of
-- “expected” tokens with the name @name@.
label :: String -> m a -> m a
-- | @'hidden' p@ behaves just like parser @p@, but it doesn't show any
-- “expected” tokens in error message when @p@ fails.
--
-- Please use 'hidden' instead of the old @'label' ""@ idiom.
hidden :: m a -> m a
hidden = label ""
-- | The parser @'try' p@ behaves like parser @p@, except that it
-- backtracks the parser state when @p@ fails (either consuming input or
-- not).
--
-- This combinator is used whenever arbitrary look ahead is needed. Since
-- it pretends that it hasn't consumed any input when @p@ fails, the
-- ('A.<|>') combinator will try its second alternative even if the first
-- parser failed while consuming input.
--
-- For example, here is a parser that is supposed to parse the word “let”
-- or the word “lexical”:
--
-- >>> parseTest (string "let" <|> string "lexical") "lexical"
-- 1:1:
-- unexpected "lex"
-- expecting "let"
--
-- What happens here? The first parser consumes “le” and fails (because it
-- doesn't see a “t”). The second parser, however, isn't tried, since the
-- first parser has already consumed some input! 'try' fixes this behavior
-- and allows backtracking to work:
--
-- >>> parseTest (try (string "let") <|> string "lexical") "lexical"
-- "lexical"
--
-- 'try' also improves error messages in case of overlapping alternatives,
-- because Megaparsec's hint system can be used:
--
-- >>> parseTest (try (string "let") <|> string "lexical") "le"
-- 1:1:
-- unexpected "le"
-- expecting "let" or "lexical"
--
-- __Please note__ that as of Megaparsec 4.4.0, 'string' backtracks
-- automatically (see 'tokens'), so it does not need 'try'. However, the
-- examples above demonstrate the idea behind 'try' so well that it was
-- decided to keep them. You still need to use 'try' when your
-- alternatives are complex, composite parsers.
try :: m a -> m a
-- | If @p@ in @'lookAhead' p@ succeeds (either consuming input or not)
-- the whole parser behaves like @p@ succeeded without consuming anything
-- (parser state is not updated as well). If @p@ fails, 'lookAhead' has no
-- effect, i.e. it will fail consuming input if @p@ fails consuming input.
-- Combine with 'try' if this is undesirable.
lookAhead :: m a -> m a
-- | @'notFollowedBy' p@ only succeeds when the parser @p@ fails. This
-- parser /never consumes/ any input and /never modifies/ parser state. It
-- can be used to implement the “longest match” rule.
notFollowedBy :: m a -> m ()
-- | @'withRecovery' r p@ allows continue parsing even if parser @p@
-- fails. In this case @r@ is called with the actual 'ParseError' as its
-- argument. Typical usage is to return a value signifying failure to
-- parse this particular object and to consume some part of the input up
-- to the point where the next object starts.
--
-- Note that if @r@ fails, original error message is reported as if
-- without 'withRecovery'. In no way recovering parser @r@ can influence
-- error messages.
--
-- @since 4.4.0
withRecovery
:: (ParseError (Token s) e -> m a) -- ^ How to recover from failure
-> m a -- ^ Original parser
-> m a -- ^ Parser that can recover from failures
-- | @'observing' p@ allows to “observe” failure of the @p@ parser, should
-- it happen, without actually ending parsing, but instead getting the
-- 'ParseError' in 'Left'. On success parsed value is returned in 'Right'
-- as usual. Note that this primitive just allows you to observe parse
-- errors as they happen, it does not backtrack or change how the @p@
-- parser works in any way.
--
-- @since 5.1.0
observing
:: m a -- ^ The parser to run
-> m (Either (ParseError (Token s) e) a)
-- | This parser only succeeds at the end of the input.
eof :: m ()
-- | The parser @'token' test exp@ accepts a token @t@ with result @x@
-- when the function @test t@ returns @'Just' x@. @exp@ specifies the
-- collection of expected items to report in error messages.
--
-- This is the most primitive combinator for accepting tokens. For
-- example, the 'Text.Megaparsec.Char.satisfy' parser is implemented as:
--
-- > satisfy f = token testChar E.empty
-- > where
-- > testChar x = if f x then Just x else Nothing
token
:: (Token s -> Maybe a)
-- ^ Matching function for the token to parse
-> Set (ErrorItem (Token s))
-- ^ Expected items (in case of an error)
-> m a
-- | The parser @'tokens' test@ parses a chunk of input and returns it.
-- Supplied predicate @test@ is used to check equality of given and parsed
-- chunks after a candidate chunk of correct length is fetched from the
-- stream.
--
-- This can be used for example to write 'Text.Megaparsec.Char.string':
--
-- > string = tokens (==)
--
-- Note that beginning from Megaparsec 4.4.0, this is an auto-backtracking
-- primitive, which means that if it fails, it never consumes any input.
-- This is done to make its consumption model match how error messages for
-- this primitive are reported (which becomes an important thing as user
-- gets more control with primitives like 'withRecovery'):
--
-- >>> parseTest (string "abc") "abd"
-- 1:1:
-- unexpected "abd"
-- expecting "abc"
--
-- This means, in particular, that it's no longer necessary to use 'try'
-- with 'tokens'-based parsers, such as 'Text.Megaparsec.Char.string' and
-- 'Text.Megaparsec.Char.string''. This feature /does not/ affect
-- performance in any way.
tokens
:: (Tokens s -> Tokens s -> Bool)
-- ^ Predicate to check equality of chunks
-> Tokens s
-- ^ Chunk of input to match against
-> m (Tokens s)
-- | Parse /zero/ or more tokens for which the supplied predicate holds.
-- Try to use this as much as possible because for many streams the
-- combinator is much faster than parsers built with 'many' and
-- 'Text.Megaparsec.Char.satisfy'.
--
-- The following equations should clarify the behavior:
--
-- > takeWhileP (Just "foo") f = many (satisfy f <?> "foo")
-- > takeWhileP Nothing f = many (satisfy f)
--
-- The combinator never fails, although it may parse an empty chunk.
--
-- @since 6.0.0
takeWhileP
:: Maybe String -- ^ Name for a single token in the row
-> (Token s -> Bool) -- ^ Predicate to use to test tokens
-> m (Tokens s) -- ^ A chunk of matching tokens
-- | Similar to 'takeWhileP', but fails if it can't parse at least one
-- token. Note that the combinator either succeeds or fails without
-- consuming any input, so 'try' is not necessary with it.
--
-- @since 6.0.0
takeWhile1P
:: Maybe String -- ^ Name for a single token in the row
-> (Token s -> Bool) -- ^ Predicate to use to test tokens
-> m (Tokens s) -- ^ A chunk of matching tokens
-- | Extract the specified number of tokens from the input stream and
-- return them packed as a chunk of stream. If there is not enough tokens
-- in the stream, a parse error will be signaled. It's guaranteed that if
-- the parser succeeds, the requested number of tokens will be returned.
--
-- The parser is roughly equivalent to:
--
-- > takeP (Just "foo") n = count n (anyChar <?> "foo")
-- > takeP Nothing n = count n anyChar
--
-- Note that if the combinator fails due to insufficient number of tokens
-- in the input stream, it backtracks automatically. No 'try' is necessary
-- with 'takeP'.
--
-- @since 6.0.0
takeP
:: Maybe String -- ^ Name for a single token in the row
-> Int -- ^ How many tokens to extract
-> m (Tokens s) -- ^ A chunk of matching tokens
-- | Return the full parser state as a 'State' record.
getParserState :: m (State s)
-- | @'updateParserState' f@ applies the function @f@ to the parser state.
updateParserState :: (State s -> State s) -> m ()
instance (Ord e, Stream s) => MonadParsec e s (ParsecT e s m) where
failure = pFailure
fancyFailure = pFancyFailure
label = pLabel
try = pTry
lookAhead = pLookAhead
notFollowedBy = pNotFollowedBy
withRecovery = pWithRecovery
observing = pObserving
eof = pEof
token = pToken
tokens = pTokens
takeWhileP = pTakeWhileP
takeWhile1P = pTakeWhile1P
takeP = pTakeP
getParserState = pGetParserState
updateParserState = pUpdateParserState
pFailure
:: Maybe (ErrorItem (Token s))
-> Set (ErrorItem (Token s))
-> ParsecT e s m a
pFailure us ps = ParsecT $ \s@(State _ pos _ _) _ _ _ eerr ->
eerr (TrivialError pos us ps) s
{-# INLINE pFailure #-}
pFancyFailure
:: Set (ErrorFancy e)
-> ParsecT e s m a
pFancyFailure xs = ParsecT $ \s@(State _ pos _ _) _ _ _ eerr ->
eerr (FancyError pos xs) s
{-# INLINE pFancyFailure #-}
pLabel :: String -> ParsecT e s m a -> ParsecT e s m a
pLabel l p = ParsecT $ \s cok cerr eok eerr ->
let el = Label <$> NE.nonEmpty l
cl = Label . (NE.fromList "the rest of " <>) <$> NE.nonEmpty l
cok' x s' hs = cok x s' (refreshLastHint hs cl)
eok' x s' hs = eok x s' (refreshLastHint hs el)
eerr' err = eerr $
case err of
(TrivialError pos us _) ->
TrivialError pos us (maybe E.empty E.singleton el)
_ -> err
in unParser p s cok' cerr eok' eerr'
{-# INLINE pLabel #-}
pTry :: ParsecT e s m a -> ParsecT e s m a
pTry p = ParsecT $ \s cok _ eok eerr ->
let eerr' err _ = eerr err s
in unParser p s cok eerr' eok eerr'
{-# INLINE pTry #-}
pLookAhead :: ParsecT e s m a -> ParsecT e s m a
pLookAhead p = ParsecT $ \s _ cerr eok eerr ->
let eok' a _ _ = eok a s mempty
in unParser p s eok' cerr eok' eerr
{-# INLINE pLookAhead #-}
pNotFollowedBy :: Stream s => ParsecT e s m a -> ParsecT e s m ()
pNotFollowedBy p = ParsecT $ \s@(State input pos _ _) _ _ eok eerr ->
let what = maybe EndOfInput (Tokens . nes . fst) (take1_ input)
unexpect u = TrivialError pos (pure u) E.empty
cok' _ _ _ = eerr (unexpect what) s
cerr' _ _ = eok () s mempty
eok' _ _ _ = eerr (unexpect what) s
eerr' _ _ = eok () s mempty
in unParser p s cok' cerr' eok' eerr'
{-# INLINE pNotFollowedBy #-}
pWithRecovery
:: (ParseError (Token s) e -> ParsecT e s m a)
-> ParsecT e s m a
-> ParsecT e s m a
pWithRecovery r p = ParsecT $ \s cok cerr eok eerr ->
let mcerr err ms =
let rcok x s' _ = cok x s' mempty
rcerr _ _ = cerr err ms
reok x s' _ = eok x s' (toHints (statePos s') err)
reerr _ _ = cerr err ms
in unParser (r err) ms rcok rcerr reok reerr
meerr err ms =
let rcok x s' _ = cok x s' (toHints (statePos s') err)
rcerr _ _ = eerr err ms
reok x s' _ = eok x s' (toHints (statePos s') err)
reerr _ _ = eerr err ms
in unParser (r err) ms rcok rcerr reok reerr
in unParser p s cok mcerr eok meerr
{-# INLINE pWithRecovery #-}
pObserving
:: ParsecT e s m a
-> ParsecT e s m (Either (ParseError (Token s) e) a)
pObserving p = ParsecT $ \s cok _ eok _ ->
let cerr' err s' = cok (Left err) s' mempty
eerr' err s' = eok (Left err) s' (toHints (statePos s') err)
in unParser p s (cok . Right) cerr' (eok . Right) eerr'
{-# INLINE pObserving #-}
pEof :: forall e s m. Stream s => ParsecT e s m ()
pEof = ParsecT $ \s@(State input (pos:|z) tp w) _ _ eok eerr ->
case take1_ input of
Nothing -> eok () s mempty
Just (x,_) ->
let !apos = positionAt1 (Proxy :: Proxy s) pos x
us = (pure . Tokens . nes) x
ps = E.singleton EndOfInput
in eerr (TrivialError (apos:|z) us ps)
(State input (apos:|z) tp w)
{-# INLINE pEof #-}
pToken :: forall e s m a. Stream s
=> (Token s -> Maybe a)
-> Set (ErrorItem (Token s))
-> ParsecT e s m a
pToken test ps = ParsecT $ \s@(State input (pos:|z) tp w) cok _ _ eerr ->
case take1_ input of
Nothing ->