-
Notifications
You must be signed in to change notification settings - Fork 20
/
Parser.hs
1250 lines (1107 loc) · 37.1 KB
/
Parser.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.MMark.Parser
-- Copyright : © 2017–present Mark Karpov
-- License : BSD 3 clause
--
-- Maintainer : Mark Karpov <markkarpov92@gmail.com>
-- Stability : experimental
-- Portability : portable
--
-- MMark markdown parser.
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
module Text.MMark.Parser
( MMarkErr (..)
, parse )
where
import Control.Applicative (Alternative, liftA2)
import Control.Monad
import Data.Bifunctor (Bifunctor (..))
import Data.Bool (bool)
import Data.HTML.Entities (htmlEntityMap)
import Data.List.NonEmpty (NonEmpty (..), (<|))
import Data.Maybe (isNothing, fromJust, catMaybes, isJust)
import Data.Monoid (Any (..))
import Data.Ratio ((%))
import Data.Text (Text)
import Lens.Micro ((^.))
import Text.MMark.Parser.Internal
import Text.MMark.Type
import Text.MMark.Util
import Text.Megaparsec hiding (parse, State (..))
import Text.Megaparsec.Char hiding (eol)
import Text.URI (URI)
import Text.URI.Lens (uriPath)
import qualified Control.Monad.Combinators.NonEmpty as NE
import qualified Data.Aeson as Aeson
import qualified Data.Char as Char
import qualified Data.DList as DList
import qualified Data.HashMap.Strict as HM
import qualified Data.List.NonEmpty as NE
import qualified Data.Set as E
import qualified Data.Text as T
import qualified Data.Text.Encoding as TE
import qualified Text.Email.Validate as Email
import qualified Text.Megaparsec.Char.Lexer as L
import qualified Text.URI as URI
#if !MIN_VERSION_base(4,13,0)
import Data.Semigroup (Semigroup (..))
#endif
#if !defined(ghcjs_HOST_OS)
import qualified Data.Yaml as Yaml
#endif
----------------------------------------------------------------------------
-- Auxiliary data types
-- | Frame that describes where we are in parsing inlines.
data InlineFrame
= EmphasisFrame -- ^ Emphasis with asterisk @*@
| EmphasisFrame_ -- ^ Emphasis with underscore @_@
| StrongFrame -- ^ Strong emphasis with asterisk @**@
| StrongFrame_ -- ^ Strong emphasis with underscore @__@
| StrikeoutFrame -- ^ Strikeout
| SubscriptFrame -- ^ Subscript
| SuperscriptFrame -- ^ Superscript
deriving (Eq, Ord, Show)
-- | State of inline parsing that specifies whether we expect to close one
-- frame or there is a possibility to close one of two alternatives.
data InlineState
= SingleFrame InlineFrame -- ^ One frame to be closed
| DoubleFrame InlineFrame InlineFrame -- ^ Two frames to be closed
deriving (Eq, Ord, Show)
----------------------------------------------------------------------------
-- Top-level API
-- | Parse a markdown document in the form of a strict 'Text' value and
-- either report parse errors or return an 'MMark' document.
parse
:: FilePath
-- ^ File name (only to be used in error messages), may be empty
-> Text
-- ^ Input to parse
-> Either (ParseErrorBundle Text MMarkErr) MMark
-- ^ Parse errors or parsed document
parse file input =
case runBParser pMMark file input of
Left bundle -> Left bundle
Right ((myaml, rawBlocks), defs) ->
let parsed = doInline <$> rawBlocks
doInline = fmap
$ first (replaceEof "end of inline block")
. runIParser defs pInlinesTop
e2p = either DList.singleton (const DList.empty)
in case NE.nonEmpty . DList.toList $ foldMap (foldMap e2p) parsed of
Nothing -> Right MMark
{ mmarkYaml = myaml
, mmarkBlocks = fmap fromRight <$> parsed
, mmarkExtension = mempty }
Just errs -> Left ParseErrorBundle
{ bundleErrors = errs
, bundlePosState = PosState
{ pstateInput = input
, pstateOffset = 0
, pstateSourcePos = initialPos file
, pstateTabWidth = mkPos 4
, pstateLinePrefix = ""
}
}
----------------------------------------------------------------------------
-- Block parser
-- | Parse an MMark document on block level.
pMMark :: BParser (Maybe Aeson.Value, [Block Isp])
pMMark = do
meyaml <- optional pYamlBlock
blocks <- pBlocks
eof
return $ case meyaml of
Nothing ->
(Nothing, blocks)
Just (Left (o, err)) ->
(Nothing, prependErr o (YamlParseError err) blocks)
Just (Right yaml) ->
(Just yaml, blocks)
-- | Parse a YAML block. On success return the actual parsed 'Aeson.Value' in
-- 'Right', otherwise return 'SourcePos' of parse error and 'String'
-- describing the error as generated by the @yaml@ package in 'Left'.
pYamlBlock :: BParser (Either (Int, String) Aeson.Value)
pYamlBlock = do
string "---" *> sc' *> eol
let go acc = do
l <- takeWhileP Nothing notNewline
void (optional eol)
e <- atEnd
if e || T.stripEnd l == "---"
then return acc
else go (acc . (l:))
doffset <- getOffset
ls <- go id <*> ([] <$ sc)
return $ decodeYaml ls doffset
-- | Parse several (possibly zero) blocks in a row.
pBlocks :: BParser [Block Isp]
pBlocks = catMaybes <$> many pBlock
-- | Parse a single block of markdown document.
pBlock :: BParser (Maybe (Block Isp))
pBlock = do
sc
rlevel <- refLevel
alevel <- L.indentLevel
done <- atEnd
if done || alevel < rlevel then empty else
case compare alevel (ilevel rlevel) of
LT -> choice
[ Just <$> pThematicBreak
, Just <$> pAtxHeading
, Just <$> pFencedCodeBlock
, Just <$> pTable
, Just <$> pUnorderedList
, Just <$> pOrderedList
, Just <$> pBlockquote
, pReferenceDef
, Just <$> pParagraph ]
_ ->
Just <$> pIndentedCodeBlock
-- | Parse a thematic break.
pThematicBreak :: BParser (Block Isp)
pThematicBreak = do
l' <- lookAhead nonEmptyLine
let l = T.filter (not . isSpace) l'
if T.length l >= 3 &&
(T.all (== '*') l ||
T.all (== '-') l ||
T.all (== '_') l)
then ThematicBreak <$ nonEmptyLine <* sc
else empty
-- | Parse an ATX heading.
pAtxHeading :: BParser (Block Isp)
pAtxHeading = do
(void . lookAhead . try) hashIntro
withRecovery recover $ do
hlevel <- length <$> hashIntro
sc1'
ispOffset <- getOffset
r <- someTill (satisfy notNewline <?> "heading character") . try $
optional (sc1' *> some (char '#') *> sc') *> (eof <|> eol)
let toBlock = case hlevel of
1 -> Heading1
2 -> Heading2
3 -> Heading3
4 -> Heading4
5 -> Heading5
_ -> Heading6
toBlock (IspSpan ispOffset (T.strip (T.pack r))) <$ sc
where
hashIntro = count' 1 6 (char '#')
recover err =
Heading1 (IspError err) <$ takeWhileP Nothing notNewline <* sc
-- | Parse a fenced code block.
pFencedCodeBlock :: BParser (Block Isp)
pFencedCodeBlock = do
alevel <- L.indentLevel
(ch, n, infoString) <- pOpeningFence
let content = label "code block content" (option "" nonEmptyLine <* eol)
ls <- manyTill content (pClosingFence ch n)
CodeBlock infoString (assembleCodeBlock alevel ls) <$ sc
-- | Parse the opening fence of a fenced code block.
pOpeningFence :: BParser (Char, Int, Maybe Text)
pOpeningFence = p '`' <|> p '~'
where
p ch = try $ do
void $ count 3 (char ch)
n <- (+ 3) . length <$> many (char ch)
ml <- optional
(T.strip <$> someEscapedWith notNewline <?> "info string")
guard (maybe True (not . T.any (== '`')) ml)
(ch, n,
case ml of
Nothing -> Nothing
Just l ->
if T.null l
then Nothing
else Just l) <$ eol
-- | Parse the closing fence of a fenced code block.
pClosingFence :: Char -> Int -> BParser ()
pClosingFence ch n = try . label "closing code fence" $ do
clevel <- ilevel <$> refLevel
void $ L.indentGuard sc' LT clevel
void $ count n (char ch)
(void . many . char) ch
sc'
eof <|> eol
-- | Parse an indented code block.
pIndentedCodeBlock :: BParser (Block Isp)
pIndentedCodeBlock = do
alevel <- L.indentLevel
clevel <- ilevel <$> refLevel
let go ls = do
indented <- lookAhead $
(>= clevel) <$> (sc *> L.indentLevel)
if indented
then do
l <- option "" nonEmptyLine
continue <- eol'
let ls' = ls . (l:)
if continue
then go ls'
else return ls'
else return ls
-- NOTE This is a bit unfortunate, but it's difficult to guarantee
-- that preceding space is not yet consumed when we get to
-- interpreting input as an indented code block, so we need to restore
-- the space this way.
f x = T.replicate (unPos alevel - 1) " " <> x
g [] = []
g (x:xs) = f x : xs
ls <- g . ($ []) <$> go id
CodeBlock Nothing (assembleCodeBlock clevel ls) <$ sc
-- | Parse an unorederd list.
pUnorderedList :: BParser (Block Isp)
pUnorderedList = do
(bullet, bulletPos, minLevel, indLevel) <-
pListBullet Nothing
x <- innerBlocks bulletPos minLevel indLevel
xs <- many $ do
(_, bulletPos', minLevel', indLevel') <-
pListBullet (Just (bullet, bulletPos))
innerBlocks bulletPos' minLevel' indLevel'
return (UnorderedList (normalizeListItems (x:|xs)))
where
innerBlocks bulletPos minLevel indLevel = do
p <- getSourcePos
let tooFar = sourceLine p > sourceLine bulletPos <> pos1
rlevel = slevel minLevel indLevel
if tooFar || sourceColumn p < minLevel
then return [bool Naked Paragraph tooFar emptyIspSpan]
else subEnv True rlevel pBlocks
-- | Parse a list bullet. Return a tuple with the following components (in
-- order):
--
-- * 'Char' used to represent the bullet
-- * 'SourcePos' at which the bullet was located
-- * the closest column position where content could start
-- * the indentation level after the bullet
pListBullet
:: Maybe (Char, SourcePos)
-- ^ Bullet 'Char' and start position of the first bullet in a list
-> BParser (Char, SourcePos, Pos, Pos)
pListBullet mbullet = try $ do
pos <- getSourcePos
l <- (<> mkPos 2) <$> L.indentLevel
bullet <-
case mbullet of
Nothing -> char '-' <|> char '+' <|> char '*'
Just (bullet, bulletPos) -> do
guard (sourceColumn pos >= sourceColumn bulletPos)
char bullet
eof <|> sc1
l' <- L.indentLevel
return (bullet, pos, l, l')
-- | Parse an ordered list.
pOrderedList :: BParser (Block Isp)
pOrderedList = do
startOffset <- getOffset
(startIx, del, startPos, minLevel, indLevel) <-
pListIndex Nothing
x <- innerBlocks startPos minLevel indLevel
xs <- manyIndexed (startIx + 1) $ \expectedIx -> do
startOffset' <- getOffset
(actualIx, _, startPos', minLevel', indLevel') <-
pListIndex (Just (del, startPos))
let f blocks =
if actualIx == expectedIx
then blocks
else prependErr
startOffset'
(ListIndexOutOfOrder actualIx expectedIx)
blocks
f <$> innerBlocks startPos' minLevel' indLevel'
return . OrderedList startIx . normalizeListItems $
(if startIx <= 999999999
then x
else prependErr startOffset (ListStartIndexTooBig startIx) x)
:| xs
where
innerBlocks indexPos minLevel indLevel = do
p <- getSourcePos
let tooFar = sourceLine p > sourceLine indexPos <> pos1
rlevel = slevel minLevel indLevel
if tooFar || sourceColumn p < minLevel
then return [bool Naked Paragraph tooFar emptyIspSpan]
else subEnv True rlevel pBlocks
-- | Parse a list index. Return a tuple with the following components (in
-- order):
--
-- * 'Word' parsed numeric index
-- * 'Char' used as delimiter after the numeric index
-- * 'SourcePos' at which the index was located
-- * the closest column position where content could start
-- * the indentation level after the index
pListIndex
:: Maybe (Char, SourcePos)
-- ^ Delimiter 'Char' and start position of the first index in a list
-> BParser (Word, Char, SourcePos, Pos, Pos)
pListIndex mstart = try $ do
pos <- getSourcePos
i <- L.decimal
del <- case mstart of
Nothing -> char '.' <|> char ')'
Just (del, startPos) -> do
guard (sourceColumn pos >= sourceColumn startPos)
char del
l <- (<> pos1) <$> L.indentLevel
eof <|> sc1
l' <- L.indentLevel
return (i, del, pos, l, l')
-- | Parse a block quote.
pBlockquote :: BParser (Block Isp)
pBlockquote = do
minLevel <- try $ do
minLevel <- (<> pos1) <$> L.indentLevel
void (char '>')
eof <|> sc
l <- L.indentLevel
return $
if l > minLevel
then minLevel <> pos1
else minLevel
indLevel <- L.indentLevel
if indLevel >= minLevel
then do
let rlevel = slevel minLevel indLevel
xs <- subEnv False rlevel pBlocks
return (Blockquote xs)
else return (Blockquote [])
-- | Parse a link\/image reference definition and register it.
pReferenceDef :: BParser (Maybe (Block Isp))
pReferenceDef = do
(o, dlabel) <- try (pRefLabel <* char ':')
withRecovery recover $ do
sc' <* optional eol <* sc'
uri <- pUri
hadSpN <- optional $
(sc1' *> option False (True <$ eol)) <|> (True <$ (sc' <* eol))
sc'
mtitle <-
if isJust hadSpN
then optional pTitle <* sc'
else return Nothing
case (hadSpN, mtitle) of
(Just True, Nothing) -> return ()
_ -> hidden eof <|> eol
conflict <- registerReference dlabel (uri, mtitle)
when conflict $ do
setOffset o
customFailure (DuplicateReferenceDefinition dlabel)
Nothing <$ sc
where
recover err =
Just (Naked (IspError err)) <$ takeWhileP Nothing notNewline <* sc
-- | Parse a pipe table.
pTable :: BParser (Block Isp)
pTable = do
(n, headerRow) <- try $ do
pos <- L.indentLevel
option False (T.any (== '|') <$> lookAhead nonEmptyLine) >>= guard
let pipe' = option False (True <$ pipe)
l <- pipe'
headerRow <- NE.sepBy1 cell (try (pipe <* notFollowedBy eol))
r <- pipe'
let n = NE.length headerRow
guard (n > 1 || l || r)
eol <* sc'
L.indentLevel >>= \i -> guard (i == pos || i == (pos <> pos1))
lookAhead nonEmptyLine >>= guard . isHeaderLike
return (n, headerRow)
withRecovery recover $ do
sc'
caligns <- rowWrapper (NE.fromList <$> sepByCount n calign pipe)
otherRows <- many $ do
endOfTable >>= guard . not
rowWrapper (NE.fromList <$> sepByCount n cell pipe)
Table caligns (headerRow :| otherRows) <$ sc
where
cell = do
o <- getOffset
txt <- fmap (T.stripEnd . T.pack) . foldMany' . choice $
[ (++) . T.unpack <$> hidden (string "\\|")
, (++) . T.unpack <$> pCodeSpanB
, (:) <$> label "inline content" (satisfy cellChar) ]
return (IspSpan o txt)
cellChar x = x /= '|' && notNewline x
rowWrapper p = do
void (optional pipe)
r <- p
void (optional pipe)
eof <|> eol
sc'
return r
pipe = char '|' <* sc'
calign = do
let colon' = option False (True <$ char ':')
l <- colon'
void (count 3 (char '-') <* many (char '-'))
r <- colon'
sc'
return $
case (l, r) of
(False, False) -> CellAlignDefault
(True, False) -> CellAlignLeft
(False, True) -> CellAlignRight
(True, True) -> CellAlignCenter
isHeaderLike txt =
T.length (T.filter isHeaderConstituent txt) % T.length txt >
8 % 10
isHeaderConstituent x =
isSpace x || x == '|' || x == '-' || x == ':'
endOfTable =
lookAhead (option True (isBlank <$> nonEmptyLine))
recover err =
Naked (IspError (replaceEof "end of table block" err)) <$
manyTill
(optional nonEmptyLine)
(endOfTable >>= guard) <* sc
-- | Parse a paragraph or naked text (is some cases).
pParagraph :: BParser (Block Isp)
pParagraph = do
startOffset <- getOffset
allowNaked <- isNakedAllowed
rlevel <- refLevel
let go ls = do
l <- lookAhead (option "" nonEmptyLine)
broken <- succeeds . lookAhead . try $ do
sc
alevel <- L.indentLevel
guard (alevel < ilevel rlevel)
unless (alevel < rlevel) . choice $
[ void (char '>')
, void pThematicBreak
, void pAtxHeading
, void pOpeningFence
, void (pListBullet Nothing)
, void (pListIndex Nothing) ]
if isBlank l
then return (ls, Paragraph)
else if broken
then return (ls, Naked)
else do
void nonEmptyLine
continue <- eol'
let ls' = ls . (l:)
if continue
then go ls'
else return (ls', Naked)
l <- nonEmptyLine
continue <- eol'
(ls, toBlock) <-
if continue
then go id
else return (id, Naked)
(if allowNaked then toBlock else Paragraph)
(IspSpan startOffset (assembleParagraph (l:ls []))) <$ sc
----------------------------------------------------------------------------
-- Auxiliary block-level parsers
-- | 'match' a code span, this is a specialised and adjusted version of
-- 'pCodeSpan'.
pCodeSpanB :: BParser Text
pCodeSpanB = fmap fst . match . hidden $ do
n <- try (length <$> some (char '`'))
let finalizer = try $ do
void $ count n (char '`')
notFollowedBy (char '`')
skipManyTill (label "code span content" $
takeWhile1P Nothing (== '`') <|>
takeWhile1P Nothing (\x -> x /= '`' && notNewline x))
finalizer
----------------------------------------------------------------------------
-- Inline parser
-- | The top level inline parser.
pInlinesTop :: IParser (NonEmpty Inline)
pInlinesTop = do
inlines <- pInlines
eof <|> void pLfdr
return inlines
-- | Parse inlines using settings from given 'InlineConfig'.
pInlines :: IParser (NonEmpty Inline)
pInlines = do
done <- atEnd
allowsEmpty <- isEmptyAllowed
if done
then
if allowsEmpty
then (return . nes . Plain) ""
else unexpEic EndOfInput
else NE.some $ do
mch <- lookAhead (anySingle <?> "inline content")
case mch of
'`' -> pCodeSpan
'[' -> do
allowsLinks <- isLinksAllowed
if allowsLinks
then pLink
else unexpEic (Tokens $ nes '[')
'!' -> do
gotImage <- (succeeds . void . lookAhead . string) "!["
allowsImages <- isImagesAllowed
if gotImage
then if allowsImages
then pImage
else unexpEic (Tokens . NE.fromList $ "![")
else pPlain
'<' -> do
allowsLinks <- isLinksAllowed
if allowsLinks
then try pAutolink <|> pPlain
else pPlain
'\\' ->
try pHardLineBreak <|> pPlain
ch ->
if isFrameConstituent ch
then pEnclosedInline
else pPlain
-- | Parse a code span.
--
-- See also: 'pCodeSpanB'.
pCodeSpan :: IParser Inline
pCodeSpan = do
n <- try (length <$> some (char '`'))
let finalizer = try $ do
void $ count n (char '`')
notFollowedBy (char '`')
r <- CodeSpan . collapseWhiteSpace . T.concat <$>
manyTill (label "code span content" $
takeWhile1P Nothing (== '`') <|>
takeWhile1P Nothing (/= '`'))
finalizer
r <$ lastChar OtherChar
-- | Parse a link.
pLink :: IParser Inline
pLink = do
void (char '[')
o <- getOffset
txt <- disallowLinks (disallowEmpty pInlines)
void (char ']')
(dest, mtitle) <- pLocation o txt
Link txt dest mtitle <$ lastChar OtherChar
-- | Parse an image.
pImage :: IParser Inline
pImage = do
(pos, alt) <- emptyAlt <|> nonEmptyAlt
(src, mtitle) <- pLocation pos alt
Image alt src mtitle <$ lastChar OtherChar
where
emptyAlt = do
o <- getOffset
void (string "![]")
return (o + 2, nes (Plain ""))
nonEmptyAlt = do
void (string "![")
o <- getOffset
alt <- disallowImages (disallowEmpty pInlines)
void (char ']')
return (o, alt)
-- | Parse an autolink.
pAutolink :: IParser Inline
pAutolink = between (char '<') (char '>') $ do
notFollowedBy (char '>')
uri' <- URI.parser
let (txt, uri) =
case isEmailUri uri' of
Nothing ->
( (nes . Plain . URI.render) uri'
, uri' )
Just email ->
( nes (Plain email)
, URI.makeAbsolute mailtoScheme uri' )
Link txt uri Nothing <$ lastChar OtherChar
-- | Parse inline content inside an enclosing construction such as emphasis,
-- strikeout, superscript, and\/or subscript markup.
pEnclosedInline :: IParser Inline
pEnclosedInline = disallowEmpty $ pLfdr >>= \case
SingleFrame x ->
liftFrame x <$> pInlines <* pRfdr x
DoubleFrame x y -> do
inlines0 <- pInlines
thisFrame <- pRfdr x <|> pRfdr y
let thatFrame = if thisFrame == x then y else x
minlines1 <- optional pInlines
void (pRfdr thatFrame)
return . liftFrame thatFrame $
case minlines1 of
Nothing ->
nes (liftFrame thisFrame inlines0)
Just inlines1 ->
liftFrame thisFrame inlines0 <| inlines1
-- | Parse a hard line break.
pHardLineBreak :: IParser Inline
pHardLineBreak = do
void (char '\\')
eol
notFollowedBy eof
sc'
lastChar SpaceChar
return LineBreak
-- | Parse plain text.
pPlain :: IParser Inline
pPlain = fmap (Plain . bakeText) . foldSome $ do
ch <- lookAhead (anySingle <?> "inline content")
let newline' =
(('\n':) . dropWhile isSpace) <$ eol <* sc' <* lastChar SpaceChar
case ch of
'\\' -> (:) <$>
((escapedChar <* lastChar OtherChar) <|>
try (char '\\' <* notFollowedBy eol <* lastChar OtherChar))
'\n' ->
newline'
'\r' ->
newline'
'!' -> do
notFollowedBy (string "![")
(:) <$> char '!' <* lastChar PunctChar
'<' -> do
notFollowedBy pAutolink
(:) <$> char '<' <* lastChar PunctChar
'&' -> choice
[ (:) <$> numRef
, (++) . reverse <$> entityRef
, (:) <$> char '&' ] <* lastChar PunctChar
_ ->
(:) <$>
if Char.isSpace ch
then char ch <* lastChar SpaceChar
else if isSpecialChar ch
then failure
(Just . Tokens . nes $ ch)
(E.singleton . Label . NE.fromList $ "inline content")
else if Char.isPunctuation ch
then char ch <* lastChar PunctChar
else char ch <* lastChar OtherChar
----------------------------------------------------------------------------
-- Auxiliary inline-level parsers
-- | Parse an inline and reference-style link\/image location.
pLocation
:: Int -- ^ Offset where the content inlines start
-> NonEmpty Inline -- ^ The inner content inlines
-> IParser (URI, Maybe Text) -- ^ URI and optionally title
pLocation innerOffset inner = do
mr <- optional (inplace <|> withRef)
case mr of
Nothing ->
collapsed innerOffset inner <|> shortcut innerOffset inner
Just (dest, mtitle) ->
return (dest, mtitle)
where
inplace = do
void (char '(')
sc'
dest <- pUri
hadSpace <- option False (True <$ sc1)
mtitle <- if hadSpace
then optional pTitle <* sc'
else return Nothing
void (char ')')
return (dest, mtitle)
withRef =
pRefLabel >>= uncurry lookupRef
collapsed o inlines = do
-- NOTE We need to do these manipulations so the failure caused by
-- @'string' "[]"@ does not overwrite our custom failures.
o' <- getOffset
setOffset o
(void . hidden . string) "[]"
setOffset (o' + 2)
lookupRef o (mkLabel inlines)
shortcut o inlines =
lookupRef o (mkLabel inlines)
lookupRef o dlabel =
lookupReference dlabel >>= \case
Left names -> do
setOffset o
customFailure (CouldNotFindReferenceDefinition dlabel names)
Right x ->
return x
mkLabel = T.unwords . T.words . asPlainText
-- | Parse a URI.
pUri :: (Ord e, Show e, MonadParsec e Text m) => m URI
pUri = between (char '<') (char '>') URI.parser <|> naked
where
naked = do
let f x = not (isSpaceN x || x == ')')
l = "end of URI"
(s, s') <- T.span f <$> getInput
when (T.null s) . void $
(satisfy f <?> "URI") -- this will now fail
setInput s
r <- region (replaceEof l) (URI.parser <* label l eof)
setInput s'
return r
-- | Parse a title of a link or an image.
pTitle :: MonadParsec MMarkErr Text m => m Text
pTitle = choice
[ p '\"' '\"'
, p '\'' '\''
, p '(' ')' ]
where
p start end = between (char start) (char end) $
let f x = x /= end
in manyEscapedWith f "unescaped character"
-- | Parse label of a reference link.
pRefLabel :: MonadParsec MMarkErr Text m => m (Int, Text)
pRefLabel = do
try $ do
void (char '[')
notFollowedBy (char ']')
o <- getOffset
sc
let f x = x /= '[' && x /= ']'
dlabel <- someEscapedWith f <?> "reference label"
void (char ']')
return (o, dlabel)
-- | Parse an opening markup sequence corresponding to given 'InlineState'.
pLfdr :: IParser InlineState
pLfdr = try $ do
o <- getOffset
let r st = st <$ string (inlineStateDel st)
st <- hidden $ choice
[ r (DoubleFrame StrongFrame StrongFrame)
, r (DoubleFrame StrongFrame EmphasisFrame)
, r (SingleFrame StrongFrame)
, r (SingleFrame EmphasisFrame)
, r (DoubleFrame StrongFrame_ StrongFrame_)
, r (DoubleFrame StrongFrame_ EmphasisFrame_)
, r (SingleFrame StrongFrame_)
, r (SingleFrame EmphasisFrame_)
, r (DoubleFrame StrikeoutFrame StrikeoutFrame)
, r (DoubleFrame StrikeoutFrame SubscriptFrame)
, r (SingleFrame StrikeoutFrame)
, r (SingleFrame SubscriptFrame)
, r (SingleFrame SuperscriptFrame) ]
let dels = inlineStateDel st
failNow = do
setOffset o
(customFailure . NonFlankingDelimiterRun . toNesTokens) dels
lch <- getLastChar
rch <- getNextChar OtherChar
when (lch >= rch) failNow
return st
-- | Parse a closing markup sequence corresponding to given 'InlineFrame'.
pRfdr :: InlineFrame -> IParser InlineFrame
pRfdr frame = try $ do
let dels = inlineFrameDel frame
expectingInlineContent = region $ \case
TrivialError pos us es -> TrivialError pos us $
E.insert (Label $ NE.fromList "inline content") es
other -> other
o <- getOffset
(void . expectingInlineContent . string) dels
let failNow = do
setOffset o
(customFailure . NonFlankingDelimiterRun . toNesTokens) dels
lch <- getLastChar
rch <- getNextChar SpaceChar
when (lch <= rch) failNow
return frame
-- | Get 'CharType' of the next char in the input stream.
getNextChar
:: CharType -- ^ What we should consider frame constituent characters
-> IParser CharType
getNextChar frameType = lookAhead (option SpaceChar (charType <$> anySingle))
where
charType ch
| isFrameConstituent ch = frameType
| Char.isSpace ch = SpaceChar
| ch == '\\' = OtherChar
| Char.isPunctuation ch = PunctChar
| otherwise = OtherChar
----------------------------------------------------------------------------
-- Parsing helpers
manyIndexed :: (Alternative m, Num n) => n -> (n -> m a) -> m [a]
manyIndexed n' m = go n'
where
go !n = liftA2 (:) (m n) (go (n + 1)) <|> pure []
foldMany :: MonadPlus m => m (a -> a) -> m (a -> a)
foldMany f = go id
where
go g =
optional f >>= \case
Nothing -> pure g
Just h -> go (h . g)
foldMany' :: MonadPlus m => m ([a] -> [a]) -> m [a]
foldMany' f = ($ []) <$> go id
where
go g =
optional f >>= \case
Nothing -> pure g
Just h -> go (g . h)
foldSome :: MonadPlus m => m (a -> a) -> m (a -> a)
foldSome f = liftA2 (flip (.)) f (foldMany f)
foldSome' :: MonadPlus m => m ([a] -> [a]) -> m [a]
foldSome' f = liftA2 ($) f (foldMany' f)
sepByCount :: MonadPlus m => Int -> m a -> m sep -> m [a]
sepByCount 0 _ _ = pure []
sepByCount n p sep = liftA2 (:) p (count (n - 1) (sep *> p))
nonEmptyLine :: BParser Text
nonEmptyLine = takeWhile1P Nothing notNewline
manyEscapedWith :: MonadParsec MMarkErr Text m
=> (Char -> Bool)
-> String
-> m Text
manyEscapedWith f l = fmap T.pack . foldMany' . choice $
[ (:) <$> escapedChar
, (:) <$> numRef
, (++) . reverse <$> entityRef
, (:) <$> satisfy f <?> l ]
someEscapedWith :: MonadParsec MMarkErr Text m
=> (Char -> Bool)
-> m Text
someEscapedWith f = fmap T.pack . foldSome' . choice $
[ (:) <$> escapedChar
, (:) <$> numRef
, (++) . reverse <$> entityRef
, (:) <$> satisfy f ]
escapedChar :: MonadParsec e Text m => m Char
escapedChar = label "escaped character" $
try (char '\\' *> satisfy isAsciiPunctuation)
-- | Parse an HTML5 entity reference.
entityRef :: MonadParsec MMarkErr Text m => m String
entityRef = do
o <- getOffset
let f (TrivialError _ us es) = TrivialError o us es
f (FancyError _ xs) = FancyError o xs
name <- try . region f $ between (char '&') (char ';')
(takeWhile1P Nothing Char.isAlphaNum <?> "HTML5 entity name")
case HM.lookup name htmlEntityMap of
Nothing -> do
setOffset o
customFailure (UnknownHtmlEntityName name)
Just txt -> return (T.unpack txt)
-- | Parse a numeric character using the given numeric parser.
numRef :: MonadParsec MMarkErr Text m => m Char
numRef = do
o <- getOffset
let f = between (string "&#") (char ';')
n <- try (f (char' 'x' *> L.hexadecimal)) <|> f L.decimal
if n == 0 || n > fromEnum (maxBound :: Char)
then do
setOffset o
customFailure (InvalidNumericCharacter n)
else return (Char.chr n)
sc :: MonadParsec e Text m => m ()
sc = void $ takeWhileP (Just "white space") isSpaceN
sc1 :: MonadParsec e Text m => m ()
sc1 = void $ takeWhile1P (Just "white space") isSpaceN