1 %*********************************************************************************
3 %* John Hughes's and Simon Peyton Jones's Pretty Printer Combinators *
5 %* based on "The Design of a Pretty-printing Library" *
6 %* in Advanced Functional Programming, *
7 %* Johan Jeuring and Erik Meijer (eds), LNCS 925 *
8 %* http://www.cs.chalmers.se/~rjmh/Papers/pretty.ps *
10 %* Heavily modified by Simon Peyton Jones, Dec 96 *
12 %*********************************************************************************
14 Version 3.0 28 May 1997
15 * Cured massive performance bug. If you write
17 foldl <> empty (map (text.show) [1..10000])
19 you get quadratic behaviour with V2.0. Why? For just the same reason as you get
20 quadratic behaviour with left-associated (++) chains.
22 This is really bad news. One thing a pretty-printer abstraction should
23 certainly guarantee is insensivity to associativity. It matters: suddenly
24 GHC's compilation times went up by a factor of 100 when I switched to the
27 I fixed it with a bit of a hack (because I wanted to get GHC back on the
28 road). I added two new constructors to the Doc type, Above and Beside:
33 Then, where I need to get to a "TextBeside" or "NilAbove" form I "force"
34 the Doc to squeeze out these suspended calls to Beside and Above; but in so
35 doing I re-associate. It's quite simple, but I'm not satisfied that I've done
36 the best possible job. I'll send you the code if you are interested.
40 int, integer, float, double, rational,
41 lparen, rparen, lbrack, rbrack, lbrace, rbrace,
43 * fullRender's type signature has changed. Rather than producing a string it
44 now takes an extra couple of arguments that tells it how to glue fragments
49 -> Float -- Ribbons per line
50 -> (TextDetails -> a -> a) -- What to do with text
51 -> a -- What to do at the end
55 The "fragments" are encapsulated in the TextDetails data type:
56 data TextDetails = Chr Char
60 The Chr and Str constructors are obvious enough. The PStr constructor has a packed
61 string (FastString) inside it. It's generated by using the new "ptext" export.
63 An advantage of this new setup is that you can get the renderer to do output
64 directly (by passing in a function of type (TextDetails -> IO () -> IO ()),
65 rather than producing a string that you then print.
68 Version 2.0 24 April 1997
69 * Made empty into a left unit for <> as well as a right unit;
70 it is also now true that
72 which wasn't true before.
74 * Fixed an obscure bug in sep that occassionally gave very wierd behaviour
78 * Corrected and tidied up the laws and invariants
80 ======================================================================
81 Relative to John's original paper, there are the following new features:
83 1. There's an empty document, "empty". It's a left and right unit for
84 both <> and $$, and anywhere in the argument list for
85 sep, hcat, hsep, vcat, fcat etc.
87 It is Really Useful in practice.
89 2. There is a paragraph-fill combinator, fsep, that's much like sep,
90 only it keeps fitting things on one line until it can't fit any more.
92 3. Some random useful extra combinators are provided.
93 <+> puts its arguments beside each other with a space between them,
94 unless either argument is empty in which case it returns the other
97 hcat is a list version of <>
98 hsep is a list version of <+>
99 vcat is a list version of $$
101 sep (separate) is either like hsep or like vcat, depending on what fits
103 cat is behaves like sep, but it uses <> for horizontal conposition
104 fcat is behaves like fsep, but it uses <> for horizontal conposition
106 These new ones do the obvious things:
107 char, semi, comma, colon, space,
108 parens, brackets, braces,
111 4. The "above" combinator, $$, now overlaps its two arguments if the
112 last line of the top argument stops before the first line of the second begins.
113 For example: text "hi" $$ nest 5 "there"
120 There are two places this is really useful
122 a) When making labelled blocks, like this:
123 Left -> code for left
124 Right -> code for right
126 code for longlonglonglabel
127 The block is on the same line as the label if the label is
128 short, but on the next line otherwise.
130 b) When laying out lists like this:
135 which some people like. But if the list fits on one line
136 you want [first, second, third]. You can't do this with
137 John's original combinators, but it's quite easy with the
140 The combinator $+$ gives the original "never-overlap" behaviour.
142 5. Several different renderers are provided:
144 * one that uses cut-marks to avoid deeply-nested documents
145 simply piling up in the right-hand margin
146 * one that ignores indentation (fewer chars output; good for machines)
147 * one that ignores indentation and newlines (ditto, only more so)
149 6. Numerous implementation tidy-ups
150 Use of unboxed data types to speed up the implementation
155 {-# LANGUAGE BangPatterns #-}
156 {-# OPTIONS -fno-warn-unused-imports #-}
157 -- XXX GHC 6.9 seems to be confused by unpackCString# being used only in
162 Mode(..), TextDetails(..),
164 empty, isEmpty, nest,
166 char, text, ftext, ptext,
167 int, integer, float, double, rational,
168 parens, brackets, braces, quotes, doubleQuotes,
169 semi, comma, colon, space, equals,
170 lparen, rparen, lbrack, rbrack, lbrace, rbrace, cparen,
172 (<>), (<+>), hcat, hsep,
179 -- renderStyle, -- Haskell 1.3 only
180 render, fullRender, printDoc, showDocWith,
181 bufLeftRender -- performance hack
189 import Numeric (fromRat)
191 --import Foreign.Ptr (castPtr)
193 #if defined(__GLASGOW_HASKELL__)
195 import GHC.Base ( unpackCString# )
196 import GHC.Exts ( Int# )
197 import GHC.Ptr ( Ptr(..) )
200 -- Don't import Util( assertPanic ) because it makes a loop in the module structure
210 -- Disable ASSERT checks; they are expensive!
211 #define LOCAL_ASSERT(x)
216 %*********************************************************
218 \subsection{The interface}
220 %*********************************************************
222 The primitive @Doc@ values
226 isEmpty :: Doc -> Bool
227 text :: String -> Doc
230 semi, comma, colon, space, equals :: Doc
231 lparen, rparen, lbrack, rbrack, lbrace, rbrace :: Doc
233 parens, brackets, braces :: Doc -> Doc
234 quotes, doubleQuotes :: Doc -> Doc
237 integer :: Integer -> Doc
238 float :: Float -> Doc
239 double :: Double -> Doc
240 rational :: Rational -> Doc
243 Combining @Doc@ values
246 (<>) :: Doc -> Doc -> Doc -- Beside
247 hcat :: [Doc] -> Doc -- List version of <>
248 (<+>) :: Doc -> Doc -> Doc -- Beside, separated by space
249 hsep :: [Doc] -> Doc -- List version of <+>
251 ($$) :: Doc -> Doc -> Doc -- Above; if there is no
252 -- overlap it "dovetails" the two
253 vcat :: [Doc] -> Doc -- List version of $$
255 cat :: [Doc] -> Doc -- Either hcat or vcat
256 sep :: [Doc] -> Doc -- Either hsep or vcat
257 fcat :: [Doc] -> Doc -- ``Paragraph fill'' version of cat
258 fsep :: [Doc] -> Doc -- ``Paragraph fill'' version of sep
260 nest :: Int -> Doc -> Doc -- Nested
266 hang :: Doc -> Int -> Doc -> Doc
267 punctuate :: Doc -> [Doc] -> [Doc] -- punctuate p [d1, ... dn] = [d1 <> p, d2 <> p, ... dn-1 <> p, dn]
270 Displaying @Doc@ values.
273 instance Show Doc where
274 showsPrec _ doc cont = showDoc doc cont
276 render :: Doc -> String -- Uses default style
278 -> Int -- Line length
279 -> Float -- Ribbons per line
280 -> (TextDetails -> a -> a) -- What to do with text
281 -> a -- What to do at the end
285 {- When we start using 1.3
286 renderStyle :: Style -> Doc -> String
287 data Style = Style { lineLength :: Int, -- In chars
288 ribbonsPerLine :: Float, -- Ratio of ribbon length to line length
291 style :: Style -- The default style
292 style = Style { lineLength = 100, ribbonsPerLine = 2.5, mode = PageMode }
295 data Mode = PageMode -- Normal
296 | ZigZagMode -- With zig-zag cuts
297 | LeftMode -- No indentation, infinitely long lines
298 | OneLineMode -- All on one line
303 %*********************************************************
305 \subsection{The @Doc@ calculus}
307 %*********************************************************
309 The @Doc@ combinators satisfy the following laws:
313 <a1> (x $$ y) $$ z = x $$ (y $$ z)
321 <b1> (x <> y) <> z = x <> (y <> z)
322 <b2> empty <> x = empty
329 <t1> text s <> text t = text (s++t)
330 <t2> text "" <> x = x, if x non-empty
335 <n2> nest k (nest k' x) = nest (k+k') x
336 <n3> nest k (x <> y) = nest k z <> nest k y
337 <n4> nest k (x $$ y) = nest k x $$ nest k y
338 <n5> nest k empty = empty
339 <n6> x <> nest k y = x <> y, if x non-empty
341 - Note the side condition on <n6>! It is this that
342 makes it OK for empty to be a left unit for <>.
346 <m1> (text s <> x) $$ y = text s <> ((text "" <> x)) $$
349 <m2> (x $$ y) <> z = x $$ (y <> z)
353 Laws for list versions
354 ~~~~~~~~~~~~~~~~~~~~~~
355 <l1> sep (ps++[empty]++qs) = sep (ps ++ qs)
356 ...ditto hsep, hcat, vcat, fill...
358 <l2> nest k (sep ps) = sep (map (nest k) ps)
359 ...ditto hsep, hcat, vcat, fill...
363 <o1> oneLiner (nest k p) = nest k (oneLiner p)
364 <o2> oneLiner (x <> y) = oneLiner x <> oneLiner y
368 You might think that the following verion of <m1> would
371 <3 NO> (text s <> x) $$ y = text s <> ((empty <> x)) $$
374 But it doesn't work, for if x=empty, we would have
376 text s $$ y = text s <> (empty $$ nest (-length s) y)
377 = text s <> nest (-length s) y
382 %*********************************************************
384 \subsection{Simple derived definitions}
386 %*********************************************************
401 int n = text (show n)
402 integer n = text (show n)
403 float n = text (show n)
404 double n = text (show n)
405 rational n = text (show (fromRat n :: Double))
406 --rational n = text (show (fromRationalX n)) -- _showRational 30 n)
408 quotes p = char '`' <> p <> char '\''
409 doubleQuotes p = char '"' <> p <> char '"'
410 parens p = char '(' <> p <> char ')'
411 brackets p = char '[' <> p <> char ']'
412 braces p = char '{' <> p <> char '}'
414 cparen :: Bool -> Doc -> Doc
418 hcat = foldr (<>) empty
419 hsep = foldr (<+>) empty
420 vcat = foldr ($$) empty
422 hang d1 n d2 = sep [d1, nest n d2]
425 punctuate p (d:ds) = go d ds
428 go d (e:es) = (d <> p) : go e es
432 %*********************************************************
434 \subsection{The @Doc@ data type}
436 %*********************************************************
438 A @Doc@ represents a {\em set} of layouts. A @Doc@ with
439 no occurrences of @Union@ or @NoDoc@ represents just one layout.
443 | NilAbove Doc -- text "" $$ x
444 | TextBeside !TextDetails FastInt Doc -- text s <> x
445 | Nest FastInt Doc -- nest k x
446 | Union Doc Doc -- ul `union` ur
447 | NoDoc -- The empty set of documents
448 | Beside Doc Bool Doc -- True <=> space between
449 | Above Doc Bool Doc -- True <=> never overlap
451 type RDoc = Doc -- RDoc is a "reduced Doc", guaranteed not to have a top-level Above or Beside
454 reduceDoc :: Doc -> RDoc
455 reduceDoc (Beside p g q) = beside p g (reduceDoc q)
456 reduceDoc (Above p g q) = above p g (reduceDoc q)
460 data TextDetails = Chr {-#UNPACK#-}!Char
462 | PStr FastString -- a hashed string
463 | LStr {-#UNPACK#-}!LitString FastInt -- a '\0'-terminated
466 space_text :: TextDetails
468 nl_text :: TextDetails
472 Here are the invariants:
475 The argument of @NilAbove@ is never @Empty@. Therefore
476 a @NilAbove@ occupies at least two lines.
479 The arugment of @TextBeside@ is never @Nest@.
482 The layouts of the two arguments of @Union@ both flatten to the same string.
485 The arguments of @Union@ are either @TextBeside@, or @NilAbove@.
488 The right argument of a union cannot be equivalent to the empty set (@NoDoc@).
489 If the left argument of a union is equivalent to the empty set (@NoDoc@),
490 then the @NoDoc@ appears in the first line.
493 An empty document is always represented by @Empty@.
494 It can't be hidden inside a @Nest@, or a @Union@ of two @Empty@s.
497 The first line of every layout in the left argument of @Union@
498 is longer than the first line of any layout in the right argument.
499 (1) ensures that the left argument has a first line. In view of (3),
500 this invariant means that the right argument must have at least two
505 -- Arg of a NilAbove is always an RDoc
506 nilAbove_ :: Doc -> Doc
507 nilAbove_ p = LOCAL_ASSERT( _ok p ) NilAbove p
512 -- Arg of a TextBeside is always an RDoc
513 textBeside_ :: TextDetails -> FastInt -> Doc -> Doc
514 textBeside_ s sl p = TextBeside s sl (LOCAL_ASSERT( _ok p ) p)
516 _ok (Nest _ _) = False
519 -- Arg of Nest is always an RDoc
520 nest_ :: FastInt -> Doc -> Doc
521 nest_ k p = Nest k (LOCAL_ASSERT( _ok p ) p)
526 -- Args of union are always RDocs
527 union_ :: Doc -> Doc -> Doc
528 union_ p q = Union (LOCAL_ASSERT( _ok p ) p) (LOCAL_ASSERT( _ok q ) q)
530 _ok (TextBeside _ _ _) = True
531 _ok (NilAbove _) = True
532 _ok (Union _ _) = True
536 Notice the difference between
537 * NoDoc (no documents)
538 * Empty (one empty document; no height and no width)
539 * text "" (a document containing the empty string;
540 one line high, but has no width)
544 %*********************************************************
546 \subsection{@empty@, @text@, @nest@, @union@}
548 %*********************************************************
556 char c = textBeside_ (Chr c) (_ILIT(1)) Empty
557 text s = case iUnbox (length s) of {sl -> textBeside_ (Str s) sl Empty}
558 ftext :: FastString -> Doc
559 ftext s = case iUnbox (lengthFS s) of {sl -> textBeside_ (PStr s) sl Empty}
560 ptext :: LitString -> Doc
561 ptext s_= case iUnbox (lengthLS s) of {sl -> textBeside_ (LStr s sl) sl Empty}
562 where s = {-castPtr-} s_
564 #if defined(__GLASGOW_HASKELL__)
565 -- RULE that turns (text "abc") into (ptext (A# "abc"#)) to avoid the
566 -- intermediate packing/unpacking of the string.
568 "text/str" forall a. text (unpackCString# a) = ptext (Ptr a)
572 nest k p = mkNest (iUnbox k) (reduceDoc p) -- Externally callable version
574 -- mkNest checks for Nest's invariant that it doesn't have an Empty inside it
575 mkNest :: Int# -> Doc -> Doc
576 mkNest k (Nest k1 p) = mkNest (k +# k1) p
577 mkNest _ NoDoc = NoDoc
578 mkNest _ Empty = Empty
579 mkNest k p | k ==# _ILIT(0) = p -- Worth a try!
580 mkNest k p = nest_ k p
582 -- mkUnion checks for an empty document
583 mkUnion :: Doc -> Doc -> Doc
584 mkUnion Empty _ = Empty
585 mkUnion p q = p `union_` q
588 %*********************************************************
590 \subsection{Vertical composition @$$@}
592 %*********************************************************
596 p $$ q = Above p False q
597 ($+$) :: Doc -> Doc -> Doc
598 p $+$ q = Above p True q
600 above :: Doc -> Bool -> RDoc -> RDoc
601 above (Above p g1 q1) g2 q2 = above p g1 (above q1 g2 q2)
602 above p@(Beside _ _ _) g q = aboveNest (reduceDoc p) g (_ILIT(0)) (reduceDoc q)
603 above p g q = aboveNest p g (_ILIT(0)) (reduceDoc q)
605 aboveNest :: RDoc -> Bool -> FastInt -> RDoc -> RDoc
606 -- Specfication: aboveNest p g k q = p $g$ (nest k q)
608 aboveNest NoDoc _ _ _ = NoDoc
609 aboveNest (p1 `Union` p2) g k q = aboveNest p1 g k q `union_`
612 aboveNest Empty _ k q = mkNest k q
613 aboveNest (Nest k1 p) g k q = nest_ k1 (aboveNest p g (k -# k1) q)
614 -- p can't be Empty, so no need for mkNest
616 aboveNest (NilAbove p) g k q = nilAbove_ (aboveNest p g k q)
617 aboveNest (TextBeside s sl p) g k q = textBeside_ s sl rest
621 Empty -> nilAboveNest g k1 q
622 _ -> aboveNest p g k1 q
623 aboveNest _ _ _ _ = panic "aboveNest: Unhandled case"
627 nilAboveNest :: Bool -> FastInt -> RDoc -> RDoc
628 -- Specification: text s <> nilaboveNest g k q
629 -- = text s <> (text "" $g$ nest k q)
631 nilAboveNest _ _ Empty = Empty -- Here's why the "text s <>" is in the spec!
632 nilAboveNest g k (Nest k1 q) = nilAboveNest g (k +# k1) q
634 nilAboveNest g k q | (not g) && (k ># _ILIT(0)) -- No newline if no overlap
635 = textBeside_ (Str (spaces k)) k q
636 | otherwise -- Put them really above
637 = nilAbove_ (mkNest k q)
641 %*********************************************************
643 \subsection{Horizontal composition @<>@}
645 %*********************************************************
648 p <> q = Beside p False q
649 p <+> q = Beside p True q
651 beside :: Doc -> Bool -> RDoc -> RDoc
652 -- Specification: beside g p q = p <g> q
654 beside NoDoc _ _ = NoDoc
655 beside (p1 `Union` p2) g q = (beside p1 g q) `union_` (beside p2 g q)
657 beside (Nest k p) g q = nest_ k $! beside p g q -- p non-empty
658 beside p@(Beside p1 g1 q1) g2 q2
659 {- (A `op1` B) `op2` C == A `op1` (B `op2` C) iff op1 == op2
660 [ && (op1 == <> || op1 == <+>) ] -}
661 | g1 == g2 = beside p1 g1 $! beside q1 g2 q2
662 | otherwise = beside (reduceDoc p) g2 q2
663 beside p@(Above _ _ _) g q = let d = reduceDoc p in d `seq` beside d g q
664 beside (NilAbove p) g q = nilAbove_ $! beside p g q
665 beside (TextBeside s sl p) g q = textBeside_ s sl $! rest
668 Empty -> nilBeside g q
673 nilBeside :: Bool -> RDoc -> RDoc
674 -- Specification: text "" <> nilBeside g p
677 nilBeside _ Empty = Empty -- Hence the text "" in the spec
678 nilBeside g (Nest _ p) = nilBeside g p
679 nilBeside g p | g = textBeside_ space_text (_ILIT(1)) p
683 %*********************************************************
685 \subsection{Separate, @sep@, Hughes version}
687 %*********************************************************
690 -- Specification: sep ps = oneLiner (hsep ps)
694 sep = sepX True -- Separate with spaces
695 cat = sepX False -- Don't
697 sepX :: Bool -> [Doc] -> Doc
699 sepX x (p:ps) = sep1 x (reduceDoc p) (_ILIT(0)) ps
702 -- Specification: sep1 g k ys = sep (x : map (nest k) ys)
703 -- = oneLiner (x <g> nest k (hsep ys))
704 -- `union` x $$ nest k (vcat ys)
706 sep1 :: Bool -> RDoc -> FastInt -> [Doc] -> RDoc
707 sep1 _ NoDoc _ _ = NoDoc
708 sep1 g (p `Union` q) k ys = sep1 g p k ys
710 (aboveNest q False k (reduceDoc (vcat ys)))
712 sep1 g Empty k ys = mkNest k (sepX g ys)
713 sep1 g (Nest n p) k ys = nest_ n (sep1 g p (k -# n) ys)
715 sep1 _ (NilAbove p) k ys = nilAbove_ (aboveNest p False k (reduceDoc (vcat ys)))
716 sep1 g (TextBeside s sl p) k ys = textBeside_ s sl (sepNB g p (k -# sl) ys)
717 sep1 _ _ _ _ = panic "sep1: Unhandled case"
719 -- Specification: sepNB p k ys = sep1 (text "" <> p) k ys
720 -- Called when we have already found some text in the first item
721 -- We have to eat up nests
723 sepNB :: Bool -> Doc -> FastInt -> [Doc] -> Doc
724 sepNB g (Nest _ p) k ys = sepNB g p k ys
726 sepNB g Empty k ys = oneLiner (nilBeside g (reduceDoc rest))
728 nilAboveNest False k (reduceDoc (vcat ys))
731 | otherwise = hcat ys
733 sepNB g p k ys = sep1 g p k ys
736 %*********************************************************
740 %*********************************************************
749 -- fill (p1:p2:ps) = oneLiner p1 <#> nest (length p1)
750 -- (fill (oneLiner p2 : ps))
754 fill :: Bool -> [Doc] -> Doc
756 fill g (p:ps) = fill1 g (reduceDoc p) (_ILIT(0)) ps
759 fill1 :: Bool -> RDoc -> FastInt -> [Doc] -> Doc
760 fill1 _ NoDoc _ _ = NoDoc
761 fill1 g (p `Union` q) k ys = fill1 g p k ys
763 (aboveNest q False k (fill g ys))
765 fill1 g Empty k ys = mkNest k (fill g ys)
766 fill1 g (Nest n p) k ys = nest_ n (fill1 g p (k -# n) ys)
768 fill1 g (NilAbove p) k ys = nilAbove_ (aboveNest p False k (fill g ys))
769 fill1 g (TextBeside s sl p) k ys = textBeside_ s sl (fillNB g p (k -# sl) ys)
770 fill1 _ _ _ _ = panic "fill1: Unhandled case"
772 fillNB :: Bool -> Doc -> Int# -> [Doc] -> Doc
773 fillNB g (Nest _ p) k ys = fillNB g p k ys
774 fillNB _ Empty _ [] = Empty
775 fillNB g Empty k (y:ys) = nilBeside g (fill1 g (oneLiner (reduceDoc y)) k1 ys)
777 nilAboveNest False k (fill g (y:ys))
779 !k1 | g = k -# _ILIT(1)
782 fillNB g p k ys = fill1 g p k ys
786 %*********************************************************
788 \subsection{Selecting the best layout}
790 %*********************************************************
793 best :: Int -- Line length
794 -> Int -- Ribbon length
796 -> RDoc -- No unions in here!
802 get :: FastInt -- (Remaining) width of line
806 get w (NilAbove p) = nilAbove_ (get w p)
807 get w (TextBeside s sl p) = textBeside_ s sl (get1 w sl p)
808 get w (Nest k p) = nest_ k (get (w -# k) p)
809 get w (p `Union` q) = nicest w r (get w p) (get w q)
810 get _ _ = panic "best/get: Unhandled case"
812 get1 :: FastInt -- (Remaining) width of line
813 -> FastInt -- Amount of first line already eaten up
814 -> Doc -- This is an argument to TextBeside => eat Nests
815 -> Doc -- No unions in here!
817 get1 _ _ Empty = Empty
818 get1 _ _ NoDoc = NoDoc
819 get1 w sl (NilAbove p) = nilAbove_ (get (w -# sl) p)
820 get1 w sl (TextBeside t tl p) = textBeside_ t tl (get1 w (sl +# tl) p)
821 get1 w sl (Nest _ p) = get1 w sl p
822 get1 w sl (p `Union` q) = nicest1 w r sl (get1 w sl p)
824 get1 _ _ _ = panic "best/get1: Unhandled case"
826 nicest :: FastInt -> FastInt -> Doc -> Doc -> Doc
827 nicest w r p q = nicest1 w r (_ILIT(0)) p q
828 nicest1 :: FastInt -> FastInt -> Int# -> Doc -> Doc -> Doc
829 nicest1 w r sl p q | fits ((w `minFastInt` r) -# sl) p = p
832 fits :: FastInt -- Space available
834 -> Bool -- True if *first line* of Doc fits in space available
836 fits n _ | n <# _ILIT(0) = False
839 fits _ (NilAbove _) = True
840 fits n (TextBeside _ sl p) = fits (n -# sl) p
841 fits _ _ = panic "fits: Unhandled case"
844 @first@ and @nonEmptySet@ are similar to @nicest@ and @fits@, only simpler.
845 @first@ returns its first argument if it is non-empty, otherwise its second.
848 first :: Doc -> Doc -> Doc
849 first p q | nonEmptySet p = p
852 nonEmptySet :: Doc -> Bool
853 nonEmptySet NoDoc = False
854 nonEmptySet (_ `Union` _) = True
855 nonEmptySet Empty = True
856 nonEmptySet (NilAbove _) = True -- NoDoc always in first line
857 nonEmptySet (TextBeside _ _ p) = nonEmptySet p
858 nonEmptySet (Nest _ p) = nonEmptySet p
859 nonEmptySet _ = panic "nonEmptySet: Unhandled case"
862 @oneLiner@ returns the one-line members of the given set of @Doc@s.
865 oneLiner :: Doc -> Doc
866 oneLiner NoDoc = NoDoc
867 oneLiner Empty = Empty
868 oneLiner (NilAbove _) = NoDoc
869 oneLiner (TextBeside s sl p) = textBeside_ s sl (oneLiner p)
870 oneLiner (Nest k p) = nest_ k (oneLiner p)
871 oneLiner (p `Union` _) = oneLiner p
872 oneLiner _ = panic "oneLiner: Unhandled case"
877 %*********************************************************
879 \subsection{Displaying the best layout}
881 %*********************************************************
886 renderStyle Style{mode, lineLength, ribbonsPerLine} doc
887 = fullRender mode lineLength ribbonsPerLine doc ""
890 render doc = showDocWith PageMode doc
892 showDoc :: Doc -> String -> String
893 showDoc doc rest = showDocWithAppend PageMode doc rest
895 showDocWithAppend :: Mode -> Doc -> String -> String
896 showDocWithAppend mode doc rest = fullRender mode 100 1.5 string_txt rest doc
898 showDocWith :: Mode -> Doc -> String
899 showDocWith mode doc = showDocWithAppend mode doc ""
901 string_txt :: TextDetails -> String -> String
902 string_txt (Chr c) s = c:s
903 string_txt (Str s1) s2 = s1 ++ s2
904 string_txt (PStr s1) s2 = unpackFS s1 ++ s2
905 string_txt (LStr s1 _) s2 = unpackLitString s1 ++ s2
910 fullRender OneLineMode _ _ txt end doc
911 = lay (reduceDoc doc)
913 lay NoDoc = cant_fail
914 lay (Union _ q) = lay q -- Second arg can't be NoDoc
915 lay (Nest _ p) = lay p
917 lay (NilAbove p) = space_text `txt` lay p -- NoDoc always on
919 lay (TextBeside s _ p) = s `txt` lay p
920 lay _ = panic "fullRender/OneLineMode/lay: Unhandled case"
922 fullRender LeftMode _ _ txt end doc
923 = lay (reduceDoc doc)
925 lay NoDoc = cant_fail
926 lay (Union p q) = lay (first p q)
927 lay (Nest _ p) = lay p
929 lay (NilAbove p) = nl_text `txt` lay p -- NoDoc always on first line
930 lay (TextBeside s _ p) = s `txt` lay p
931 lay _ = panic "fullRender/LeftMode/lay: Unhandled case"
933 fullRender mode line_length ribbons_per_line txt end doc
934 = display mode line_length ribbon_length txt end best_doc
936 best_doc = best hacked_line_length ribbon_length (reduceDoc doc)
938 hacked_line_length, ribbon_length :: Int
939 ribbon_length = round (fromIntegral line_length / ribbons_per_line)
940 hacked_line_length = case mode of
941 ZigZagMode -> maxBound
944 display :: Mode -> Int -> Int -> (TextDetails -> t -> t) -> t -> Doc -> t
945 display mode page_width ribbon_width txt end doc
946 = case (iUnbox page_width) -# (iUnbox ribbon_width) of { gap_width ->
947 case gap_width `quotFastInt` _ILIT(2) of { shift ->
949 lay k (Nest k1 p) = lay (k +# k1) p
952 lay k (NilAbove p) = nl_text `txt` lay k p
954 lay k (TextBeside s sl p)
956 ZigZagMode | k >=# gap_width
958 Str (multi_ch shift '/') `txt` (
960 lay1 (k -# shift) s sl p)))
964 Str (multi_ch shift '\\') `txt` (
966 lay1 (k +# shift) s sl p )))
969 lay _ _ = panic "display/lay: Unhandled case"
971 lay1 k s sl p = indent k (s `txt` lay2 (k +# sl) p)
973 lay2 k (NilAbove p) = nl_text `txt` lay k p
974 lay2 k (TextBeside s sl p) = s `txt` (lay2 (k +# sl) p)
975 lay2 k (Nest _ p) = lay2 k p
977 lay2 _ _ = panic "display/lay2: Unhandled case"
979 -- optimise long indentations using LitString chunks of 8 spaces
980 indent n r | n >=# _ILIT(8) = LStr (sLit " ") (_ILIT(8)) `txt`
981 indent (n -# _ILIT(8)) r
982 | otherwise = Str (spaces n) `txt` r
988 cant_fail = error "easy_display: NoDoc"
990 multi_ch :: Int# -> Char -> String
991 multi_ch n ch | n <=# _ILIT(0) = ""
992 | otherwise = ch : multi_ch (n -# _ILIT(1)) ch
994 spaces :: Int# -> String
995 spaces n | n <=# _ILIT(0) = ""
996 | otherwise = ' ' : spaces (n -# _ILIT(1))
1002 pprCols = 100 -- could make configurable
1004 printDoc :: Mode -> Handle -> Doc -> IO ()
1005 printDoc LeftMode hdl doc
1006 = do { printLeftRender hdl doc; hFlush hdl }
1007 printDoc mode hdl doc
1008 = do { fullRender mode pprCols 1.5 put done doc ;
1011 put (Chr c) next = hPutChar hdl c >> next
1012 put (Str s) next = hPutStr hdl s >> next
1013 put (PStr s) next = hPutStr hdl (unpackFS s) >> next
1014 -- NB. not hPutFS, we want this to go through
1015 -- the I/O library's encoding layer. (#3398)
1016 put (LStr s l) next = hPutLitString hdl s l >> next
1018 done = hPutChar hdl '\n'
1020 -- some versions of hPutBuf will barf if the length is zero
1021 hPutLitString :: Handle -> Ptr a -> Int# -> IO ()
1022 hPutLitString handle a l = if l ==# _ILIT(0)
1024 else hPutBuf handle a (iBox l)
1026 -- Printing output in LeftMode is performance critical: it's used when
1027 -- dumping C and assembly output, so we allow ourselves a few dirty
1030 -- (1) we specialise fullRender for LeftMode with IO output.
1032 -- (2) we add a layer of buffering on top of Handles. Handles
1033 -- don't perform well with lots of hPutChars, which is mostly
1034 -- what we're doing here, because Handles have to be thread-safe
1035 -- and async exception-safe. We only have a single thread and don't
1036 -- care about exceptions, so we add a layer of fast buffering
1037 -- over the Handle interface.
1039 -- (3) a few hacks in layLeft below to convince GHC to generate the right
1042 printLeftRender :: Handle -> Doc -> IO ()
1043 printLeftRender hdl doc = do
1044 b <- newBufHandle hdl
1048 bufLeftRender :: BufHandle -> Doc -> IO ()
1049 bufLeftRender b doc = layLeft b (reduceDoc doc)
1051 -- HACK ALERT! the "return () >>" below convinces GHC to eta-expand
1052 -- this function with the IO state lambda. Otherwise we end up with
1053 -- closures in all the case branches.
1054 layLeft :: BufHandle -> Doc -> IO ()
1055 layLeft b _ | b `seq` False = undefined -- make it strict in b
1056 layLeft _ NoDoc = cant_fail
1057 layLeft b (Union p q) = return () >> layLeft b (first p q)
1058 layLeft b (Nest _ p) = return () >> layLeft b p
1059 layLeft b Empty = bPutChar b '\n'
1060 layLeft b (NilAbove p) = bPutChar b '\n' >> layLeft b p
1061 layLeft b (TextBeside s _ p) = put b s >> layLeft b p
1063 put b _ | b `seq` False = undefined
1064 put b (Chr c) = bPutChar b c
1065 put b (Str s) = bPutStr b s
1066 put b (PStr s) = bPutFS b s
1067 put b (LStr s l) = bPutLitString b s l
1068 layLeft _ _ = panic "layLeft: Unhandled case"