Debian Codegraph @

src/Text/XmlHtml/XML/Parse.hs

raw
1 {-# LANGUAGE OverloadedStrings #-}
2
3 module Text.XmlHtml.XML.Parse where
4
5 import Control.Applicative
6 import Control.Monad
7 import Data.Char
8 import Data.List
9 import Data.Maybe
10 import Text.XmlHtml.Common
11 import Text.XmlHtml.TextParser
12
13 import qualified Text.Parsec as P
14
15 import Data.Map (Map)
16 import qualified Data.Map as M
17
18 import Data.Text (Text)
19 import qualified Data.Text as T
20
21
22 ------------------------------------------------------------------------------
23 -- | This is my best guess as to the best rule for handling document fragments
24 -- for processing. It is essentially modeled after document, but allowing
25 -- multiple nodes.
26 docFragment :: Encoding -> Parser Document
27 docFragment e = do
28 (dt, nodes1) <- prolog
29 nodes2 <- content
30 return $ XmlDocument e dt (nodes1 ++ nodes2)
31
32
33 ------------------------------------------------------------------------------
34 -- Everything from here forward is translated from the XML specification. --
35 ------------------------------------------------------------------------------
36
37 {-
38 Map from numbered productions in the XML specification to symbols here:
39
40 PROD SPEC NAME PARSER NAME NOTES
41 -----|------------------|---------------------|-------
42 [1] document document
43 [2] Char {2}
44 [3] S whiteSpace
45 [4] NameStartChar isNameStartChar {1}
46 [4a] NameChar isNameChar {1}
47 [5] Name name
48 [6] Names names
49 [7] Nmtoken nmtoken
50 [8] Nmtokens nmtokens
51 [9] EntityValue {4}
52 [10] AttValue attrValue
53 [11] SystemLiteral systemLiteral
54 [12] PubidLiteral pubIdLiteral
55 [13] PubidChar isPubIdChar {1}
56 [14] CharData charData
57 [15] Comment comment
58 [16] PI processingInstruction
59 [17] PITarget piTarget
60 [18] CDSect cdSect
61 [19] CDStart cdSect {3}
62 [20] CData cdSect {3}
63 [21] CDEnd cdSect {3}
64 [22] prolog prolog
65 [23] XMLDecl xmlDecl
66 [24] VersionInfo versionInfo
67 [25] Eq eq
68 [26] VersionNum versionInfo {3}
69 [27] Misc misc
70 [28] doctypedecl docTypeDecl
71 [28a] DeclSep {4}
72 [28b] intSubset {4}
73 [29] markupdecl {4}
74 [30] extSubset {4}
75 [31] extSubsetDecl {4}
76 [32] SDDecl sdDecl
77 [39] element element
78 [40] STag emptyOrStartTag
79 [41] Attribute attribute
80 [42] ETag endTag
81 [43] content content
82 [44] EmptyElemTag emptyOrStartTag
83 [45] elementDecl {4}
84 [46] contentSpec {4}
85 [47] children {4}
86 [48] cp {4}
87 [49] choice {4}
88 [50] seq {4}
89 [51] Mixed {4}
90 [52] AttlistDecl {4}
91 [53] AttDef {4}
92 [54] AttType {4}
93 [55] StringType {4}
94 [56] TokenizedType {4}
95 [57] EnumeratedType {4}
96 [58] NotationType {4}
97 [59] Enumeration {4}
98 [60] DefaultDecl {4}
99 [61] conditionalSect {4}
100 [62] includeSect {4}
101 [63] ignoreSect {4}
102 [64] ignoreSectContents {4}
103 [65] Ignore {4}
104 [66] CharRef charRef
105 [67] Reference reference
106 [68] EntityRef entityRef
107 [69] PEReference {4}
108 [70] EntityDecl {4}
109 [71] GEDecl {4}
110 [72] PEDecl {4}
111 [73] EntityDef {4}
112 [74] PEDef {4}
113 [75] ExternalID externalID
114 [76] NDataDecl {4}
115 [77] TextDecl textDecl
116 [78] extParsedEnt extParsedEnt
117 [80] EncodingDecl encodingDecl
118 [81] EncName encodingDecl {3}
119 [82] NotationDecl {4}
120 [83] PublicID {4}
121 [84] Letter {5}
122 [85] BaseChar {5}
123 [86] Ideographic {5}
124 [87] CombiningChar {5}
125 [88] Digit {5}
126 [89] Extender {5}
127
128 Notes:
129 {1} - These productions match single characters, and so are
130 implemented as predicates instead of parsers.
131 {3} - Denotes a production which is not exposed as a top-level symbol
132 because it is trivial and included in another definition.
133 {4} - This module does not contain a parser for the DTD subsets, so
134 grammar that occurs only in DTD subsets is not defined.
135 {5} - These are orphaned productions for character classes.
136 -}
137
138
139 ------------------------------------------------------------------------------
140 whiteSpace :: Parser ()
141 whiteSpace = some (P.satisfy (`elem` [' ','\t','\r','\n'])) *> return ()
142
143
144 ------------------------------------------------------------------------------
145 isNameStartChar :: Char -> Bool
146 isNameStartChar c | c == ':' = True
147 | c == '_' = True
148 | c >= 'a' && c <= 'z' = True
149 | c >= 'A' && c <= 'Z' = True
150 | c >= '\xc0' && c <= '\xd6' = True
151 | c >= '\xd8' && c <= '\xf6' = True
152 | c >= '\xf8' && c <= '\x2ff' = True
153 | c >= '\x370' && c <= '\x37d' = True
154 | c >= '\x37f' && c <= '\x1fff' = True
155 | c >= '\x200c' && c <= '\x200d' = True
156 | c >= '\x2070' && c <= '\x218f' = True
157 | c >= '\x2c00' && c <= '\x2fef' = True
158 | c >= '\x3001' && c <= '\xd7ff' = True
159 | c >= '\xf900' && c <= '\xfdcf' = True
160 | c >= '\xfdf0' && c <= '\xfffd' = True
161 | c >= '\x10000' && c <= '\xeffff' = True
162 | otherwise = False
163
164
165 ------------------------------------------------------------------------------
166 isNameChar :: Char -> Bool
167 isNameChar c | isNameStartChar c = True
168 | c == '-' = True
169 | c == '.' = True
170 | c == '\xb7' = True
171 | c >= '0' && c <= '9' = True
172 | c >= '\x300' && c <= '\x36f' = True
173 | c >= '\x203f' && c <= '\x2040' = True
174 | otherwise = False
175
176
177 ------------------------------------------------------------------------------
178 name :: Parser Text
179 name = do
180 c <- P.satisfy isNameStartChar
181 r <- takeWhile0 isNameChar
182 return $ T.cons c r
183
184
185 ------------------------------------------------------------------------------
186 attrValue :: Parser Text
187 attrValue = fmap T.concat (singleQuoted <|> doubleQuoted)
188 where
189 singleQuoted = P.char '\'' *> refTill ['<','&','\''] <* P.char '\''
190 doubleQuoted = P.char '"' *> refTill ['<','&','"'] <* P.char '"'
191 refTill end = many (takeWhile1 (not . (`elem` end)) <|> reference)
192
193
194 ------------------------------------------------------------------------------
195 systemLiteral :: Parser Text
196 systemLiteral = singleQuoted <|> doubleQuoted
197 where
198 singleQuoted = do
199 _ <- P.char '\''
200 x <- takeWhile0 (not . (== '\''))
201 _ <- P.char '\''
202 return x
203 doubleQuoted = do
204 _ <- P.char '\"'
205 x <- takeWhile0 (not . (== '\"'))
206 _ <- P.char '\"'
207 return x
208
209
210 ------------------------------------------------------------------------------
211 pubIdLiteral :: Parser Text
212 pubIdLiteral = singleQuoted <|> doubleQuoted
213 where
214 singleQuoted = do
215 _ <- P.char '\''
216 x <- takeWhile0 (\c -> isPubIdChar c && c /= '\'')
217 _ <- P.char '\''
218 return x
219 doubleQuoted = do
220 _ <- P.char '\"'
221 x <- takeWhile0 isPubIdChar
222 _ <- P.char '\"'
223 return x
224
225
226 ------------------------------------------------------------------------------
227 isPubIdChar :: Char -> Bool
228 isPubIdChar c | c >= 'a' && c <= 'z' = True
229 | c >= 'A' && c <= 'Z' = True
230 | c >= '0' && c <= '9' = True
231 | c `elem` otherChars = True
232 | otherwise = False
233 where
234 otherChars = " \r\n-\'()+,./:=?;!*#@$_%" :: [Char]
235
236 ------------------------------------------------------------------------------
237 -- | The requirement to not contain "]]>" is for SGML compatibility. We
238 -- deliberately choose to not enforce it. This makes the parser accept
239 -- strictly more documents than a standards-compliant parser.
240 charData :: Parser Node
241 charData = TextNode <$> takeWhile1 (not . (`elem` ['<','&']))
242
243
244 ------------------------------------------------------------------------------
245 comment :: Parser (Maybe Node)
246 comment = text "<!--" *> (Just <$> Comment <$> commentText) <* text "-->"
247 where
248 commentText = fmap T.concat $ many $
249 nonDash <|> P.try (T.cons <$> P.char '-' <*> nonDash)
250 nonDash = takeWhile1 (not . (== '-'))
251
252
253 ------------------------------------------------------------------------------
254 -- | Always returns Nothing since there's no representation for a PI in the
255 -- document tree.
256 processingInstruction :: Parser (Maybe Node)
257 processingInstruction = do
258 _ <- text "<?"
259 _ <- piTarget
260 _ <- emptyEnd <|> contentEnd
261 return Nothing
262 where
263 emptyEnd = P.try (P.string "?>")
264 contentEnd = P.try $ do
265 _ <- whiteSpace
266 P.manyTill P.anyChar (P.try $ text "?>")
267
268 ------------------------------------------------------------------------------
269 piTarget :: Parser ()
270 piTarget = do
271 n <- name
272 when (T.map toLower n == "xml") $ fail "xml declaration can't occur here"
273
274
275 ------------------------------------------------------------------------------
276 cdata :: [Char] -> Parser a -> Parser Node
277 cdata cs end = TextNode <$> T.concat <$> P.manyTill part end
278 where part = takeWhile1 (not . (`elem` cs))
279 <|> T.singleton <$> P.anyChar
280
281
282 ------------------------------------------------------------------------------
283 cdSect :: Parser (Maybe Node)
284 cdSect = Just <$> do
285 _ <- text "<![CDATA["
286 cdata "]" (text "]]>")
287
288
289 ------------------------------------------------------------------------------
290 prolog :: Parser (Maybe DocType, [Node])
291 prolog = do
292 _ <- optional xmlDecl
293 nodes1 <- many misc
294 rest <- optional $ do
295 dt <- docTypeDecl
296 nodes2 <- many misc
297 return (dt, nodes2)
298 case rest of
299 Nothing -> return (Nothing, catMaybes nodes1)
300 Just (dt, nodes2) -> return (Just dt, catMaybes (nodes1 ++ nodes2))
301
302
303 ------------------------------------------------------------------------------
304 -- | Return value is the encoding, if present.
305 xmlDecl :: Parser (Maybe Text)
306 xmlDecl = do
307 _ <- text "<?xml"
308 _ <- versionInfo
309 e <- optional encodingDecl
310 _ <- optional sdDecl
311 _ <- optional whiteSpace
312 _ <- text "?>"
313 return e
314
315
316 ------------------------------------------------------------------------------
317 versionInfo :: Parser ()
318 versionInfo = do
319 whiteSpace *> text "version" *> eq *> (singleQuoted <|> doubleQuoted)
320 where
321 singleQuoted = P.char '\'' *> versionNum <* P.char '\''
322 doubleQuoted = P.char '\"' *> versionNum <* P.char '\"'
323 versionNum = do
324 _ <- text "1."
325 _ <- some (P.satisfy (\c -> c >= '0' && c <= '9'))
326 return ()
327
328
329 ------------------------------------------------------------------------------
330 eq :: Parser ()
331 eq = optional whiteSpace *> P.char '=' *> optional whiteSpace *> return ()
332
333
334 ------------------------------------------------------------------------------
335 misc :: Parser (Maybe Node)
336 misc = comment <|> processingInstruction <|> (whiteSpace *> return Nothing)
337
338
339 ------------------------------------------------------------------------------
340 -- | Internal subset is parsed, but ignored since we don't have data types to
341 -- store it.
342 docTypeDecl :: Parser DocType
343 docTypeDecl = do
344 _ <- text "<!DOCTYPE"
345 whiteSpace
346 tag <- name
347 _ <- optional whiteSpace
348 extid <- externalID
349 _ <- optional whiteSpace
350 intsub <- internalDoctype
351 _ <- P.char '>'
352 return (DocType tag extid intsub)
353
354
355 ------------------------------------------------------------------------------
356 -- | States for the DOCTYPE internal subset state machine.
357 data InternalDoctypeState = IDSStart
358 | IDSScanning Int
359 | IDSInQuote Int Char
360 | IDSCommentS1 Int
361 | IDSCommentS2 Int
362 | IDSCommentS3 Int
363 | IDSComment Int
364 | IDSCommentD1 Int
365 | IDSCommentE1 Int
366
367
368 ------------------------------------------------------------------------------
369 -- | Internal DOCTYPE subset. We don't actually parse this; just scan through
370 -- and look for the end, and store it in a block of text.
371 internalDoctype :: Parser InternalSubset
372 internalDoctype = InternalText <$> T.pack <$> scanText (dfa IDSStart)
373 <|> return NoInternalSubset
374 where dfa IDSStart '[' = ScanNext (dfa (IDSScanning 0))
375 dfa IDSStart _ = ScanFail "Not a DOCTYPE internal subset"
376 dfa (IDSInQuote n c) d
377 | c == d = ScanNext (dfa (IDSScanning n))
378 | otherwise = ScanNext (dfa (IDSInQuote n c))
379 dfa (IDSScanning n) '[' = ScanNext (dfa (IDSScanning (n+1)))
380 dfa (IDSScanning 0) ']' = ScanFinish
381 dfa (IDSScanning n) ']' = ScanNext (dfa (IDSScanning (n-1)))
382 dfa (IDSScanning n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
383 dfa (IDSScanning n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
384 dfa (IDSScanning n) '<' = ScanNext (dfa (IDSCommentS1 n))
385 dfa (IDSScanning n) _ = ScanNext (dfa (IDSScanning n))
386 dfa (IDSCommentS1 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
387 dfa (IDSCommentS1 0) ']' = ScanFinish
388 dfa (IDSCommentS1 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
389 dfa (IDSCommentS1 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
390 dfa (IDSCommentS1 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
391 dfa (IDSCommentS1 n) '!' = ScanNext (dfa (IDSCommentS2 n))
392 dfa (IDSCommentS1 n) _ = ScanNext (dfa (IDSScanning n))
393 dfa (IDSCommentS2 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
394 dfa (IDSCommentS2 0) ']' = ScanFinish
395 dfa (IDSCommentS2 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
396 dfa (IDSCommentS2 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
397 dfa (IDSCommentS2 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
398 dfa (IDSCommentS2 n) '-' = ScanNext (dfa (IDSCommentS3 n))
399 dfa (IDSCommentS2 n) _ = ScanNext (dfa (IDSScanning n))
400 dfa (IDSCommentS3 n) '[' = ScanNext (dfa (IDSScanning (n+1)))
401 dfa (IDSCommentS3 0) ']' = ScanFinish
402 dfa (IDSCommentS3 n) ']' = ScanNext (dfa (IDSScanning (n-1)))
403 dfa (IDSCommentS3 n) '\'' = ScanNext (dfa (IDSInQuote n '\''))
404 dfa (IDSCommentS3 n) '\"' = ScanNext (dfa (IDSInQuote n '\"'))
405 dfa (IDSCommentS3 n) '-' = ScanNext (dfa (IDSComment n))
406 dfa (IDSCommentS3 n) _ = ScanNext (dfa (IDSScanning n))
407 dfa (IDSComment n) '-' = ScanNext (dfa (IDSCommentD1 n))
408 dfa (IDSComment n) _ = ScanNext (dfa (IDSComment n))
409 dfa (IDSCommentD1 n) '-' = ScanNext (dfa (IDSCommentE1 n))
410 dfa (IDSCommentD1 n) _ = ScanNext (dfa (IDSComment n))
411 dfa (IDSCommentE1 n) '>' = ScanNext (dfa (IDSScanning n))
412 dfa (IDSCommentE1 _) _ = ScanFail "Poorly formatted comment"
413
414
415 ------------------------------------------------------------------------------
416 sdDecl :: Parser ()
417 sdDecl = do
418 _ <- P.try $ whiteSpace *> text "standalone"
419 eq
420 _ <- single <|> double
421 return ()
422 where
423 single = P.char '\'' *> yesno <* P.char '\''
424 double = P.char '\"' *> yesno <* P.char '\"'
425 yesno = text "yes" <|> text "no"
426
427
428 ------------------------------------------------------------------------------
429 element :: Parser Node
430 element = do
431 (t,a,b) <- emptyOrStartTag
432 if b then return (Element t a [])
433 else nonEmptyElem t a
434 where
435 nonEmptyElem t a = do
436 c <- content
437 endTag t
438 return (Element t a c)
439
440
441 ------------------------------------------------------------------------------
442 -- | Results are (tag name, attributes, isEmpty)
443 emptyOrStartTag :: Parser (Text, [(Text, Text)], Bool)
444 emptyOrStartTag = do
445 t <- P.try $ P.char '<' *> name
446 a <- many $ P.try $ do
447 whiteSpace
448 attribute
449 when (hasDups a) $ fail "Duplicate attribute names in element"
450 _ <- optional whiteSpace
451 e <- optional (P.char '/')
452 _ <- P.char '>'
453 return (t, a, isJust e)
454 where
455 hasDups a = length (nub (map fst a)) < length a
456
457
458 ------------------------------------------------------------------------------
459 attribute :: Parser (Text, Text)
460 attribute = do
461 n <- name
462 eq
463 v <- attrValue
464 return (n,v)
465
466
467 ------------------------------------------------------------------------------
468 endTag :: Text -> Parser ()
469 endTag s = do
470 _ <- text "</"
471 t <- name
472 when (s /= t) $ fail $ "mismatched tags: </" ++ T.unpack t ++
473 "> found inside <" ++ T.unpack s ++ "> tag"
474 _ <- optional whiteSpace
475 _ <- text ">"
476 return ()
477
478
479 ------------------------------------------------------------------------------
480 content :: Parser [Node]
481 content = do
482 n <- optional charData
483 ns <- fmap concat $ many $ do
484 s <- ((Just <$> TextNode <$> reference)
485 <|> cdSect
486 <|> processingInstruction
487 <|> comment
488 <|> fmap Just element)
489 t <- optional charData
490 return [s,t]
491 return $ coalesceText $ catMaybes (n:ns)
492 where
493 coalesceText (TextNode s : TextNode t : ns)
494 = coalesceText (TextNode (T.append s t) : ns)
495 coalesceText (n:ns)
496 = n : coalesceText ns
497 coalesceText []
498 = []
499
500
501 ------------------------------------------------------------------------------
502 charRef :: Parser Text
503 charRef = hexCharRef <|> decCharRef
504 where
505 decCharRef = do
506 _ <- text "&#"
507 ds <- some digit
508 _ <- P.char ';'
509 c <- safeChr $ foldl' (\a b -> 10 * a + b) 0 ds
510 when (not (isValidChar c)) $ fail $
511 "Reference is not a valid character"
512 return $ T.singleton c
513 where
514 digit = do
515 d <- P.satisfy (\c -> c >= '0' && c <= '9')
516 return (ord d - ord '0')
517 hexCharRef = do
518 _ <- text "&#x"
519 ds <- some digit
520 _ <- P.char ';'
521 c <- safeChr $ foldl' (\a b -> 16 * a + b) 0 ds
522 when (not (isValidChar c)) $ fail $
523 "Reference is not a valid character"
524 return $ T.singleton c
525 where
526 digit = num <|> upper <|> lower
527 num = do
528 d <- P.satisfy (\c -> c >= '0' && c <= '9')
529 return (ord d - ord '0')
530 upper = do
531 d <- P.satisfy (\c -> c >= 'A' && c <= 'F')
532 return (10 + ord d - ord 'A')
533 lower = do
534 d <- P.satisfy (\c -> c >= 'a' && c <= 'f')
535 return (10 + ord d - ord 'a')
536
537
538 ------------------------------------------------------------------------------
539 reference :: Parser Text
540 reference = charRef <|> entityRef
541
542
543 ------------------------------------------------------------------------------
544 entityRef :: Parser Text
545 entityRef = do
546 _ <- P.char '&'
547 n <- name
548 _ <- P.char ';'
549 case M.lookup n entityRefLookup of
550 Nothing -> fail $ "Unknown entity reference: " ++ T.unpack n
551 Just t -> return t
552 where
553 entityRefLookup :: Map Text Text
554 entityRefLookup = M.fromList [
555 ("amp", "&"),
556 ("lt", "<"),
557 ("gt", ">"),
558 ("apos", "\'"),
559 ("quot", "\"")
560 ]
561
562
563 ------------------------------------------------------------------------------
564 externalID :: Parser ExternalID
565 externalID = systemID <|> publicID <|> return NoExternalID
566 where
567 systemID = do
568 _ <- text "SYSTEM"
569 whiteSpace
570 fmap System systemLiteral
571 publicID = do
572 _ <- text "PUBLIC"
573 whiteSpace
574 pid <- pubIdLiteral
575 whiteSpace
576 sid <- systemLiteral
577 return (Public pid sid)
578
579
580 ------------------------------------------------------------------------------
581 encodingDecl :: Parser Text
582 encodingDecl = do
583 _ <- P.try $ whiteSpace *> text "encoding"
584 _ <- eq
585 singleQuoted <|> doubleQuoted
586 where
587 singleQuoted = P.char '\'' *> encName <* P.char '\''
588 doubleQuoted = P.char '\"' *> encName <* P.char '\"'
589 encName = do
590 c <- P.satisfy isEncStart
591 cs <- takeWhile0 isEnc
592 return (T.cons c cs)
593 isEncStart c | c >= 'A' && c <= 'Z' = True
594 | c >= 'a' && c <= 'z' = True
595 | otherwise = False
596 isEnc c | c >= 'A' && c <= 'Z' = True
597 | c >= 'a' && c <= 'z' = True
598 | c >= '0' && c <= '9' = True
599 | c `elem` ['.','_','-'] = True
600 | otherwise = False
601