1 {-# LANGUAGE OverloadedStrings #-}
2 {-# LANGUAGE PatternSynonyms #-}
3 {-# LANGUAGE ViewPatterns #-}
9 import Control.Monad (Monad(..))
11 import Data.Char (Char)
12 import Data.Eq (Eq(..))
13 import Data.Foldable (Foldable(..), any)
14 import Data.Function (($))
15 import Data.Functor ((<$>))
17 import Data.List.NonEmpty (NonEmpty(..))
18 import Data.Maybe (Maybe(..))
19 import Data.Monoid (Monoid(..))
20 import Data.Ord (Ordering(..), Ord(..))
21 import Data.Semigroup (Semigroup(..))
22 import Data.Sequence ((|>))
23 import Data.TreeSeq.Strict (Tree(..), Trees)
24 import Prelude (undefined, Num(..), Bounded(..))
25 import System.FilePath (FilePath)
26 import Text.Show (Show(..))
27 import qualified Data.List as List
28 import qualified Data.Sequence as Seq
29 import qualified Data.Text.Lazy as TL
30 import qualified Text.Megaparsec as P
38 -- | A single 'Tree' to gather all the 'Node's
39 -- simplifies greatly the navigation and transformations,
40 -- especially because the later XML or DTC output
41 -- are themselves a single tree-like data structure.
43 -- Also, having a single 'Tree' is easier to merge
44 -- XML coming from the first parsing phase (eg. @('NodeHeader' ('HeaderEqual' ('Just' "li") ""))@),
45 -- and XML coming from the second parsing phase (eg. @'NodePair' ('PairElem' ('Just' "li") [])@).
47 -- For error reporting, indentation sensitivity and paragraph grouping,
48 -- each 'Node' is annotated with a 'Cell'
49 -- spanning over all its content (sub-'Trees' included).
50 type Root = Tree (Cell Node)
51 type Roots = Trees (Cell Node)
53 pattern Tree0 :: a -> Tree a
54 pattern Tree0 a <- Tree a (null -> True)
55 where Tree0 a = Tree a mempty
59 = NodeHeader !Header -- ^ node, from first parsing (indentation-sensitive)
60 | NodeText !TL.Text -- ^ leaf verbatim text, from first parsing (indentation-sensitive)
61 | NodePair !Pair -- ^ node, from second parsing (on some 'NodeText's)
62 | NodeToken !Token -- ^ leaf, from second parsing (on some 'NodeText's)
63 | NodeLower !ElemName !ElemAttrs -- ^ node, @<name a=b@
64 | NodePara -- ^ node, gather trees by paragraph,
65 -- useful to know when to generate a <para> XML node
71 = HeaderColon !(Maybe ElemName) !White -- ^ @name: @
72 | HeaderEqual !ElemName !White -- ^ @name=@
73 | HeaderBar !(Maybe ElemName) !White -- ^ @name|@
74 | HeaderGreat !(Maybe ElemName) !White -- ^ @name>@
75 | HeaderBrackets !TL.Text -- ^ @[name]@
76 | HeaderDot !TL.Text -- ^ @1. @
77 | HeaderDash -- ^ @- @
78 | HeaderDashDash -- ^ @-- @
79 | HeaderSection !LevelSection -- ^ @# @
80 | HeaderDotSlash !FilePath -- ^ @./file @
81 deriving (Eq, Ord, Show)
82 instance Pretty Header
89 -- ** Type 'LevelSection'
90 type LevelSection = Int
94 = PairElem !ElemName !ElemAttrs -- ^ @\<name a0=v0 a1=v1>text\</name>@
95 | PairTag Bool -- ^ @\#text\#@ or @~\#text\#@
96 | PairAt Bool -- ^ @\@text\@@ or @~\@text\@@
97 | PairStar -- ^ @*text*@
98 | PairSlash -- ^ @/text/@
99 | PairUnderscore -- ^ @_value_@
100 | PairDash -- ^ @-text-@
101 | PairBackquote -- ^ @`text`@
102 | PairSinglequote -- ^ @'text'@
103 | PairDoublequote -- ^ @"text"@
104 | PairFrenchquote -- ^ @«text»@
105 | PairParen -- ^ @(text)@
106 | PairBrace -- ^ @{text}@
107 | PairBracket -- ^ @[text]@
108 deriving (Eq,Ord,Show)
114 | TokenEscape !Char -- ^ @\\char@
116 | TokenAt !Bool !Ref -- ^ @\@foo@ or @~\@foo@
117 | TokenTag !Bool !Ref -- ^ @\#foo@ or @~\#foo@
123 = FilterAnd !Filter !Filter
124 | FilterOr !Filter !Filter
128 deriving (Eq,Ord,Show)
138 -- | In normal order: a list of 'Header's, maybe ended by 'Value', all read on the same line.
142 -- | In reverse order: a list of nodes in scope
143 -- (hence to which the next line can append to).
146 -- | Having an initial 'Root' simplifies 'mergeRowIndent':
147 -- one can always put the last 'Root' as a child to a previous one.
148 -- This 'Root' just has to be discarded by 'collapseRows'.
150 initRows = [Tree0 $ Sourced (FileRange "" p p :| []) $ NodeHeader HeaderDash]
152 p = LineColumn{lineNum=numM1, colNum=num0}
153 -- NOTE: lineNum= -1 is a hack so that any following 'Root'
154 -- becomes a 'NodePara' if possible, and always a child.
155 numM1 = numMax<>numMax<>P.pos1
157 numMax = P.mkPos maxBound
159 -- | @mergeRow rows row@ append @row@ into @rows@, while merging what has to be.
161 -- * [@rows@] is old 'Rows', its |Root|s' 'cell_begin' are descending (non-strictly),
162 -- they MAY span over multilines, and they can be many from a single line.
163 -- * [@row@] is new 'Row', its |Root|s' 'cell_begin' are descending (non-strictly),
164 -- they MUST span only over a single and entire line.
166 -- This is the main entry point to build 'Rows' by accumulating 'Row' into them.
167 mergeRow :: Rows -> Row -> Rows
169 debug2_ "mergeRow" ("news",List.reverse row) ("olds",rows) $
170 mergeRowPrefix 0 rows $ List.reverse row
172 -- | Merge by considering matching prefixes.
174 -- 'HeaderGreat' and 'HeaderBar' work, not on indentation,
175 -- but on their vertical alignment as prefixes.
176 -- Hence, each new 'Row' has those prefixes zipped into a single one
177 -- when they match, are aligned and adjacent.
178 mergeRowPrefix :: ColInt -> Rows -> Row -> Rows
179 mergeRowPrefix col rows row =
180 debug3_ "mergeRowPrefix" ("col",col) ("news",row) ("olds",rows) $
183 (_, []) -> undefined -- NOTE: cannot happen with initRows
184 ( _new@(Tree (Sourced (FileRange _fn bn _en:|_sn) n) _ns):news
185 , _old@(Tree (Sourced (FileRange _fo _bo eo:|_so) _o) _os):_olds ) ->
186 case collapseRowsWhile isCollapsable rows of
187 [] -> mergeRowIndent rows row
188 head@(unTree -> ch@(Sourced (FileRange _fh bh _eh:|_sh) h)) : olds' ->
190 -- NOTE: zipping: when new is HeaderGreat, collapse last line downto col
191 -- then check if there is a matching HeaderGreat,
192 -- if so, discard new and restart with a col advanced to new's beginning
193 (NodeHeader HeaderGreat{}, NodeHeader HeaderGreat{})
194 | isAdjacent && isMatching ch -> discard
195 -- NOTE: same for HeaderBar
196 (NodeHeader HeaderBar{}, NodeHeader HeaderBar{})
197 | isAdjacent && isMatching ch -> discard
198 -- NOTE: collapsing: any other new aligned or on the right of an adjacent head
199 -- makes it collapse entirely
200 (_, NodeHeader HeaderGreat{})
201 | col < colInt bh -> collapse
202 -- NOTE: same for HeaderBar
203 (_, NodeHeader HeaderBar{})
204 | col < colInt bh -> collapse
205 _ -> debug "mergeRowPrefix/indent" $ mergeRowIndent rows row
207 isAdjacent = lineInt bn - lineInt eo <= 1
208 discard = debug "mergeRowPrefix/discard" $ mergeRowPrefix (colInt bh) rows news
209 collapse = debug "mergeRowPrefix/collapse" $ mergeRowPrefix col (collapseRoot head olds') row
211 isMatching (Sourced (FileRange _fh bh _eh:|_sh) h) =
212 colInt bn == colInt bh &&
214 isCollapsable = debug2 "mergeRowPrefix/isCollapsable" "new" "old" $
215 \_t0@(unTree -> c0@(Sourced (FileRange _f0 b0 _e0:|_s0) _n0))
216 _t1@(unTree -> Sourced (FileRange _f1 b1 e1:|_s1) _n1) ->
217 not (isMatching c0) &&
218 (lineInt b0 - lineInt e1 <= 1) && -- adjacent
219 col < colInt b1 -- righter than col
221 -- | Merge by considering indentation.
222 mergeRowIndent :: Rows -> Row -> Rows
223 mergeRowIndent rows row =
224 debug2_ "mergeRowIndent" ("news",row) ("olds",rows) $
227 (_, []) -> undefined -- NOTE: cannot happen with initRows
228 ( new@(Tree (Sourced ssn@(FileRange fn bn en:|sn) n) ns):news
229 ,old@(Tree (Sourced sso@(FileRange fo bo eo:|so) o) os):olds ) ->
230 case debug0 "mergeRowIndent/colNew" (colInt bn) `compare`
231 debug0 "mergeRowIndent/colOld" (colInt bo) of
232 -- NOTE: new is on the left
235 -- NOTE: merge adjacent NodeText
238 (NodeText tn, NodeText to)
239 | TL.null tn || TL.null to
240 , not isVerbatim -> collapse
241 | isAdjacent && isIndented -> merge $ Tree t (os<>ns)
243 t = NodeText <$> Sourced (FileRange fo boNew eo:|so) (indent<>to) <> Sourced ssn tn
244 boNew = bo{colNum=colNum bn}
245 indent = TL.replicate (int64 $ colInt bo - colInt bn) " "
246 -- | Whether the horizontal delta is made of spaces
248 debug0 "mergeRowIndent/isIndented" $
251 (unTree -> (source -> (fileRange_end -> ep) :| _)) : _ ->
252 case lineInt ep `compare` lineInt bo of
254 EQ -> colInt ep <= colInt bn
257 -- NOTE: new is vertically aligned
260 -- NOTE: preserve all NodeText "", but still split into two NodePara
261 (NodeText tn, NodeText to)
262 | TL.null tn || TL.null to
263 , not isVerbatim -> collapse
264 | isAdjacent -> merge $ Tree (NodeText <$> Sourced sso to <> Sourced ssn tn) (os<>ns)
265 -- NOTE: HeaderSection can parent Nodes at the same level
266 (NodeHeader (HeaderSection lvlNew), NodeHeader (HeaderSection lvlOld)) ->
267 if debug0 "mergeRowIndent/lvlNew" lvlNew
268 > debug0 "mergeRowIndent/lvlOld" lvlOld
275 -- NOTE: old is no HeaderSection, then collapse to any older and loop
276 (NodeHeader HeaderSection{}, _)
277 | rows'@(sec:_) <- collapseRowsWhile isCollapsable rows
278 , (unTree -> (unSourced -> NodeHeader HeaderSection{})) <- sec ->
279 mergeRowIndent rows' row
281 isCollapsable = debug2 "mergeRowIndent/isCollapsable" "new" "old" $
282 \_t0@(unTree -> Sourced (FileRange _f0 b0 _e0:|_ss0) n0) _t1 ->
284 NodeHeader HeaderSection{} -> False
285 _ -> colInt bn == colInt b0
286 -- NOTE: in case of alignment, HeaderSection is parent
287 (_, NodeHeader HeaderSection{}) -> concat
290 -- NOTE: new is on the right
293 -- NOTE: keep NodeText "" out of old NodePara
294 (NodeText "", NodePara) -> collapse
295 -- NOTE: merge adjacent NodeText
296 (NodeText tn, NodeText to) ->
298 _ | TL.null tn || TL.null to
299 , not isVerbatim -> collapse
302 True -> merge $ Tree (NodeText <$> Sourced sso to <> Sourced ssn tn) (os<>ns)
306 False -> mergeRowIndent (collapseRoot old olds) (shifted:news)
308 shifted = Tree (Sourced (FileRange fn bnNew en:|sn) $ NodeText $ indent<>tn) (os<>ns)
309 bnNew = bn{colNum=colNum bo}
310 indent = TL.replicate (int64 $ colInt bn - colInt bo) " "
314 isAdjacent = lineInt bn - lineInt eo <= 1
315 -- | Whether a parent semantic want new to stay a NodeText
316 isVerbatim = any p rows
318 p (unTree -> (unSourced -> NodeHeader HeaderBar{})) = True
320 concat = debug "mergeRowIndent/concat" $ List.reverse row <> rows
321 merge m = debug "mergeRowIndent/merge" $ mergeRowIndent (m : olds) news
322 collapse = debug "mergeRowIndent/collapse" $ mergeRowIndent (collapseRoot old olds) row
323 replace = debug "mergeRowIndent/replace" $ mergeRowIndent (new : collapseRoot old olds) news
325 -- | Like 'mergeRowIndent', but without maintaining the appending,
326 -- hence collapsing all the 'Root's of the given 'Rows'.
328 -- NOTE: 'initRows' MUST have been the first 'Rows'
329 -- before calling 'mergeRowIndent' on it to get the given 'Rows'.
330 collapseRows :: Rows -> Roots
332 debug1_ "collapseRows" ("rows",rows) $
333 case collapseRowsWhile (\_new _old -> True) rows of
336 -- NOTE: subTrees returns the children of the updated initRows
338 -- | Collapse downto any last HeaderSection, returning it and its level.
339 collapseSection :: ColInt -> Rows -> Rows
340 collapseSection col = debug1 "collapseSection" "rows" go
342 go rows@(new@(unTree -> Sourced (FileRange _fn bn _en:|_sn) n):olds)
345 NodeHeader HeaderSection{} -> rows
346 _ -> collapseSection col $ collapseRoot new $ go olds
349 collapseRowsWhile :: (Root -> Root -> Bool) -> Rows -> Rows
350 collapseRowsWhile test = debug1 "collapseRowsWhile" "rows" $ \case
352 rows@(new@(Tree (Sourced (FileRange _fn bn _en:|_sn) n) _ns):news) ->
355 old@(Tree (Sourced (FileRange _fo bo eo:|_so) o) _os):olds
356 | not $ test new old -> rows
358 case debug0 "collapseRowsWhile/colNew" (colInt bn) `compare`
359 debug0 "collapseRowsWhile/colOld" (colInt bo) of
360 -- NOTE: new is vertically aligned
363 -- NOTE: HeaderSection can parent Nodes at the same level
364 (NodeHeader (HeaderSection lvlNew), NodeHeader (HeaderSection lvlOld)) ->
365 if debug0 "collapseRowsWhile/lvlNew" lvlNew
366 > debug0 "collapseRowsWhile/lvlOld" lvlOld
373 debug "collapseRowsWhile/replace" $
374 collapseRowsWhile test $ (new:) $ collapseRoot old olds
375 -- NOTE: old is no HeaderSection, then collapse to any older and loop
376 (NodeHeader HeaderSection{}, _)
377 | news'@(sec:_) <- debug0 "collapseRowsWhile/section" $ collapseRowsWhile isCollapsable news
378 , (unTree -> (unSourced -> NodeHeader HeaderSection{})) <- sec ->
379 collapseRowsWhile test news'
381 isCollapsable = debug2 "collapseRowsWhile/isCollapsable" "new" "old" $
382 \_t0@(unTree -> Sourced (FileRange _f0 b0 _e0:|_s0) n0) _t1 ->
384 NodeHeader HeaderSection{} -> False
385 _ -> colInt bn == colInt b0
386 -- NOTE: in case of alignment, HeaderSection is parent
387 (_, NodeHeader HeaderSection{}) -> debug "collapseRowsWhile/section/parent" collapse
388 -- NOTE: merge within old NodePara.
389 (_, NodePara) | isAdjacent -> collapse
392 -- NOTE: new is either on the left or on the right
395 isAdjacent = lineInt bn - lineInt eo <= 1
396 collapse = debug "collapseRowsWhile/collapse" $ collapseRowsWhile test $ collapseRoot new $ news
397 collapse2 = debug "collapseRowsWhile/collapse2" $ collapseRowsWhile test $ collapseRoot new $ collapseRoot old $ olds
399 -- | Put a 'Root' as a child of the head 'Root'.
401 -- NOTE: 'collapseRoot' is where 'NodePara' may be introduced.
403 -- NOTE: any NodeText/NodeText merging must have been done before.
404 collapseRoot :: Root -> Rows -> Rows
405 collapseRoot new@(Tree (Sourced ssn@(FileRange _fn bn en:|_sn) n) _ns) rows =
406 debug2_ "collapseRoot" ("new",Seq.singleton new) ("rows",rows) $
409 old@(Tree (Sourced (FileRange fo bo eo:|so) o) os) : olds ->
411 -- NOTE: no child into NodeText
412 (_, NodeText{}) -> collapse2
413 -- NOTE: NodeText can begin a NodePara
414 (NodeText tn, _) | not $ TL.null tn ->
416 -- NOTE: no NodePara within those
417 NodeHeader HeaderEqual{} -> collapse
418 NodeHeader HeaderBar{} -> collapse
419 NodeHeader HeaderDashDash{} -> collapse
420 -- NOTE: NodePara within those
421 NodePara | not isAdjacent -> para
424 -- NOTE: amongst remaining nodes, only adjacent ones may enter an old NodePara.
425 -- Note that since a NodePara is never adjacent to another,
426 -- it is not nested within another.
430 -- NOTE: no HeaderSection (even adjacent) within a NodePara
431 NodeHeader HeaderSection{} -> collapse2
433 | otherwise -> collapse2
436 isAdjacent = lineInt bn - lineInt eo <= 1
437 para = Tree (Sourced ssn NodePara) (return new) : rows
438 collapse = Tree (Sourced (FileRange fo bo en:|so) o) (os |> new) : olds
439 collapse2 = collapseRoot new $ collapseRoot old olds