-
Notifications
You must be signed in to change notification settings - Fork 63
/
Copy pathParse.hs
1562 lines (1453 loc) · 57 KB
/
Parse.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
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
-- | This module provides both a native Haskell solution for parsing XML
-- documents into a stream of events, and a set of parser combinators for
-- dealing with a stream of events.
--
-- As a simple example:
--
-- >>> :set -XOverloadedStrings
-- >>> import Conduit (runConduit, (.|))
-- >>> import Data.Text (Text, unpack)
-- >>> import Data.XML.Types (Event)
-- >>> data Person = Person Int Text Text deriving Show
-- >>> :{
-- let parsePerson :: MonadThrow m => ConduitT Event o m (Maybe Person)
-- parsePerson = tag' "person" parseAttributes $ \(age, goodAtHaskell) -> do
-- name <- content
-- return $ Person (read $ unpack age) name goodAtHaskell
-- where parseAttributes = (,) <$> requireAttr "age" <*> requireAttr "goodAtHaskell" <* ignoreAttrs
-- parsePeople :: MonadThrow m => ConduitT Event o m (Maybe [Person])
-- parsePeople = tagNoAttr "people" $ many parsePerson
-- inputXml = mconcat
-- [ "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
-- , "<people>"
-- , " <person age=\"25\" goodAtHaskell=\"yes\">Michael</person>"
-- , " <person age=\"2\" goodAtHaskell=\"might become\">Eliezer</person>"
-- , "</people>"
-- ]
-- :}
--
-- >>> runConduit $ parseLBS def inputXml .| force "people required" parsePeople
-- [Person 25 "Michael" "yes",Person 2 "Eliezer" "might become"]
--
--
-- This module also supports streaming results using 'yield'.
-- This allows parser results to be processed using conduits
-- while a particular parser (e.g. 'many') is still running.
-- Without using streaming results, you have to wait until the parser finished
-- before you can process the result list. Large XML files might be easier
-- to process by using streaming results.
-- See http://stackoverflow.com/q/21367423/2597135 for a related discussion.
--
-- >>> import Data.Conduit.List as CL
-- >>> :{
-- let parsePeople' :: MonadThrow m => ConduitT Event Person m (Maybe ())
-- parsePeople' = tagNoAttr "people" $ manyYield parsePerson
-- :}
--
-- >>> runConduit $ parseLBS def inputXml .| force "people required" parsePeople' .| CL.mapM_ print
-- Person 25 "Michael" "yes"
-- Person 2 "Eliezer" "might become"
--
-- Previous versions of this module contained a number of more sophisticated
-- functions written by Aristid Breitkreuz and Dmitry Olshansky. To keep this
-- package simpler, those functions are being moved to a separate package. This
-- note will be updated with the name of the package(s) when available.
module Text.XML.Stream.Parse
( -- * Parsing XML files
parseBytes
, parseBytesPos
, parseText
, parseTextPos
, detectUtf
, parseFile
, parseLBS
-- ** Parser settings
, ParseSettings
, def
, DecodeEntities
, DecodeIllegalCharacters
, psDecodeEntities
, psDecodeIllegalCharacters
, psRetainNamespaces
, psEntityExpansionSizeLimit
-- *** Entity decoding
, decodeXmlEntities
, decodeHtmlEntities
-- * Event parsing
, tag
, tag'
, tagNoAttr
, tagIgnoreAttrs
, content
, contentMaybe
-- * Ignoring tags/trees
, ignoreEmptyTag
, ignoreTree
, ignoreContent
, ignoreTreeContent
, ignoreAnyTreeContent
-- * Streaming events
, takeContent
, takeTree
, takeTreeContent
, takeAnyTreeContent
-- * Tag name matching
, NameMatcher(..)
, matching
, anyOf
, anyName
-- * Attribute parsing
, AttrParser
, attr
, requireAttr
, optionalAttr
, requireAttrRaw
, optionalAttrRaw
, ignoreAttrs
-- * Combinators
, orE
, choose
, many
, many_
, manyIgnore
, many'
, force
-- * Streaming combinators
, manyYield
, manyYield'
, manyIgnoreYield
-- * Exceptions
, XmlException (..)
-- * Other types
, PositionRange
, EventPos
) where
import Conduit
import Control.Applicative (Alternative (empty, (<|>)),
Applicative (..), (<$>))
import qualified Control.Applicative as A
import Control.Arrow ((***))
import Control.Exception (Exception (..), SomeException)
import Control.Monad (ap, liftM, void)
import Control.Monad.Fix (fix)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT (..))
import Control.Monad.Trans.Resource (MonadResource, MonadThrow (..),
throwM)
import Data.Attoparsec.Text (Parser, anyChar, char, manyTill,
skipWhile, string, takeWhile,
takeWhile1, (<?>),
notInClass, skipMany, skipMany1,
satisfy, peekChar)
import qualified Data.Attoparsec.Text as AT
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Builder as Builder
import Data.Char (isSpace)
import Data.Conduit.Attoparsec (PositionRange, conduitParser)
import qualified Data.Conduit.Text as CT
import Data.Default.Class (Default (..))
import Data.List (foldl', intercalate)
import qualified Data.Map as Map
import Data.Maybe (fromMaybe, isNothing, mapMaybe)
import Data.String (IsString (..))
import Data.Text (Text, pack)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8With)
import Data.Text.Encoding.Error (lenientDecode)
import Data.Typeable (Typeable)
import Data.XML.Types (Content (..), Event (..),
ExternalID (..),
Instruction (..), Name (..))
import Prelude hiding (takeWhile)
import Text.XML.Stream.Token
-- $setup
-- >>> :set -XOverloadedStrings
-- >>> import Conduit
-- >>> import Control.Monad (void, join)
type EntityTable = [(Text, Text)]
tokenToEvent :: ParseSettings -> EntityTable -> [NSLevel] -> Token -> (EntityTable, [NSLevel], [Event])
tokenToEvent _ es n (TokenXMLDeclaration _) = (es, n, [])
tokenToEvent _ es n (TokenInstruction i) = (es, n, [EventInstruction i])
tokenToEvent ps es n (TokenBeginElement name as isClosed _) =
(es, n', if isClosed then [begin, end] else [begin])
where
l0 = case n of
[] -> NSLevel Nothing Map.empty
x:_ -> x
(as', l') = foldl' go (id, l0) as
go (front, l) (TName kpref kname, val) =
(addNS front, l'')
where
isPrefixed = kpref == Just "xmlns"
isUnprefixed = isNothing kpref && kname == "xmlns"
addNS
| not (psRetainNamespaces ps) && (isPrefixed || isUnprefixed) = id
| otherwise = (. ((tname, resolveEntities' ps es val):))
where
resolveEntities' ps' es' xs =
mapMaybe extractTokenContent
(resolveEntities ps' es'
(map TokenContent xs))
extractTokenContent (TokenContent c) = Just c
extractTokenContent _ = Nothing
tname
| isPrefixed = TName Nothing ("xmlns:" `T.append` kname)
| otherwise = TName kpref kname
l''
| isPrefixed =
l { prefixes = Map.insert kname (contentsToText val)
$ prefixes l }
| isUnprefixed =
l { defaultNS = if T.null $ contentsToText val
then Nothing
else Just $ contentsToText val }
| otherwise = l
n' = if isClosed then n else l' : n
fixAttName (name', val) = (tnameToName True l' name', val)
elementName = tnameToName False l' name
begin = EventBeginElement elementName $ map fixAttName $ as' []
end = EventEndElement elementName
tokenToEvent _ es n (TokenEndElement name) =
(es, n', [EventEndElement $ tnameToName False l name])
where
(l, n') =
case n of
[] -> (NSLevel Nothing Map.empty, [])
x:xs -> (x, xs)
tokenToEvent ps es n tok@(TokenContent c@(ContentEntity e))
= case lookup e es of
Just _ -> (es, n, concatMap toEvents newtoks)
Nothing -> (es, n, [EventContent c])
where
toEvents t =
let (_, _, events) = tokenToEvent ps [] n t
in events
newtoks = resolveEntities ps es [tok]
tokenToEvent _ es n (TokenContent c) = (es, n, [EventContent c])
tokenToEvent _ es n (TokenComment c) = (es, n, [EventComment c])
tokenToEvent _ es n (TokenDoctype t eid es') = (es ++ es', n, [EventBeginDoctype t eid, EventEndDoctype])
tokenToEvent _ es n (TokenCDATA t) = (es, n, [EventCDATA t])
resolveEntities :: ParseSettings
-> EntityTable
-> [Token]
-> [Token]
resolveEntities ps entities = foldr go []
where
go tok@(TokenContent (ContentEntity e)) toks
= case expandEntity entities e of
Just xs -> foldr go toks xs
Nothing -> tok : toks
go tok toks = tok : toks
expandEntity es e
| Just t <- lookup e es =
case AT.parseOnly (manyTill
(parseToken ps :: Parser Token)
AT.endOfInput) t of
Left _ -> Nothing
Right xs -> -- recursively expand
let es' = filter (\(x,_) -> x /= e) es
in fst <$> foldr (goent es') (Just ([], 0)) xs
-- we delete e from the entity map in resolving its contents,
-- to avoid infinite loops in recursive expansion.
| otherwise = Nothing
goent _ _ Nothing = Nothing
goent es (TokenContent (ContentEntity e)) (Just (cs, size))
= expandEntity es e >>= foldr (goent es) (Just (cs, size))
goent _ tok (Just (toks, size)) =
let toksize = fromIntegral $
L.length (Builder.toLazyByteString (tokenToBuilder tok))
in case size + toksize of
n | n > psEntityExpansionSizeLimit ps -> Nothing
| otherwise -> Just (tok:toks, n)
tnameToName :: Bool -> NSLevel -> TName -> Name
tnameToName _ _ (TName (Just "xml") name) =
Name name (Just "http://www.w3.org/XML/1998/namespace") (Just "xml")
tnameToName isAttr (NSLevel def' _) (TName Nothing name) =
Name name (if isAttr then Nothing else def') Nothing
tnameToName _ (NSLevel _ m) (TName (Just pref) name) =
case Map.lookup pref m of
Just ns -> Name name (Just ns) (Just pref)
Nothing -> Name name Nothing (Just pref) -- FIXME is this correct?
-- | Automatically determine which UTF variant is being used. This function
-- first checks for BOMs, removing them as necessary, and then check for the
-- equivalent of <?xml for each of UTF-8, UTF-16LE/BE, and UTF-32LE/BE. It
-- defaults to assuming UTF-8.
detectUtf :: MonadThrow m => ConduitT S.ByteString T.Text m ()
detectUtf =
conduit id
where
conduit front = await >>= maybe (return ()) (push front)
push front bss =
either conduit
(uncurry checkXMLDecl)
(getEncoding front bss)
getEncoding front bs'
| S.length bs < 4 =
Left (bs `S.append`)
| otherwise =
Right (bsOut, mcodec)
where
bs = front bs'
bsOut = S.append (S.drop toDrop x) y
(x, y) = S.splitAt 4 bs
(toDrop, mcodec) =
case S.unpack x of
[0x00, 0x00, 0xFE, 0xFF] -> (4, Just CT.utf32_be)
[0xFF, 0xFE, 0x00, 0x00] -> (4, Just CT.utf32_le)
0xFE : 0xFF: _ -> (2, Just CT.utf16_be)
0xFF : 0xFE: _ -> (2, Just CT.utf16_le)
0xEF : 0xBB: 0xBF : _ -> (3, Just CT.utf8)
[0x00, 0x00, 0x00, 0x3C] -> (0, Just CT.utf32_be)
[0x3C, 0x00, 0x00, 0x00] -> (0, Just CT.utf32_le)
[0x00, 0x3C, 0x00, 0x3F] -> (0, Just CT.utf16_be)
[0x3C, 0x00, 0x3F, 0x00] -> (0, Just CT.utf16_le)
_ -> (0, Nothing) -- Assuming UTF-8
checkXMLDecl :: MonadThrow m
=> S.ByteString
-> Maybe CT.Codec
-> ConduitT S.ByteString T.Text m ()
checkXMLDecl bs (Just codec) = leftover bs >> CT.decode codec
checkXMLDecl bs0 Nothing =
loop [] (AT.parse (parseToken def)) bs0
where
loop chunks0 parser nextChunk =
case parser $ decodeUtf8With lenientDecode nextChunk of
AT.Fail{} -> fallback
AT.Partial f -> await >>= maybe fallback (loop chunks f)
AT.Done _ (TokenXMLDeclaration attrs) -> findEncoding attrs
AT.Done{} -> fallback
where
chunks = nextChunk : chunks0
fallback = complete CT.utf8
complete codec = mapM_ leftover chunks >> CT.decode codec
findEncoding [] = fallback
findEncoding ((TName _ "encoding", [ContentText enc]):_) =
case T.toLower enc of
"iso-8859-1" -> complete CT.iso8859_1
"utf-8" -> complete CT.utf8
_ -> complete CT.utf8
findEncoding (_:xs) = findEncoding xs
type EventPos = (Maybe PositionRange, Event)
-- | Parses a byte stream into 'Event's. This function is implemented fully in
-- Haskell using attoparsec-text for parsing. The produced error messages do
-- not give line/column information, so you may prefer to stick with the parser
-- provided by libxml-enumerator. However, this has the advantage of not
-- relying on any C libraries.
--
-- This relies on 'detectUtf' to determine character encoding, and 'parseText'
-- to do the actual parsing.
parseBytes :: MonadThrow m
=> ParseSettings
-> ConduitT S.ByteString Event m ()
parseBytes = mapOutput snd . parseBytesPos
parseBytesPos :: MonadThrow m
=> ParseSettings
-> ConduitT S.ByteString EventPos m ()
parseBytesPos ps = detectUtf .| parseTextPos ps
dropBOM :: Monad m => ConduitT T.Text T.Text m ()
dropBOM =
await >>= maybe (return ()) push
where
push t =
case T.uncons t of
Nothing -> dropBOM
Just (c, cs) ->
let output
| c == '\xfeef' = cs
| otherwise = t
in yield output >> idConduit
idConduit = await >>= maybe (return ()) (\x -> yield x >> idConduit)
-- | Parses a character stream into 'Event's. This function is implemented
-- fully in Haskell using attoparsec-text for parsing. The produced error
-- messages do not give line/column information, so you may prefer to stick
-- with the parser provided by libxml-enumerator. However, this has the
-- advantage of not relying on any C libraries.
--
-- Since 1.2.4
parseText :: MonadThrow m => ParseSettings -> ConduitT T.Text Event m ()
parseText = mapOutput snd . parseTextPos
-- | Same as 'parseText', but includes the position of each event.
--
-- Since 1.2.4
parseTextPos :: MonadThrow m
=> ParseSettings
-> ConduitT T.Text EventPos m ()
parseTextPos de =
dropBOM
.| tokenize
.| toEventC de
.| addBeginEnd
where
tokenize = conduitToken de
addBeginEnd = yield (Nothing, EventBeginDocument) >> addEnd
addEnd = await >>= maybe
(yield (Nothing, EventEndDocument))
(\e -> yield e >> addEnd)
toEventC :: Monad m => ParseSettings -> ConduitT (PositionRange, Token) EventPos m ()
toEventC ps =
go [] []
where
go !es !levels =
await >>= maybe (return ()) push
where
push (position, token) =
mapM_ (yield . (,) (Just position)) events >> go es' levels'
where
(es', levels', events) = tokenToEvent ps es levels token
type DecodeEntities = Text -> Content
type DecodeIllegalCharacters = Int -> Maybe Char
data ParseSettings = ParseSettings
{ psDecodeEntities :: DecodeEntities
, psRetainNamespaces :: Bool
-- ^ Whether the original xmlns attributes should be retained in the parsed
-- values. For more information on motivation, see:
--
-- <https://github.com/snoyberg/xml/issues/38>
--
-- Default: False
--
-- Since 1.2.1
, psDecodeIllegalCharacters :: DecodeIllegalCharacters
-- ^ How to decode illegal character references (@&#[0-9]+;@ or @&#x[0-9a-fA-F]+;@).
--
-- Character references within the legal ranges defined by <https://www.w3.org/TR/REC-xml/#NT-Char the standard> are automatically parsed.
-- Others are passed to this function.
--
-- Default: @const Nothing@
--
-- Since 1.7.1
, psEntityExpansionSizeLimit :: Int
-- ^ Maximum number of characters allowed in expanding an
-- internal entity. This is intended to protect against the
-- billion laughs attack.
--
-- Default: @8192@
--
-- Since 1.9.1
}
instance Default ParseSettings where
def = ParseSettings
{ psDecodeEntities = decodeXmlEntities
, psRetainNamespaces = False
, psDecodeIllegalCharacters = const Nothing
, psEntityExpansionSizeLimit = 8192
}
conduitToken :: MonadThrow m => ParseSettings -> ConduitT T.Text (PositionRange, Token) m ()
conduitToken = conduitParser . parseToken
parseToken :: ParseSettings -> Parser Token
parseToken settings = do
mbc <- peekChar
case mbc of
Just '<' -> char '<' >> parseLt
_ -> TokenContent <$> parseContent settings False False
where
parseLt = do
mbc <- peekChar
case mbc of
Just '?' -> char' '?' >> parseInstr
Just '!' -> char' '!' >>
(parseComment <|> parseCdata <|> parseDoctype)
Just '/' -> char' '/' >> parseEnd
_ -> parseBegin
parseInstr = (do
name <- parseIdent
if name == "xml"
then do
as <- A.many $ parseAttribute settings
skipSpace
char' '?'
char' '>'
newline <|> return ()
return $ TokenXMLDeclaration as
else do
skipSpace
x <- T.pack <$> manyTill anyChar (string "?>")
return $ TokenInstruction $ Instruction name x)
<?> "instruction"
parseComment = (do
char' '-'
char' '-'
c <- T.pack <$> manyTill anyChar (string "-->")
return $ TokenComment c) <?> "comment"
parseCdata = (do
_ <- string "[CDATA["
t <- T.pack <$> manyTill anyChar (string "]]>")
return $ TokenCDATA t) <?> "CDATA"
parseDoctype = (do
_ <- string "DOCTYPE"
skipSpace
name <- parseName
let i =
case name of
TName Nothing x -> x
TName (Just x) y -> T.concat [x, ":", y]
skipSpace
eid <- fmap Just parsePublicID <|>
fmap Just parseSystemID <|>
return Nothing
skipSpace
mbc <- peekChar
ents <- case mbc of
Just '[' ->
do char' '['
ents <- parseDeclarations id
skipSpace
return ents
_ -> return []
char' '>'
newline <|> return ()
return $ TokenDoctype i eid ents) <?> "DOCTYPE"
parseDeclarations front = -- we ignore everything but ENTITY
(char' ']' >> return (front [])) <|>
(parseEntity >>= \f -> parseDeclarations (front . f)) <|>
(string "<!--" >> manyTill anyChar (string "-->") >>
parseDeclarations front) <|>
-- this clause handles directives like <!ELEMENT
-- and processing instructions:
(do char' '<'
skipMany
(void (takeWhile1 (notInClass "]<>'\"")) <|> void quotedText)
char' '>'
parseDeclarations front) <|>
(skipMany1 (satisfy (notInClass "]<>")) >>
parseDeclarations front)
parseEntity = (do
_ <- string "<!ENTITY"
skipSpace
isParameterEntity <- AT.option False (True <$ (char' '%' *> skipSpace))
i <- parseIdent
t <- quotedText
skipSpace
char' '>'
return $
if isParameterEntity
then id
else ((i, t):)) <?> "entity"
parsePublicID = PublicID <$> (string "PUBLIC" *> quotedText) <*> quotedText
parseSystemID = SystemID <$> (string "SYSTEM" *> quotedText)
quotedText = (do
skipSpace
between '"' <|> between '\'') <?> "quoted text"
between c = do
char' c
x <- takeWhile (/=c)
char' c
return x
parseEnd = (do
skipSpace
n <- parseName
skipSpace
char' '>'
return $ TokenEndElement n) <?> "close tag"
parseBegin = (do
skipSpace
n <- parseName
as <- A.many $ parseAttribute settings
skipSpace
isClose <- (char '/' >> skipSpace >> return True) <|> return False
char' '>'
return $ TokenBeginElement n as isClose 0) <?> "open tag"
parseAttribute :: ParseSettings -> Parser TAttribute
parseAttribute settings = (do
skipSpace
key <- parseName
skipSpace
char' '='
skipSpace
val <- squoted <|> dquoted
return (key, val)) <?> "attribute"
where
squoted = char '\'' *> manyTill (parseContent settings False True) (char '\'')
dquoted = char '"' *> manyTill (parseContent settings True False) (char '"')
parseName :: Parser TName
parseName =
(name <$> parseIdent <*> A.optional (char ':' >> parseIdent)) <?> "name"
where
name i1 Nothing = TName Nothing i1
name i1 (Just i2) = TName (Just i1) i2
parseIdent :: Parser Text
parseIdent = takeWhile1 valid <?> "identifier"
where
valid '&' = False
valid '<' = False
valid '>' = False
valid ':' = False
valid '?' = False
valid '=' = False
valid '"' = False
valid '\'' = False
valid '/' = False
valid ';' = False
valid '#' = False
valid c = not $ isXMLSpace c
parseContent :: ParseSettings
-> Bool -- break on double quote
-> Bool -- break on single quote
-> Parser Content
parseContent (ParseSettings decodeEntities _ decodeIllegalCharacters _) breakDouble breakSingle = parseReference <|> parseTextContent where
parseReference = do
char' '&'
t <- parseEntityRef <|> parseHexCharRef <|> parseDecCharRef
char' ';'
return t
parseEntityRef = do
TName ma b <- parseName
let name = maybe "" (`T.append` ":") ma `T.append` b
return $ case name of
"lt" -> ContentText "<"
"gt" -> ContentText ">"
"amp" -> ContentText "&"
"quot" -> ContentText "\""
"apos" -> ContentText "'"
_ -> decodeEntities name
parseHexCharRef = do
void $ string "#x"
n <- AT.hexadecimal
case toValidXmlChar n <|> decodeIllegalCharacters n of
Nothing -> fail "Invalid character from hexadecimal character reference."
Just c -> return $ ContentText $ T.singleton c
parseDecCharRef = do
void $ string "#"
n <- AT.decimal
case toValidXmlChar n <|> decodeIllegalCharacters n of
Nothing -> fail "Invalid character from decimal character reference."
Just c -> return $ ContentText $ T.singleton c
parseTextContent = ContentText <$> takeWhile1 valid <?> "text content"
valid '"' = not breakDouble
valid '\'' = not breakSingle
valid '&' = False -- amp
valid '<' = False -- lt
valid _ = True
-- | Is this codepoint a valid XML character? See
-- <https://www.w3.org/TR/xml/#charsets>. This is proudly XML 1.0 only.
toValidXmlChar :: Int -> Maybe Char
toValidXmlChar n
| any checkRange ranges = Just (toEnum n)
| otherwise = Nothing
where
--Inclusive lower bound, inclusive upper bound.
ranges :: [(Int, Int)]
ranges =
[ (0x9, 0xA)
, (0xD, 0xD)
, (0x20, 0xD7FF)
, (0xE000, 0xFFFD)
, (0x10000, 0x10FFFF)
]
checkRange (lb, ub) = lb <= n && n <= ub
skipSpace :: Parser ()
skipSpace = skipWhile isXMLSpace
-- | Determines whether a character is an XML white space. The list of
-- white spaces is given by
--
-- > S ::= (#x20 | #x9 | #xD | #xA)+
--
-- in <http://www.w3.org/TR/2008/REC-xml-20081126/#sec-common-syn>.
isXMLSpace :: Char -> Bool
isXMLSpace ' ' = True
isXMLSpace '\t' = True
isXMLSpace '\r' = True
isXMLSpace '\n' = True
isXMLSpace _ = False
newline :: Parser ()
newline = void $ (char '\r' >> char '\n') <|> char '\n'
char' :: Char -> Parser ()
char' = void . char
data ContentType = Ignore | IsContent Text | IsError String | NotContent
-- | Grabs the next piece of content if available. This function skips over any
-- comments, instructions or entities, and concatenates all content until the next start
-- or end tag.
contentMaybe :: MonadThrow m => ConduitT Event o m (Maybe Text)
contentMaybe = do
x <- peekC
case pc' x of
Ignore -> dropC 1 >> contentMaybe
IsContent t -> dropC 1 >> fmap Just (takeContents (t:))
IsError e -> lift $ throwM $ InvalidEntity e x
NotContent -> return Nothing
where
pc' Nothing = NotContent
pc' (Just x) = pc x
pc (EventContent (ContentText t)) = IsContent t
pc (EventContent (ContentEntity e)) = IsError $ "Unknown entity: " ++ show e
pc (EventCDATA t) = IsContent t
pc EventBeginElement{} = NotContent
pc EventEndElement{} = NotContent
pc EventBeginDocument{} = Ignore
pc EventEndDocument = Ignore
pc EventBeginDoctype{} = Ignore
pc EventEndDoctype = Ignore
pc EventInstruction{} = Ignore
pc EventComment{} = Ignore
takeContents front = do
x <- peekC
case pc' x of
Ignore -> dropC 1 >> takeContents front
IsContent t -> dropC 1 >> takeContents (front . (:) t)
IsError e -> lift $ throwM $ InvalidEntity e x
NotContent -> return $ T.concat $ front []
-- | Grabs the next piece of content. If none if available, returns 'T.empty'.
-- This is simply a wrapper around 'contentMaybe'.
content :: MonadThrow m => ConduitT Event o m Text
content = fromMaybe T.empty <$> contentMaybe
isWhitespace :: Event -> Bool
isWhitespace EventBeginDocument = True
isWhitespace EventEndDocument = True
isWhitespace EventBeginDoctype{} = True
isWhitespace EventEndDoctype = True
isWhitespace EventInstruction{} = True
isWhitespace (EventContent (ContentText t)) = T.all isSpace t
isWhitespace EventComment{} = True
isWhitespace (EventCDATA t) = T.all isSpace t
isWhitespace _ = False
-- | The most generic way to parse a tag. It takes a 'NameMatcher' to check whether
-- this is a correct tag name, an 'AttrParser' to handle attributes, and
-- then a parser to deal with content.
--
-- 'Events' are consumed if and only if the tag name and its attributes match.
--
-- This function automatically absorbs its balancing closing tag, and will
-- throw an exception if not all of the attributes or child elements are
-- consumed. If you want to allow extra attributes, see 'ignoreAttrs'.
--
-- This function automatically ignores comments, instructions and whitespace.
tag :: MonadThrow m
=> NameMatcher a -- ^ Check if this is a correct tag name
-- and return a value that can be used to get an @AttrParser@.
-- If this fails, the function will return @Nothing@
-> (a -> AttrParser b) -- ^ Given the value returned by the name checker, this function will
-- be used to get an @AttrParser@ appropriate for the specific tag.
-- If the @AttrParser@ fails, the function will also return @Nothing@
-> (b -> ConduitT Event o m c) -- ^ Handler function to handle the attributes and children
-- of a tag, given the value return from the @AttrParser@
-> ConduitT Event o m (Maybe c)
tag nameMatcher attrParser f = do
(x, leftovers) <- dropWS []
res <- case x of
Just (EventBeginElement name as) -> case runNameMatcher nameMatcher name of
Just y -> case runAttrParser' (attrParser y) as of
Left _ -> return Nothing
Right z -> do
z' <- f z
(a, _leftovers') <- dropWS []
case a of
Just (EventEndElement name')
| name == name' -> return (Just z')
_ -> lift $ throwM $ InvalidEndElement name a
Nothing -> return Nothing
_ -> return Nothing
case res of
-- Did not parse, put back all of the leading whitespace events and the
-- final observed event generated by dropWS
Nothing -> mapM_ leftover leftovers
-- Parse succeeded, discard all of those whitespace events and the
-- first parsed event
_ -> return ()
return res
where
-- Drop Events until we encounter a non-whitespace element. Return all of
-- the events consumed here (including the first non-whitespace event) so
-- that the calling function can treat them as leftovers if the parse fails
dropWS leftovers = do
x <- await
let leftovers' = maybe id (:) x leftovers
case isWhitespace <$> x of
Just True -> dropWS leftovers'
_ -> return (x, leftovers')
runAttrParser' p as =
case runAttrParser p as of
Left e -> Left e
Right ([], x) -> Right x
Right (attr', _) -> Left $ toException $ UnparsedAttributes attr'
-- | A simplified version of 'tag' where the 'NameMatcher' result isn't forwarded to the attributes parser.
--
-- Since 1.5.0
tag' :: MonadThrow m
=> NameMatcher a -> AttrParser b -> (b -> ConduitT Event o m c)
-> ConduitT Event o m (Maybe c)
tag' a b = tag a (const b)
-- | A further simplified tag parser, which requires that no attributes exist.
tagNoAttr :: MonadThrow m
=> NameMatcher a -- ^ Check if this is a correct tag name
-> ConduitT Event o m b -- ^ Handler function to handle the children of the matched tag
-> ConduitT Event o m (Maybe b)
tagNoAttr name f = tag' name (return ()) $ const f
-- | A further simplified tag parser, which ignores all attributes, if any exist
tagIgnoreAttrs :: MonadThrow m
=> NameMatcher a -- ^ Check if this is a correct tag name
-> ConduitT Event o m b -- ^ Handler function to handle the children of the matched tag
-> ConduitT Event o m (Maybe b)
tagIgnoreAttrs name f = tag' name ignoreAttrs $ const f
-- | Ignore an empty tag and all of its attributes.
-- This does not ignore the tag recursively
-- (i.e. it assumes there are no child elements).
-- This function returns @Just ()@ if the tag matched.
--
-- Since 1.5.0
ignoreEmptyTag :: MonadThrow m
=> NameMatcher a -- ^ Check if this is a correct tag name
-> ConduitT Event o m (Maybe ())
ignoreEmptyTag nameMatcher = tagIgnoreAttrs nameMatcher (return ())
ignored :: Monad m => ConduitT i o m ()
ignored = fix $ \recurse -> do
event <- await
case event of
Just _ -> recurse
_ -> return ()
-- | Same as `takeTree`, without yielding `Event`s.
--
-- >>> runConduit $ parseLBS def "<a>content</a><b></b>" .| (ignoreTree "a" ignoreAttrs >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "b", ...}) [],EventEndElement (Name {nameLocalName = "b", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "<a>content</a>" .| (ignoreTree "b" ignoreAttrs >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventContent (ContentText "content"),EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "content<a></a>" .| (ignoreTree anyName ignoreAttrs >> sinkList)
-- [EventContent (ContentText "content"),EventBeginElement (Name {nameLocalName = "a", ...}) [],EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- Since 1.9.0
ignoreTree :: MonadThrow m => NameMatcher a -> AttrParser b -> ConduitT Event o m (Maybe ())
ignoreTree nameMatcher attrParser = fuseUpstream (takeTree nameMatcher attrParser) ignored
-- | Same as `takeContent`, without yielding `Event`s.
--
-- >>> runConduit $ parseLBS def "<a>content</a>" .| (ignoreContent >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventContent (ContentText "content"),EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "content<a></a>" .| (ignoreContent >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "content<a></a>" .| (ignoreContent >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- Since 1.9.0
ignoreContent :: MonadThrow m => ConduitT Event o m (Maybe ())
ignoreContent = fuseUpstream takeContent ignored
-- | Same as `takeTreeContent`, without yielding `Event`s.
--
-- >>> runConduit $ parseLBS def "<a>content</a><b></b>" .| (ignoreTreeContent "a" ignoreAttrs >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "b", ...}) [],EventEndElement (Name {nameLocalName = "b", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "<a>content</a>" .| (ignoreTreeContent "b" ignoreAttrs >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventContent (ContentText "content"),EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "content<a></a>" .| (ignoreTreeContent anyName ignoreAttrs >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "a", ...}) [],EventEndElement (Name {nameLocalName = "a", ...}),EventEndDocument]
--
-- Since 1.5.0
ignoreTreeContent :: MonadThrow m => NameMatcher a -> AttrParser b -> ConduitT Event o m (Maybe ())
ignoreTreeContent namePred attrParser = fuseUpstream (takeTreeContent namePred attrParser) ignored
-- | Same as `takeAnyTreeContent`, without yielding `Event`s.
--
-- >>> runConduit $ parseLBS def "<a>content</a><b></b>" .| (ignoreAnyTreeContent >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "b", ...}) [],EventEndElement (Name {nameLocalName = "b", ...}),EventEndDocument]
--
-- >>> runConduit $ parseLBS def "text<b></b>" .| (ignoreAnyTreeContent >> sinkList)
-- [EventBeginElement (Name {nameLocalName = "b", ...}) [],EventEndElement (Name {nameLocalName = "b", ...}),EventEndDocument]
--
-- Since 1.5.0
ignoreAnyTreeContent :: MonadThrow m => ConduitT Event o m (Maybe ())
ignoreAnyTreeContent = fuseUpstream takeAnyTreeContent ignored
-- | Get the value of the first parser which returns 'Just'. If no parsers
-- succeed (i.e., return @Just@), this function returns 'Nothing'.
--
-- > orE a b = choose [a, b]
--
-- Warning: `orE` doesn't backtrack. See 'choose' for detailed explanation.
orE :: Monad m
=> ConduitT Event o m (Maybe a) -- ^ The first (preferred) parser
-> ConduitT Event o m (Maybe a) -- ^ The second parser, only executed if the first parser fails
-> ConduitT Event o m (Maybe a)
orE a b = a >>= \x -> maybe b (const $ return x) x
-- | Get the value of the first parser which returns 'Just'. If no parsers
-- succeed (i.e., return 'Just'), this function returns 'Nothing'.
--
-- Warning: 'choose' doesn't backtrack. If a parser consumed some events,
-- subsequent parsers will continue from the following events. This can be a
-- problem if parsers share an accepted prefix of events, so an earlier
-- (failing) parser will discard the events that the later parser could
-- potentially succeed on.
--
-- An other problematic case is using 'choose' to implement order-independent
-- parsing using a set of parsers, with a final trailing ignore-anything-else
-- action. In this case, certain trees might be skipped.
--
-- >>> :{
-- let parse2Tags name1 name2 = do
-- tag1 <- tagNoAttr name1 (pure ())
-- tag2 <- tagNoAttr name2 (pure tag1)
-- return $ join tag2
-- :}
--
-- >>> :{
-- runConduit $ parseLBS def "<a></a><b></b>" .| choose
-- [ parse2Tags "a" "b"
-- , parse2Tags "a" "c"
-- ]
-- :}
-- Just ()
--
-- >>> :{
-- runConduit $ parseLBS def "<a></a><b></b>" .| choose
-- [ parse2Tags "a" "c"
-- , parse2Tags "a" "b"
-- ]
-- :}
-- Nothing
choose :: Monad m
=> [ConduitT Event o m (Maybe a)] -- ^ List of parsers that will be tried in order.
-> ConduitT Event o m (Maybe a) -- ^ Result of the first parser to succeed, or @Nothing@
-- if no parser succeeded
choose [] = return Nothing
choose (i:is) = i >>= maybe (choose is) (return . Just)
-- | Force an optional parser into a required parser. All of the 'tag'
-- functions, 'attr', 'choose' and 'many' deal with 'Maybe' parsers. Use this when you
-- want to finally force something to happen.
force :: MonadThrow m
=> String -- ^ Error message
-> m (Maybe a) -- ^ Optional parser to be forced
-> m a
force msg i = i >>= maybe (throwM $ XmlException msg Nothing) return
-- | A helper function which reads a file from disk using 'enumFile', detects
-- character encoding using 'detectUtf', parses the XML using 'parseBytes', and
-- then hands off control to your supplied parser.
parseFile :: MonadResource m
=> ParseSettings
-> FilePath
-> ConduitT i Event m ()
parseFile ps fp = sourceFile fp .| transPipe liftIO (parseBytes ps)