]> Git — Sourcephile - doclang.git/blob - Language/TCT/Write/XML.hs
Fix xmlify NodePair.
[doclang.git] / Language / TCT / Write / XML.hs
1 {-# LANGUAGE FlexibleContexts #-}
2 {-# LANGUAGE FlexibleInstances #-}
3 {-# LANGUAGE OverloadedLists #-}
4 {-# LANGUAGE OverloadedStrings #-}
5 {-# LANGUAGE ViewPatterns #-}
6 {-# OPTIONS_GHC -fno-warn-orphans #-}
7 module Language.TCT.Write.XML where
8
9 import Control.Monad (Monad(..))
10 import Data.Bool
11 import Data.Default.Class (Default(..))
12 import Data.Eq (Eq(..))
13 import Data.Foldable (Foldable(..))
14 import Data.Function (($), (.))
15 import Data.Functor ((<$>), (<$), ($>))
16 import Data.Maybe (Maybe(..))
17 import Data.Monoid (Monoid(..))
18 import Data.Ord (Ord(..))
19 import Data.Semigroup (Semigroup(..))
20 import Data.Sequence (Seq, ViewL(..), ViewR(..), (<|))
21 import Data.Set (Set)
22 import Data.TreeSeq.Strict (Tree(..), tree0)
23 import Data.Tuple (uncurry)
24 import Prelude (Num(..), undefined)
25 import qualified Data.Char as Char
26 import qualified Data.List as List
27 import qualified Data.Sequence as Seq
28 import qualified Data.Text.Lazy as TL
29 import qualified Language.TCT.Write.Plain as Plain
30 import qualified System.FilePath as FP
31
32 -- import Language.TCT.Debug
33 import Language.TCT.Utils
34 import Language.TCT hiding (Parser)
35 import Language.XML
36 import Text.Blaze.XML ()
37
38 -- | Main entry point
39 --
40 -- NOTE: 'XmlNode' are still annotated with 'Cell',
41 -- but nothing is done to preserve any ordering amongst them,
42 -- because 'Node's sometimes need to be reordered
43 -- (eg. about/title may have a title from the section before,
44 -- hence outside of about).
45 -- Still holding: @'cell_begin' < 'cell_end'@ and 'Cell' nesting.
46 document :: Roots -> XMLs
47 document doc =
48 -- (`S.evalState` def) $
49 case Seq.viewl doc of
50 sec@(Tree (unCell -> NodeHeader HeaderSection{}) _body) :< foot ->
51 let (titles, content) = partitionSection sec in
52 case Seq.viewl titles of
53 (unTree -> Cell bt et _) :< _ ->
54 xmlify def
55 { inh_titles = titles
56 , inh_figure = True
57 } contentWithAbout <>
58 xmlify def foot
59 where
60 contentWithAbout =
61 case Seq.findIndexL isAbout content of
62 Nothing -> Tree (Cell bt et $ NodeHeader $ HeaderColon "about" "") mempty <| content
63 Just{} -> content
64 isAbout = \case
65 (unTree -> (unCell -> NodeHeader (HeaderColon "about" _wh))) -> True
66 _ -> False
67 _ -> xmlify def doc
68 _ -> xmlify def doc
69
70 partitionSection :: Root -> (Roots, Roots)
71 partitionSection (Tree (unCell -> NodeHeader (HeaderSection lvlPar)) body) =
72 case Seq.viewl body of
73 EmptyL -> mempty
74 title@(unTree -> Cell _bt et NodePara) :< rest ->
75 let (subtitles, content) = spanlSubtitles et rest in
76 (title <| (subtitles >>= subTrees), content)
77 where
78 spanlSubtitles ep ts =
79 case Seq.viewl ts of
80 sub@(unTree -> Cell bs es (NodeHeader (HeaderSection lvlSub))) :< rs
81 | lvlSub <= lvlPar
82 , pos_line bs - pos_line ep <= 1 ->
83 let (subs, ts') = spanlSubtitles es rs in
84 (sub <| subs, ts')
85 _ -> (mempty, ts)
86 _ -> (mempty, body)
87 partitionSection _ = mempty
88
89 -- * Type 'Inh'
90 data Inh
91 = Inh
92 { inh_figure :: Bool
93 , inh_para :: [Inh -> Root -> XML]
94 , inh_titles :: Roots
95 }
96 instance Default Inh where
97 def = Inh
98 { inh_figure = False
99 , inh_para = List.repeat elementPara
100 , inh_titles = mempty
101 }
102
103 -- ** 'inh_para'
104 elementPara :: Inh -> Root -> XML
105 elementPara inh (Tree c ts) = Tree (XmlElem "para" <$ c) $ xmlify inh ts
106
107 elementTitle :: Inh -> Root -> XML
108 elementTitle inh (Tree c ts) = Tree (XmlElem "title" <$ c) $ xmlify inh ts
109
110 elementName :: Inh -> Root -> XML
111 elementName inh (Tree c ts) = Tree (XmlElem "name" <$ c) $ xmlify inh ts
112
113 attributeName :: Inh -> Root -> XML
114 attributeName _inh (Tree c ts) = tree0 (XmlAttr "name" (Plain.document ts) <$ c)
115
116 -- * Class 'Xmlify'
117 class Xmlify a where
118 xmlify :: Inh -> a -> XMLs
119 instance Xmlify Roots where
120 xmlify inh roots =
121 case Seq.viewl roots of
122 EmptyL -> mempty
123 r@(Tree cr@(Cell _br _er nr) ts) :< rs ->
124 case nr of
125 ----------------------
126 -- NOTE: HeaderColon becomes parent
127 -- of any continuous following-sibling HeaderBar or HeaderGreat
128 NodeHeader (HeaderColon n _wh)
129 | (span, rest) <- spanlHeaderColon rs
130 , not $ null span ->
131 xmlify inh (Tree cr (ts<>span)) <>
132 xmlify inh rest
133 where
134 spanlHeaderColon :: Roots -> (Roots, Roots)
135 spanlHeaderColon =
136 Seq.spanl $ \case
137 Tree (unCell -> NodeHeader (HeaderBar m _)) _ -> m == n
138 Tree (unCell -> NodeHeader (HeaderGreat m _)) _ -> m == n
139 _ -> False
140 ----------------------
141 -- NOTE: gather HeaderBrackets
142 NodeHeader HeaderBrackets{}
143 | (span,rest) <- spanlBrackets roots
144 , not (null span) ->
145 (<| xmlify inh rest) $
146 element "references" $
147 span >>= xmlify inh
148 where
149 spanlBrackets :: Roots -> (Roots, Roots)
150 spanlBrackets =
151 Seq.spanl $ \case
152 Tree (unCell -> NodeHeader HeaderBrackets{}) _ -> True
153 _ -> False
154 ----------------------
155 -- NOTE: merge adjacent NodeText-s, shouldn't be needed, but just in case.
156 NodeText x
157 | Tree (cy@(unCell -> NodeText y)) ys :< rs' <- Seq.viewl rs ->
158 xmlify inh $ Tree (NodeText <$> (x <$ cr) <> (y <$ cy)) (ts <> ys) <| rs'
159 ----------------------
160 -- NOTE: detect [some text](http://some.url) or [SomeRef]
161 NodePair PairParen
162 | Tree (Cell bb eb (NodePair PairBracket)) bracket :< rs' <- Seq.viewl rs ->
163 (<| xmlify inh rs') $
164 case bracket of
165 (toList -> [unTree -> Cell bl el (NodeToken (TokenLink lnk))]) ->
166 element "eref" $
167 xmlAttrs [Cell bl el ("to",lnk)] <>
168 xmlify inh ts
169 _ ->
170 element "rref" $
171 xmlAttrs [Cell bb eb ("to",Plain.document bracket)] <>
172 xmlify inh ts
173 ----------------------
174 -- NOTE: gather HeaderDash
175 _ | (span, rest) <- spanlItems (==HeaderDash) roots
176 , not $ null span ->
177 (<| xmlify inh rest) $
178 element "ul" $
179 span >>= xmlify inh{inh_para=List.repeat elementPara}
180 ----------------------
181 -- NOTE: gather HeaderDot
182 | (span,rest) <- spanlItems (\case HeaderDot{} -> True; _ -> False) roots
183 , not $ null span ->
184 (<| xmlify inh rest) $
185 element "ol" $
186 span >>= xmlify inh{inh_para=List.repeat elementPara}
187 where
188 spanlItems :: (Header -> Bool) -> Roots -> (Roots, Roots)
189 spanlItems liHeader =
190 Seq.spanl $ \(unTree -> (unCell -> nod)) ->
191 case nod of
192 NodeHeader (HeaderColon "li" _wh) -> True
193 NodeHeader hdr -> liHeader hdr
194 NodePair (PairElem "li" _as) -> True
195 _ -> False
196 ----------------------
197 NodePara | para:inh_para <- inh_para inh ->
198 para inh r <|
199 -- para (() <$ cr) (xmlify inh ts) <|
200 xmlify inh{inh_para} rs
201 ----------------------
202 -- NOTE: context-free Root
203 _ ->
204 xmlify inh r <>
205 xmlify inh rs
206 where
207 element :: XmlName -> XMLs -> XML
208 element n = Tree (XmlElem n <$ cr)
209 instance Xmlify Root where
210 xmlify inh tn@(Tree (Cell bn en nod) ts) =
211 case nod of
212 NodeGroup -> xmlify inh ts
213 ----------------------
214 NodePara ->
215 case inh_para inh of
216 [] -> xmlify inh ts
217 para:_ -> Seq.singleton $ para inh tn -- para (() <$ cn) $ xmlify inh ts
218 ----------------------
219 NodeHeader hdr ->
220 case hdr of
221 --
222 HeaderSection{} ->
223 Seq.singleton $
224 element "section" $ head <> xmlify inh' body
225 where
226 (titles, content) = partitionSection tn
227 (attrs, body) = partitionAttrs content
228 head =
229 case Seq.viewl titles of
230 EmptyL -> mempty
231 title@(unTree -> ct) :< subtitles ->
232 xmlAttrs (attrs `defaultAttr` (ct $> ("id",getAttrId title))) <>
233 xmlify inh{inh_para=List.repeat elementTitle} title <>
234 aliases
235 where
236 aliases =
237 subtitles >>= \subtitle@(unTree -> cs) ->
238 return $
239 Tree (cs $> XmlElem "alias") $
240 xmlAttrs [cs $> ("id",getAttrId subtitle)]
241 inh' = inh
242 { inh_para = List.repeat elementPara
243 , inh_figure = True
244 }
245 --
246 HeaderColon n _wh ->
247 let (attrs,body) = partitionAttrs ts in
248 case n of
249 -- NOTE: insert titles into <about>.
250 "about" ->
251 Seq.singleton $
252 element "about" $
253 xmlify inh' (inh_titles inh) <>
254 xmlAttrs attrs <>
255 xmlify inh' body
256 -- NOTE: in <figure> mode, unreserved elements become <figure>
257 _ | inh_figure inh && n`List.notElem`elems || TL.null n ->
258 Seq.singleton $
259 element "figure" $
260 -- xmlAttrs (setAttr (Cell en en ("type",n)) attrs) <>
261 xmlAttrs (attrs `defaultAttr` Cell bn bn ("type", n)) <>
262 case toList body of
263 [Tree0{}] -> xmlify inh'{inh_para = List.repeat elementPara} body
264 _ -> xmlify inh'{inh_para = elementTitle : List.repeat elementPara} body
265 -- NOTE: reserved elements
266 _ ->
267 Seq.singleton $
268 element (xmlLocalName n) $
269 xmlAttrs attrs <>
270 xmlify inh' body
271 where
272 inh' = inh
273 { inh_para =
274 case n of
275 "about" -> List.repeat elementTitle
276 "reference" -> elementTitle : List.repeat elementPara
277 "serie" -> List.repeat attributeName
278 "author" -> List.repeat attributeName
279 "editor" -> List.repeat attributeName
280 "org" -> List.repeat attributeName
281 "note" -> List.repeat elementPara
282 _ -> []
283 }
284 --
285 HeaderBar n _wh ->
286 Seq.singleton $
287 element "artwork" $
288 xmlAttrs (Seq.singleton $ Cell bn bn ("type", n)) <>
289 xmlify inh{inh_para=[]} ts
290 --
291 HeaderGreat n _wh ->
292 Seq.singleton $
293 let (attrs,body) = partitionAttrs ts in
294 element "quote" $
295 xmlAttrs (attrs `defaultAttr` Cell bn bn ("type", n)) <>
296 xmlify inh{inh_para=List.repeat elementPara} body
297 --
298 HeaderEqual n _wh ->
299 Seq.singleton $
300 Tree0 $ cell $ XmlAttr (xmlLocalName n) $
301 Plain.text (Plain.setStart ts def{Plain.state_escape = False}) ts
302 --
303 HeaderDot _n -> Seq.singleton $ element "li" $ xmlify inh ts
304 --
305 HeaderDash -> Seq.singleton $ element "li" $ xmlify inh ts
306 --
307 HeaderDashDash -> Seq.singleton $ Tree0 $ cell $ XmlComment $
308 -- debug1_ ("TS", ts) $
309 -- debug1_ ("RS", (S.evalState (Plain.rackUpLeft ts) Nothing)) $
310 Plain.document ts
311 -- Plain.text def $ S.evalState (Plain.rackUpLeft ts) Nothing
312 {-
313 TreeSeq.mapAlsoNode
314 (cell1 . unCell)
315 (\_k -> fmap $
316 TreeSeq.mapAlsoNode
317 (cell1 . unCell)
318 (\_k' -> cell1 . unCell)) <$> ts
319 -}
320 --
321 HeaderBrackets ident ->
322 let (attrs,body) = partitionAttrs ts in
323 Seq.singleton $
324 element "reference" $
325 xmlAttrs (setAttr (Cell en en ("id",ident)) attrs) <>
326 xmlify inh'{inh_para = elementTitle : elementTitle : List.repeat elementPara} body
327 where
328 inh' = inh{inh_figure = False}
329 --
330 HeaderDotSlash p ->
331 Seq.singleton $
332 element "include" $
333 xmlAttrs [cell ("href",TL.pack $ FP.replaceExtension p "dtc")] <>
334 xmlify inh ts
335 ----------------------
336 NodePair pair ->
337 case pair of
338 PairBracket | to <- Plain.document ts
339 , TL.all (\c -> Char.isAlphaNum c || Char.isSymbol c) to ->
340 Seq.singleton $
341 element "rref" $
342 xmlAttrs [cell ("to",to)]
343 PairStar -> Seq.singleton $ element "b" $ xmlify inh ts
344 PairSlash -> Seq.singleton $ element "i" $ xmlify inh ts
345 PairBackquote -> Seq.singleton $ element "code" $ xmlify inh ts
346 PairFrenchquote ->
347 Seq.singleton $
348 element "q" $
349 xmlify inh ts
350 {-
351 case ts of
352 (Seq.viewl -> Tree0 (Cell bl el (TokenPlain l)) :< ls) ->
353 case Seq.viewr ls of
354 m :> Tree0 (Cell br er (TokenPlain r)) ->
355 xmlify inh $
356 Tree0 (Cell bl el (TokenPlain (Text.dropWhile Char.isSpace l)))
357 <|(m|>Tree0 (Cell br er (TokenPlain (Text.dropWhileEnd Char.isSpace r))))
358 _ ->
359 xmlify inh $
360 Tree0 (Cell bl el (TokenPlain (Text.dropAround Char.isSpace l))) <| ls
361 (Seq.viewr -> rs :> Tree0 (Cell br er (TokenPlain r))) ->
362 xmlify inh $
363 rs |> Tree0 (Cell br er (TokenPlain (Text.dropAround Char.isSpace r)))
364 _ -> xmlify inh ts
365 -}
366 PairHash ->
367 Seq.singleton $
368 element "ref" $
369 xmlAttrs [cell ("to",Plain.document ts)]
370 PairElem name attrs ->
371 Seq.singleton $
372 element (xmlLocalName name) $
373 xmlAttrs (Seq.fromList $ (\(_wh,ElemAttr{..}) ->
374 cell (xmlLocalName elemAttr_name,elemAttr_value)) <$> attrs) <>
375 xmlify inh ts
376 _ ->
377 Seq.singleton (Tree0 $ Cell bn bn' $ XmlText open) `unionXml`
378 xmlify inh ts `unionXml`
379 Seq.singleton (Tree0 $ Cell en' en $ XmlText close)
380 where
381 (open, close) = pairBorders pair ts
382 bn' = bn{pos_column=pos_column bn + int (TL.length open)}
383 en' = en{pos_column=pos_column bn - int (TL.length close)}
384 ----------------------
385 NodeText t -> Seq.singleton $ Tree0 $ cell $ XmlText t
386 ----------------------
387 NodeToken tok ->
388 case tok of
389 TokenEscape c -> Seq.singleton $ Tree0 $ cell $ XmlText $ TL.singleton c
390 TokenText t -> Seq.singleton $ Tree0 $ cell $ XmlText t
391 TokenTag t -> Seq.singleton $ element "ref" $ xmlAttrs [cell ("to",t)]
392 TokenLink lnk -> Seq.singleton $ element "eref" $ xmlAttrs [cell ("to",lnk)]
393 ----------------------
394 NodeLower n as ->
395 Seq.singleton $
396 element "artwork" $
397 xmlify inh ts
398 where
399 cell :: a -> Cell a
400 cell = Cell bn en
401 element :: XmlName -> XMLs -> XML
402 element n = Tree (cell $ XmlElem n)
403 instance Xmlify (Seq (Cell (XmlName,TL.Text))) where
404 xmlify _inh = xmlAttrs
405
406 -- * Elements
407
408 -- | Reserved elements' name
409 elems :: Set TL.Text
410 elems =
411 [ "about"
412 , "abstract"
413 , "address"
414 , "alias"
415 , "annotation"
416 , "area"
417 , "artwork"
418 , "aside"
419 , "audio"
420 , "author"
421 , "authors"
422 , "bcp14"
423 , "br"
424 , "call"
425 , "city"
426 , "code"
427 , "comment"
428 , "comments"
429 , "country"
430 , "date"
431 , "dd"
432 , "define"
433 , "del"
434 , "div"
435 , "dl"
436 , "document"
437 , "dt"
438 , "editor"
439 , "email"
440 , "embed"
441 , "eref"
442 , "fax"
443 , "feed"
444 , "feedback"
445 , "figure"
446 , "filter"
447 , "format"
448 , "from"
449 , "h"
450 , "hi"
451 , "html5"
452 , "i"
453 , "index"
454 , "iref"
455 , "keyword"
456 , "li"
457 , "link"
458 , "name"
459 , "note"
460 , "ol"
461 , "organization"
462 , "para"
463 , "postamble"
464 , "preamble"
465 , "q"
466 , "ref"
467 , "reference"
468 , "references"
469 , "region"
470 , "rref"
471 , "sc"
472 , "section"
473 , "serie"
474 , "source"
475 , "span"
476 , "street"
477 , "style"
478 , "sub"
479 , "sup"
480 , "table"
481 , "tbody"
482 , "td"
483 , "tel"
484 , "tfoot"
485 , "title"
486 , "th"
487 , "thead"
488 , "toc"
489 , "tof"
490 , "tr"
491 , "tt"
492 , "u"
493 , "ul"
494 , "uri"
495 , "version"
496 , "video"
497 , "workgroup"
498 , "xml"
499 , "zipcode"
500 ]
501
502 -- * Attributes
503
504 -- | Convenient alias, forcing the types
505 xmlAttrs :: Seq (Cell (XmlName,TL.Text)) -> XMLs
506 xmlAttrs = (Tree0 . (uncurry XmlAttr <$>) <$>)
507
508 -- | Extract attributes
509 partitionAttrs :: Roots -> (Seq (Cell (XmlName, TL.Text)), Roots)
510 partitionAttrs ts = (attrs,cs)
511 where
512 (as,cs) = (`Seq.partition` ts) $ \case
513 Tree (unCell -> NodeHeader (HeaderEqual n _wh)) _cs -> not $ TL.null n
514 _ -> False
515 attrs = attr <$> as
516 attr = \case
517 Tree (Cell bp ep (NodeHeader (HeaderEqual n _wh))) a ->
518 Cell bp ep (xmlLocalName n, v)
519 where
520 v = Plain.text (Plain.setStart a def{Plain.state_escape = False}) a
521 _ -> undefined
522
523 getAttrId :: Root -> TL.Text
524 getAttrId = Plain.document . Seq.singleton
525
526 setAttr ::
527 Cell (XmlName, TL.Text) ->
528 Seq (Cell (XmlName, TL.Text)) ->
529 Seq (Cell (XmlName, TL.Text))
530 setAttr a@(unCell -> (k, _v)) as =
531 case Seq.findIndexL (\(unCell -> (n,_v)) -> n == k) as of
532 Just idx -> Seq.update idx a as
533 Nothing -> a <| as
534
535 defaultAttr ::
536 Seq (Cell (XmlName, TL.Text)) ->
537 Cell (XmlName, TL.Text) ->
538 Seq (Cell (XmlName, TL.Text))
539 defaultAttr as a@(unCell -> (k, _v)) =
540 case Seq.findIndexL (\(unCell -> (n,_v)) -> n == k) as of
541 Just _idx -> as
542 Nothing -> a <| as
543
544 -- * Text
545
546 -- | Unify two 'XMLs', merging border 'XmlText's if any.
547 unionXml :: XMLs -> XMLs -> XMLs
548 unionXml x y =
549 case (Seq.viewr x, Seq.viewl y) of
550 (xs :> x0, y0 :< ys) ->
551 case (x0,y0) of
552 ( Tree0 (Cell bx ex (XmlText tx))
553 , Tree0 (Cell by ey (XmlText ty)) ) ->
554 xs `unionXml`
555 Seq.singleton (Tree0 $ (XmlText <$>) $ Cell bx ex tx <> Cell by ey ty) `unionXml`
556 ys
557 _ -> x <> y
558 (Seq.EmptyR, _) -> y
559 (_, Seq.EmptyL) -> x
560
561 unionsXml :: Foldable f => f XMLs -> XMLs
562 unionsXml = foldl' unionXml mempty