{-# OPTIONS_HADDOCK not-home #-}
{- ---------------------------------------------------------------------------

Module      :  Text.PrettyPrint.HughesPJ
Copyright   :  (c) The University of Glasgow 2001
License     :  BSD-style (see the file libraries/base/LICENSE) -}
--
{- Maintainer  :  David Terei <dave.terei@gmail.com>
Stability   :  stable
Portability :  portable -}
--
-- John Hughes's and Simon Peyton Jones's Pretty Printer Combinators
--
{- Based on /The Design of a Pretty-printing Library/
in Advanced Functional Programming,
Johan Jeuring and Erik Meijer (eds), LNCS 925
<http://www.cs.chalmers.se/~rjmh/Papers/pretty.ps> -}
--
-- Heavily modified by Simon Peyton Jones (December 1996).
--
-- ---------------------------------------------------------------------------

{-
Version 3.0     28 May 1997
  * Cured massive performance bug.  If you write

        foldl <> empty (map (text.show) [1..10000])

    you get quadratic behaviour with V2.0.  Why?  For just the same
    reason as you get quadratic behaviour with left-associated (++)
    chains.

    This is really bad news.  One thing a pretty-printer abstraction
    should certainly guarantee is insensitivity to associativity.  It
    matters: suddenly GHC's compilation times went up by a factor of
    100 when I switched to the new pretty printer.

    I fixed it with a bit of a hack (because I wanted to get GHC back
    on the road).  I added two new constructors to the Doc type, Above
    and Beside:

         <> = Beside
         $$ = Above

    Then, where I need to get to a "TextBeside" or "NilAbove" form I
    "force" the Doc to squeeze out these suspended calls to Beside and
    Above; but in so doing I re-associate. It's quite simple, but I'm
    not satisfied that I've done the best possible job.  I'll send you
    the code if you are interested.

  * Added new exports:
        punctuate, hang
        int, integer, float, double, rational,
        lparen, rparen, lbrack, rbrack, lbrace, rbrace,

  * fullRender's type signature has changed.  Rather than producing a
    string it now takes an extra couple of arguments that tells it how
    to glue fragments of output together:

        fullRender :: Mode
                   -> Int                       -- Line length
                   -> Float                     -- Ribbons per line
                   -> (TextDetails -> a -> a)   -- What to do with text
                   -> a                         -- What to do at the end
                   -> Doc
                   -> a                         -- Result

    The "fragments" are encapsulated in the TextDetails data type:

        data TextDetails = Chr  Char
                         | Str  String
                         | PStr FAST_STRING

    The Chr and Str constructors are obvious enough.  The PStr
    constructor has a packed string (FAST_STRING) inside it.  It's
    generated by using the new "ptext" export.

    An advantage of this new setup is that you can get the renderer to
    do output directly (by passing in a function of type (TextDetails
    -> IO () -> IO ()), rather than producing a string that you then
    print.


Version 2.0     24 April 1997
  * Made empty into a left unit for <> as well as a right unit;
    it is also now true that
        nest k empty = empty
    which wasn't true before.

  * Fixed an obscure bug in sep that occassionally gave very weird behaviour

  * Added $+$

  * Corrected and tidied up the laws and invariants

======================================================================
Relative to John's original paper, there are the following new features:

1.  There's an empty document, "empty".  It's a left and right unit for
    both <> and $$, and anywhere in the argument list for
    sep, hcat, hsep, vcat, fcat etc.

    It is Really Useful in practice.

2.  There is a paragraph-fill combinator, fsep, that's much like sep,
    only it keeps fitting things on one line until it can't fit any more.

3.  Some random useful extra combinators are provided.
        <+> puts its arguments beside each other with a space between them,
            unless either argument is empty in which case it returns the other


        hcat is a list version of <>
        hsep is a list version of <+>
        vcat is a list version of $$

        sep (separate) is either like hsep or like vcat, depending on what fits

        cat  behaves like sep,  but it uses <> for horizontal composition
        fcat behaves like fsep, but it uses <> for horizontal composition

        These new ones do the obvious things:
                char, semi, comma, colon, space,
                parens, brackets, braces,
                quotes, doubleQuotes

4.  The "above" combinator, $$, now overlaps its two arguments if the
    last line of the top argument stops before the first line of the
    second begins.

        For example:  text "hi" $$ nest 5 (text "there")
        lays out as
                        hi   there
        rather than
                        hi
                             there

        There are two places this is really useful

        a) When making labelled blocks, like this:
                Left ->   code for left
                Right ->  code for right
                LongLongLongLabel ->
                          code for longlonglonglabel
           The block is on the same line as the label if the label is
           short, but on the next line otherwise.

        b) When laying out lists like this:
                [ first
                , second
                , third
                ]
           which some people like.  But if the list fits on one line
           you want [first, second, third].  You can't do this with
           John's original combinators, but it's quite easy with the
           new $$.

        The combinator $+$ gives the original "never-overlap" behaviour.

5.      Several different renderers are provided:
                * a standard one
                * one that uses cut-marks to avoid deeply-nested documents
                        simply piling up in the right-hand margin
                * one that ignores indentation
                        (fewer chars output; good for machines)
                * one that ignores indentation and newlines
                        (ditto, only more so)

6.      Numerous implementation tidy-ups
        Use of unboxed data types to speed up the implementation
-}

module Common.Lib.Pretty (

        -- * The document type
        Doc,

        -- * Constructing documents

        -- ** Converting values into documents
        char, text, ptext, sizedText, zeroWidthText,
        int, integer, float, double, rational,

        -- ** Simple derived documents
        semi, comma, colon, space, equals,
        lparen, rparen, lbrack, rbrack, lbrace, rbrace,

        -- ** Wrapping documents in delimiters
        parens, brackets, braces, quotes, doubleQuotes,

        -- ** Combining documents
        empty,
        (<>), (<+>), hcat, hsep,
        ($$), ($+$), vcat,
        sep, cat,
        fsep, fcat,
        nest,
        hang, punctuate,

        -- * Predicates on documents
        isEmpty,

        -- * Rendering documents

        -- ** Default rendering
        render,

        -- ** Rendering with a particular style
        Style (..),
        style,
        renderStyle,

        -- ** General rendering
        fullRender,
        Mode (..), TextDetails (..)

    ) where


import Prelude
import Data.Monoid ()
import Data.String ( IsString (fromString) )

infixl 6 <+>
infixl 5 $$, $+$

{- ---------------------------------------------------------------------------
The interface -}

-- The primitive Doc values

isEmpty :: Doc -> Bool;  -- ^ Returns 'True' if the document is empty

{- | The empty document, with no height and no width.
'empty' is the identity for '<>', '<+>', '$$' and '$+$', and anywhere
in the argument list for 'sep', 'hcat', 'hsep', 'vcat', 'fcat' etc. -}
empty :: Doc

semi :: Doc;                 -- ^ A ';' character
comma :: Doc;                 -- ^ A ',' character
colon :: Doc;                 -- ^ A ':' character
space :: Doc;                 -- ^ A space character
equals :: Doc;                 -- ^ A '=' character
lparen :: Doc;                 -- ^ A '(' character
rparen :: Doc;                 -- ^ A ')' character
lbrack :: Doc;                 -- ^ A '[' character
rbrack :: Doc;                 -- ^ A ']' character
lbrace :: Doc;                 -- ^ A '{' character
rbrace :: Doc;                 -- ^ A '}' character

-- | A document of height and width 1, containing a literal character.
char :: Char -> Doc

{- | A document of height 1 containing a literal string.
'text' satisfies the following laws: -}
--
-- * @'text' s '<>' 'text' t = 'text' (s'++'t)@
--
-- * @'text' \"\" '<>' x = x@, if @x@ non-empty
--
{- The side condition on the last law is necessary because @'text' \"\"@
has height 1, while 'empty' has no height. -}
text :: String -> Doc

instance IsString Doc where
    fromString :: String -> Doc
fromString = String -> Doc
text

-- | An obsolete function, now identical to 'text'.
ptext :: String -> Doc

-- | Some text with any width. (@text s = sizedText (length s) s@)
sizedText :: Int -> String -> Doc

{- | Some text, but without any width. Use for non-printing text
such as a HTML or Latex tags -}
zeroWidthText :: String -> Doc

int :: Int -> Doc;    -- ^ @int n = text (show n)@
integer :: Integer -> Doc;    -- ^ @integer n = text (show n)@
float :: Float -> Doc;    -- ^ @float n = text (show n)@
double :: Double -> Doc;    -- ^ @double n = text (show n)@
rational :: Rational -> Doc;    -- ^ @rational n = text (show n)@

parens :: Doc -> Doc;     -- ^ Wrap document in @(...)@
brackets :: Doc -> Doc;     -- ^ Wrap document in @[...]@
braces :: Doc -> Doc;     -- ^ Wrap document in @{...}@
quotes :: Doc -> Doc;     -- ^ Wrap document in @\'...\'@
doubleQuotes :: Doc -> Doc;     -- ^ Wrap document in @\"...\"@

-- Combining @Doc@ values

instance Semigroup Doc where
    p :: Doc
p <> :: Doc -> Doc -> Doc
<> q :: Doc
q = Doc -> Bool -> Doc -> Doc
beside_ Doc
p Bool
False Doc
q

instance Monoid Doc where
    mempty :: Doc
mempty = Doc
empty

{- | Beside.
'<>' is associative, with identity 'empty'. -}
-- (<>) :: Doc -> Doc -> Doc   -- see Semigroup instance above

{- | Beside, separated by space, unless one of the arguments is 'empty'.
'<+>' is associative, with identity 'empty'. -}
(<+>) :: Doc -> Doc -> Doc

{- | Above, except that if the last line of the first argument stops
at least one position before the first line of the second begins,
these two lines are overlapped.  For example: -}
--
-- >    text "hi" $$ nest 5 (text "there")
--
-- lays out as
--
-- >    hi   there
--
-- rather than
--
{- >    hi
>         there -}
--
-- '$$' is associative, with identity 'empty', and also satisfies
--
-- * @(x '$$' y) '<>' z = x '$$' (y '<>' z)@, if @y@ non-empty.
--
($$) :: Doc -> Doc -> Doc

{- | Above, with no overlapping.
'$+$' is associative, with identity 'empty'. -}
($+$) :: Doc -> Doc -> Doc

hcat :: [Doc] -> Doc;          -- ^List version of '<>'.
hsep :: [Doc] -> Doc;          -- ^List version of '<+>'.
vcat :: [Doc] -> Doc;          -- ^List version of '$$'.

cat :: [Doc] -> Doc;          -- ^ Either 'hcat' or 'vcat'.
sep :: [Doc] -> Doc;          -- ^ Either 'hsep' or 'vcat'.
fcat :: [Doc] -> Doc;          -- ^ \"Paragraph fill\" version of 'cat'.
fsep :: [Doc] -> Doc;          -- ^ \"Paragraph fill\" version of 'sep'.

{- | Nest (or indent) a document by a given number of positions
(which may also be negative).  'nest' satisfies the laws: -}
--
-- * @'nest' 0 x = x@
--
-- * @'nest' k ('nest' k' x) = 'nest' (k+k') x@
--
-- * @'nest' k (x '<>' y) = 'nest' k z '<>' 'nest' k y@
--
-- * @'nest' k (x '$$' y) = 'nest' k x '$$' 'nest' k y@
--
-- * @'nest' k 'empty' = 'empty'@
--
-- * @x '<>' 'nest' k y = x '<>' y@, if @x@ non-empty
--
{- The side condition on the last law is needed because
'empty' is a left identity for '<>'. -}
nest :: Int -> Doc -> Doc

-- GHC-specific ones.

-- | @hang d1 n d2 = sep [d1, nest n d2]@
hang :: Doc -> Int -> Doc -> Doc

-- | @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@
punctuate :: Doc -> [Doc] -> [Doc]


-- Displaying @Doc@ values.

instance Show Doc where
  showsPrec :: Int -> Doc -> ShowS
showsPrec _ = Doc -> ShowS
showDoc

-- | Renders the document as a string using the default 'style'.
render :: Doc -> String

-- | The general rendering interface.
fullRender :: Mode                      -- ^ Rendering mode
           -> Int                       -- ^ Line length
           -> Float                     -- ^ Ribbons per line
           -> (TextDetails -> a -> a)   -- ^ What to do with text
           -> a                         -- ^ What to do at the end
           -> Doc                       -- ^ The document
           -> a                         -- ^ Result

-- | Render the document as a string using a specified style.
renderStyle :: Style -> Doc -> String

-- | A rendering style.
data Style
 = Style { Style -> Mode
mode :: Mode     -- ^ The rendering mode
         , Style -> Int
lineLength :: Int      -- ^ Length of line, in chars
         , Style -> Float
ribbonsPerLine :: Float    -- ^ Ratio of ribbon length to line length
         }

-- | The default style (@mode=PageMode, lineLength=100, ribbonsPerLine=1.5@).
style :: Style
style :: Style
style = Style :: Mode -> Int -> Float -> Style
Style { lineLength :: Int
lineLength = 100, ribbonsPerLine :: Float
ribbonsPerLine = 1.5, mode :: Mode
mode = Mode
PageMode }

-- | Rendering mode.
data Mode = PageMode            -- ^ Normal
          | ZigZagMode          -- ^ With zig-zag cuts
          | LeftMode            -- ^ No indentation, infinitely long lines
          | OneLineMode         -- ^ All on one line

{- ---------------------------------------------------------------------------
The Doc calculus -}

-- The Doc combinators satisfy the following laws:

{-
Laws for $$
~~~~~~~~~~~
<a1>    (x $$ y) $$ z   = x $$ (y $$ z)
<a2>    empty $$ x      = x
<a3>    x $$ empty      = x

        ...ditto $+$...

Laws for <>
~~~~~~~~~~~
<b1>    (x <> y) <> z   = x <> (y <> z)
<b2>    empty <> x      = empty
<b3>    x <> empty      = x

        ...ditto <+>...

Laws for text
~~~~~~~~~~~~~
<t1>    text s <> text t        = text (s++t)
<t2>    text "" <> x            = x, if x non-empty

** because of law n6, t2 only holds if x doesn't
** start with `nest'.


Laws for nest
~~~~~~~~~~~~~
<n1>    nest 0 x                = x
<n2>    nest k (nest k' x)      = nest (k+k') x
<n3>    nest k (x <> y)         = nest k x <> nest k y
<n4>    nest k (x $$ y)         = nest k x $$ nest k y
<n5>    nest k empty            = empty
<n6>    x <> nest k y           = x <> y, if x non-empty

** Note the side condition on <n6>!  It is this that
** makes it OK for empty to be a left unit for <>.

Miscellaneous
~~~~~~~~~~~~~
<m1>    (text s <> x) $$ y = text s <> ((text "" <> x) $$
                                         nest (-length s) y)

<m2>    (x $$ y) <> z = x $$ (y <> z)
        if y non-empty


Laws for list versions
~~~~~~~~~~~~~~~~~~~~~~
<l1>    sep (ps++[empty]++qs)   = sep (ps ++ qs)
        ...ditto hsep, hcat, vcat, fill...

<l2>    nest k (sep ps) = sep (map (nest k) ps)
        ...ditto hsep, hcat, vcat, fill...

Laws for oneLiner
~~~~~~~~~~~~~~~~~
<o1>    oneLiner (nest k p) = nest k (oneLiner p)
<o2>    oneLiner (x <> y)   = oneLiner x <> oneLiner y

You might think that the following verion of <m1> would
be neater:

<3 NO>  (text s <> x) $$ y = text s <> ((empty <> x)) $$
                                         nest (-length s) y)

But it doesn't work, for if x=empty, we would have

        text s $$ y = text s <> (empty $$ nest (-length s) y)
                    = text s <> nest (-length s) y
-}

{- ---------------------------------------------------------------------------
Simple derived definitions -}

semi :: Doc
semi = Char -> Doc
char ';'
colon :: Doc
colon = Char -> Doc
char ':'
comma :: Doc
comma = Char -> Doc
char ','
space :: Doc
space = Char -> Doc
char ' '
equals :: Doc
equals = Char -> Doc
char '='
lparen :: Doc
lparen = Char -> Doc
char '('
rparen :: Doc
rparen = Char -> Doc
char ')'
lbrack :: Doc
lbrack = Char -> Doc
char '['
rbrack :: Doc
rbrack = Char -> Doc
char ']'
lbrace :: Doc
lbrace = Char -> Doc
char '{'
rbrace :: Doc
rbrace = Char -> Doc
char '}'

int :: Int -> Doc
int n :: Int
n = String -> Doc
text (Int -> String
forall a. Show a => a -> String
show Int
n)
integer :: Integer -> Doc
integer n :: Integer
n = String -> Doc
text (Integer -> String
forall a. Show a => a -> String
show Integer
n)
float :: Float -> Doc
float n :: Float
n = String -> Doc
text (Float -> String
forall a. Show a => a -> String
show Float
n)
double :: Double -> Doc
double n :: Double
n = String -> Doc
text (Double -> String
forall a. Show a => a -> String
show Double
n)
rational :: Rational -> Doc
rational n :: Rational
n = String -> Doc
text (Rational -> String
forall a. Show a => a -> String
show Rational
n)
{- SIGBJORN wrote instead:
rational n = text (show (fromRationalX n)) -}

quotes :: Doc -> Doc
quotes p :: Doc
p = Char -> Doc
char '\'' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Char -> Doc
char '\''
doubleQuotes :: Doc -> Doc
doubleQuotes p :: Doc
p = Char -> Doc
char '"' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Char -> Doc
char '"'
parens :: Doc -> Doc
parens p :: Doc
p = Char -> Doc
char '(' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Char -> Doc
char ')'
brackets :: Doc -> Doc
brackets p :: Doc
p = Char -> Doc
char '[' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Char -> Doc
char ']'
braces :: Doc -> Doc
braces p :: Doc
p = Char -> Doc
char '{' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Char -> Doc
char '}'

-- lazy list versions
hcat :: [Doc] -> Doc
hcat = Doc -> Doc
reduceAB (Doc -> Doc) -> ([Doc] -> Doc) -> [Doc] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Doc -> Doc -> Doc) -> Doc -> [Doc] -> Doc
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Bool -> Doc -> Doc -> Doc
beside_' Bool
False) Doc
empty
hsep :: [Doc] -> Doc
hsep = Doc -> Doc
reduceAB (Doc -> Doc) -> ([Doc] -> Doc) -> [Doc] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Doc -> Doc -> Doc) -> Doc -> [Doc] -> Doc
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Bool -> Doc -> Doc -> Doc
beside_' Bool
True) Doc
empty
vcat :: [Doc] -> Doc
vcat = Doc -> Doc
reduceAB (Doc -> Doc) -> ([Doc] -> Doc) -> [Doc] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Doc -> Doc -> Doc) -> Doc -> [Doc] -> Doc
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr (Bool -> Doc -> Doc -> Doc
above_' Bool
False) Doc
empty

beside_' :: Bool -> Doc -> Doc -> Doc
beside_' :: Bool -> Doc -> Doc -> Doc
beside_' _ p :: Doc
p Empty = Doc
p
beside_' g :: Bool
g p :: Doc
p q :: Doc
q = Doc -> Bool -> Doc -> Doc
Beside Doc
p Bool
g Doc
q

above_' :: Bool -> Doc -> Doc -> Doc
above_' :: Bool -> Doc -> Doc -> Doc
above_' _ p :: Doc
p Empty = Doc
p
above_' g :: Bool
g p :: Doc
p q :: Doc
q = Doc -> Bool -> Doc -> Doc
Above Doc
p Bool
g Doc
q

reduceAB :: Doc -> Doc
reduceAB :: Doc -> Doc
reduceAB (Above Empty _ q :: Doc
q) = Doc
q
reduceAB (Beside Empty _ q :: Doc
q) = Doc
q
reduceAB doc :: Doc
doc = Doc
doc

hang :: Doc -> Int -> Doc -> Doc
hang d1 :: Doc
d1 n :: Int
n d2 :: Doc
d2 = [Doc] -> Doc
sep [Doc
d1, Int -> Doc -> Doc
nest Int
n Doc
d2]

punctuate :: Doc -> [Doc] -> [Doc]
punctuate _ [] = []
punctuate p :: Doc
p (d :: Doc
d : ds :: [Doc]
ds) = Doc -> [Doc] -> [Doc]
go Doc
d [Doc]
ds
                   where
                     go :: Doc -> [Doc] -> [Doc]
go d' :: Doc
d' [] = [Doc
d']
                     go d' :: Doc
d' (e :: Doc
e : es :: [Doc]
es) = (Doc
d' Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
p) Doc -> [Doc] -> [Doc]
forall a. a -> [a] -> [a]
: Doc -> [Doc] -> [Doc]
go Doc
e [Doc]
es

{- ---------------------------------------------------------------------------
The Doc data type -}

{- A Doc represents a *set* of layouts.  A Doc with
no occurrences of Union or NoDoc represents just one layout. -}

{- | The abstract type of documents.
The 'Show' instance is equivalent to using 'render'. -}
data Doc
 = Empty                                -- empty
 | NilAbove Doc                         -- text "" $$ x
 | TextBeside TextDetails !Int Doc      -- text s <> x
 | Nest !Int Doc                        -- nest k x
 | Union Doc Doc                        -- ul `union` ur
 | NoDoc                                -- The empty set of documents
 | Beside Doc Bool Doc                  -- True <=> space between
 | Above Doc Bool Doc                  -- True <=> never overlap

-- RDoc is a "reduced Doc", guaranteed not to have a top-level Above or Beside
type RDoc = Doc


reduceDoc :: Doc -> RDoc
reduceDoc :: Doc -> Doc
reduceDoc (Beside p :: Doc
p g :: Bool
g q :: Doc
q) = Doc -> Bool -> Doc -> Doc
beside Doc
p Bool
g (Doc -> Doc
reduceDoc Doc
q)
reduceDoc (Above p :: Doc
p g :: Bool
g q :: Doc
q) = Doc -> Bool -> Doc -> Doc
above Doc
p Bool
g (Doc -> Doc
reduceDoc Doc
q)
reduceDoc p :: Doc
p = Doc
p


-- | The TextDetails data type
--
{- A TextDetails represents a fragment of text that will be
output at some point. -}
data TextDetails = Chr Char   -- ^ A single Char fragment
                 | Str String -- ^ A whole String fragment
                 | PStr String {- ^ Used to represent a Fast String fragment
                               but now deprecated and identical to the
                               Str constructor. -}

space_text, nl_text :: TextDetails
space_text :: TextDetails
space_text = Char -> TextDetails
Chr ' '
nl_text :: TextDetails
nl_text = Char -> TextDetails
Chr '\n'

{-
  Here are the invariants:

  1) The argument of NilAbove is never Empty. Therefore
     a NilAbove occupies at least two lines.

  2) The argument of @TextBeside@ is never @Nest@.


  3) The layouts of the two arguments of @Union@ both flatten to the same
     string.

  4) The arguments of @Union@ are either @TextBeside@, or @NilAbove@.

  5) A @NoDoc@ may only appear on the first line of the left argument of an
     union. Therefore, the right argument of an union can never be equivalent
     to the empty set (@NoDoc@).

  6) An empty document is always represented by @Empty@.  It can't be
     hidden inside a @Nest@, or a @Union@ of two @Empty@s.

  7) The first line of every layout in the left argument of @Union@ is
     longer than the first line of any layout in the right argument.
     (1) ensures that the left argument has a first line.  In view of
     (3), this invariant means that the right argument must have at
     least two lines.
-}

-- Invariant: Args to the 4 functions below are always RDocs
nilAbove_ :: RDoc -> RDoc
nilAbove_ :: Doc -> Doc
nilAbove_ = Doc -> Doc
NilAbove

        -- Arg of a TextBeside is always an RDoc
textBeside_ :: TextDetails -> Int -> RDoc -> RDoc
textBeside_ :: TextDetails -> Int -> Doc -> Doc
textBeside_ = TextDetails -> Int -> Doc -> Doc
TextBeside

nest_ :: Int -> RDoc -> RDoc
nest_ :: Int -> Doc -> Doc
nest_ = Int -> Doc -> Doc
Nest

union_ :: RDoc -> RDoc -> RDoc
union_ :: Doc -> Doc -> Doc
union_ = Doc -> Doc -> Doc
Union


{- Notice the difference between
NoDoc (no documents)
Empty (one empty document; no height and no width)
text "" (a document containing the empty string;
one line high, but has no width) -}


{- ---------------------------------------------------------------------------
@empty@, @text@, @nest@, @union@ -}

empty :: Doc
empty = Doc
Empty

isEmpty :: Doc -> Bool
isEmpty Empty = Bool
True
isEmpty _ = Bool
False

char :: Char -> Doc
char c :: Char
c = TextDetails -> Int -> Doc -> Doc
textBeside_ (Char -> TextDetails
Chr Char
c) 1 Doc
Empty
text :: String -> Doc
text s :: String
s = case String -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
s of {sl :: Int
sl -> TextDetails -> Int -> Doc -> Doc
textBeside_ (String -> TextDetails
Str String
s) Int
sl Doc
Empty}
ptext :: String -> Doc
ptext s :: String
s = case String -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length String
s of {sl :: Int
sl -> TextDetails -> Int -> Doc -> Doc
textBeside_ (String -> TextDetails
PStr String
s) Int
sl Doc
Empty}
sizedText :: Int -> String -> Doc
sizedText l :: Int
l s :: String
s = TextDetails -> Int -> Doc -> Doc
textBeside_ (String -> TextDetails
Str String
s) Int
l Doc
Empty
zeroWidthText :: String -> Doc
zeroWidthText = Int -> String -> Doc
sizedText 0

nest :: Int -> Doc -> Doc
nest k :: Int
k p :: Doc
p = Int -> Doc -> Doc
mkNest Int
k (Doc -> Doc
reduceDoc Doc
p)        -- Externally callable version

-- mkNest checks for Nest's invariant that it doesn't have an Empty inside it
mkNest :: Int -> Doc -> Doc
mkNest :: Int -> Doc -> Doc
mkNest k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
mkNest k :: Int
k (Nest k1 :: Int
k1 p :: Doc
p) = Int -> Doc -> Doc
mkNest (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
k1) Doc
p
mkNest _ NoDoc = Doc
NoDoc
mkNest _ Empty = Doc
Empty
mkNest 0 p :: Doc
p = Doc
p                  -- Worth a try!
mkNest k :: Int
k p :: Doc
p = Int -> Doc -> Doc
nest_ Int
k Doc
p

-- mkUnion checks for an empty document
mkUnion :: Doc -> Doc -> Doc
mkUnion :: Doc -> Doc -> Doc
mkUnion Empty _ = Doc
Empty
mkUnion p :: Doc
p q :: Doc
q = Doc
p Doc -> Doc -> Doc
`union_` Doc
q

{- ---------------------------------------------------------------------------
Vertical composition @$$@ -}

above_ :: Doc -> Bool -> Doc -> Doc
above_ :: Doc -> Bool -> Doc -> Doc
above_ p :: Doc
p _ Empty = Doc
p
above_ Empty _ q :: Doc
q = Doc
q
above_ p :: Doc
p g :: Bool
g q :: Doc
q = Doc -> Bool -> Doc -> Doc
Above Doc
p Bool
g Doc
q

p :: Doc
p $$ :: Doc -> Doc -> Doc
$$ q :: Doc
q = Doc -> Bool -> Doc -> Doc
above_ Doc
p Bool
False Doc
q
p :: Doc
p $+$ :: Doc -> Doc -> Doc
$+$ q :: Doc
q = Doc -> Bool -> Doc -> Doc
above_ Doc
p Bool
True Doc
q

above :: Doc -> Bool -> RDoc -> RDoc
above :: Doc -> Bool -> Doc -> Doc
above (Above p :: Doc
p g1 :: Bool
g1 q1 :: Doc
q1) g2 :: Bool
g2 q2 :: Doc
q2 = Doc -> Bool -> Doc -> Doc
above Doc
p Bool
g1 (Doc -> Bool -> Doc -> Doc
above Doc
q1 Bool
g2 Doc
q2)
above p :: Doc
p@(Beside {}) g :: Bool
g q :: Doc
q = Doc -> Bool -> Int -> Doc -> Doc
aboveNest (Doc -> Doc
reduceDoc Doc
p) Bool
g 0 (Doc -> Doc
reduceDoc Doc
q)
above p :: Doc
p g :: Bool
g q :: Doc
q = Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
g 0 (Doc -> Doc
reduceDoc Doc
q)

aboveNest :: RDoc -> Bool -> Int -> RDoc -> RDoc
-- Specfication: aboveNest p g k q = p $g$ (nest k q)

aboveNest :: Doc -> Bool -> Int -> Doc -> Doc
aboveNest _ _ k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
aboveNest NoDoc _ _ _ = Doc
NoDoc
aboveNest (p1 :: Doc
p1 `Union` p2 :: Doc
p2) g :: Bool
g k :: Int
k q :: Doc
q = Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p1 Bool
g Int
k Doc
q Doc -> Doc -> Doc
`union_`
                                      Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p2 Bool
g Int
k Doc
q

aboveNest Empty _ k :: Int
k q :: Doc
q = Int -> Doc -> Doc
mkNest Int
k Doc
q
aboveNest (Nest k1 :: Int
k1 p :: Doc
p) g :: Bool
g k :: Int
k q :: Doc
q = Int -> Doc -> Doc
nest_ Int
k1 (Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
g (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
k1) Doc
q)
                                  -- p can't be Empty, so no need for mkNest

aboveNest (NilAbove p :: Doc
p) g :: Bool
g k :: Int
k q :: Doc
q = Doc -> Doc
nilAbove_ (Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
g Int
k Doc
q)
aboveNest (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) g :: Bool
g k :: Int
k q :: Doc
q = Int
k1 Int -> Doc -> Doc
forall a b. a -> b -> b
`seq` TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl Doc
rest
                                    where
                                      k1 :: Int
k1 = Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl
                                      rest :: Doc
rest = case Doc
p of
                                                Empty -> Bool -> Int -> Doc -> Doc
nilAboveNest Bool
g Int
k1 Doc
q
                                                _ -> Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
g Int
k1 Doc
q
aboveNest (Above {}) _ _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "aboveNest Above"
aboveNest (Beside {}) _ _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "aboveNest Beside"


nilAboveNest :: Bool -> Int -> RDoc -> RDoc
{- Specification: text s <> nilaboveNest g k q
= text s <> (text "" $g$ nest k q) -}

nilAboveNest :: Bool -> Int -> Doc -> Doc
nilAboveNest _ k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
nilAboveNest _ _ Empty = Doc
Empty
                               -- Here's why the "text s <>" is in the spec!
nilAboveNest g :: Bool
g k :: Int
k (Nest k1 :: Int
k1 q :: Doc
q) = Bool -> Int -> Doc -> Doc
nilAboveNest Bool
g (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
k1) Doc
q

nilAboveNest g :: Bool
g k :: Int
k q :: Doc
q | Bool -> Bool
not Bool
g Bool -> Bool -> Bool
&& Int
k Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0      -- No newline if no overlap
                             = TextDetails -> Int -> Doc -> Doc
textBeside_ (String -> TextDetails
Str (Int -> String
indent Int
k)) Int
k Doc
q
                             | Bool
otherwise           -- Put them really above
                             = Doc -> Doc
nilAbove_ (Int -> Doc -> Doc
mkNest Int
k Doc
q)

{- ---------------------------------------------------------------------------
Horizontal composition @<>@ -}

beside_ :: Doc -> Bool -> Doc -> Doc
beside_ :: Doc -> Bool -> Doc -> Doc
beside_ p :: Doc
p _ Empty = Doc
p
beside_ Empty _ q :: Doc
q = Doc
q
beside_ p :: Doc
p g :: Bool
g q :: Doc
q = Doc -> Bool -> Doc -> Doc
Beside Doc
p Bool
g Doc
q

p :: Doc
p <+> :: Doc -> Doc -> Doc
<+> q :: Doc
q = Doc -> Bool -> Doc -> Doc
beside_ Doc
p Bool
True Doc
q

beside :: Doc -> Bool -> RDoc -> RDoc
-- Specification: beside g p q = p <g> q

beside :: Doc -> Bool -> Doc -> Doc
beside NoDoc _ _ = Doc
NoDoc
beside (p1 :: Doc
p1 `Union` p2 :: Doc
p2) g :: Bool
g q :: Doc
q = Doc -> Bool -> Doc -> Doc
beside Doc
p1 Bool
g Doc
q Doc -> Doc -> Doc
`union_` Doc -> Bool -> Doc -> Doc
beside Doc
p2 Bool
g Doc
q
beside Empty _ q :: Doc
q = Doc
q
beside (Nest k :: Int
k p :: Doc
p) g :: Bool
g q :: Doc
q = Int -> Doc -> Doc
nest_ Int
k (Doc -> Bool -> Doc -> Doc
beside Doc
p Bool
g Doc
q)       -- p non-empty
beside p :: Doc
p@(Beside p1 :: Doc
p1 g1 :: Bool
g1 q1 :: Doc
q1) g2 :: Bool
g2 q2 :: Doc
q2
           {- (A `op1` B) `op2` C == A `op1` (B `op2` C)  iff op1 == op2
                                             [ && (op1 == <> || op1 == <+>) ] -}
         | Bool
g1 Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
g2 = Doc -> Bool -> Doc -> Doc
beside Doc
p1 Bool
g1 (Doc -> Bool -> Doc -> Doc
beside Doc
q1 Bool
g2 Doc
q2)
         | Bool
otherwise = Doc -> Bool -> Doc -> Doc
beside (Doc -> Doc
reduceDoc Doc
p) Bool
g2 Doc
q2
beside p :: Doc
p@(Above {}) g :: Bool
g q :: Doc
q = Doc -> Bool -> Doc -> Doc
beside (Doc -> Doc
reduceDoc Doc
p) Bool
g Doc
q
beside (NilAbove p :: Doc
p) g :: Bool
g q :: Doc
q = Doc -> Doc
nilAbove_ (Doc -> Bool -> Doc -> Doc
beside Doc
p Bool
g Doc
q)
beside (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) g :: Bool
g q :: Doc
q = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl Doc
rest
                               where
                                  rest :: Doc
rest = case Doc
p of
                                           Empty -> Bool -> Doc -> Doc
nilBeside Bool
g Doc
q
                                           _ -> Doc -> Bool -> Doc -> Doc
beside Doc
p Bool
g Doc
q


nilBeside :: Bool -> RDoc -> RDoc
{- Specification: text "" <> nilBeside g p
= text "" <g> p -}

nilBeside :: Bool -> Doc -> Doc
nilBeside _ Empty = Doc
Empty  -- Hence the text "" in the spec
nilBeside g :: Bool
g (Nest _ p :: Doc
p) = Bool -> Doc -> Doc
nilBeside Bool
g Doc
p
nilBeside g :: Bool
g p :: Doc
p | Bool
g = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
space_text 1 Doc
p
                       | Bool
otherwise = Doc
p

{- ---------------------------------------------------------------------------
Separate, @sep@, Hughes version -}

{- Specification: sep ps  = oneLiner (hsep ps)
`union`
vcat ps -}

sep :: [Doc] -> Doc
sep = Bool -> [Doc] -> Doc
sepX Bool
True         -- Separate with spaces
cat :: [Doc] -> Doc
cat = Bool -> [Doc] -> Doc
sepX Bool
False        -- Don't

sepX :: Bool -> [Doc] -> Doc
sepX :: Bool -> [Doc] -> Doc
sepX _ [] = Doc
empty
sepX x :: Bool
x (p :: Doc
p : ps :: [Doc]
ps) = Bool -> Doc -> Int -> [Doc] -> Doc
sep1 Bool
x (Doc -> Doc
reduceDoc Doc
p) 0 [Doc]
ps


{- Specification: sep1 g k ys = sep (x : map (nest k) ys)
= oneLiner (x <g> nest k (hsep ys))
`union` x $$ nest k (vcat ys) -}

sep1 :: Bool -> RDoc -> Int -> [Doc] -> RDoc
sep1 :: Bool -> Doc -> Int -> [Doc] -> Doc
sep1 _ _ k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
sep1 _ NoDoc _ _ = Doc
NoDoc
sep1 g :: Bool
g (p :: Doc
p `Union` q :: Doc
q) k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
sep1 Bool
g Doc
p Int
k [Doc]
ys
                                  Doc -> Doc -> Doc
`union_`
                                  Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
q Bool
False Int
k (Doc -> Doc
reduceDoc ([Doc] -> Doc
vcat [Doc]
ys))

sep1 g :: Bool
g Empty k :: Int
k ys :: [Doc]
ys = Int -> Doc -> Doc
mkNest Int
k (Bool -> [Doc] -> Doc
sepX Bool
g [Doc]
ys)
sep1 g :: Bool
g (Nest n :: Int
n p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Int -> Doc -> Doc
nest_ Int
n (Bool -> Doc -> Int -> [Doc] -> Doc
sep1 Bool
g Doc
p (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
n) [Doc]
ys)

sep1 _ (NilAbove p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Doc -> Doc
nilAbove_
                                  (Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
False Int
k (Doc -> Doc
reduceDoc ([Doc] -> Doc
vcat [Doc]
ys)))
sep1 g :: Bool
g (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) k :: Int
k ys :: [Doc]
ys = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl (Bool -> Doc -> Int -> [Doc] -> Doc
sepNB Bool
g Doc
p (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl) [Doc]
ys)
sep1 _ (Above {}) _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "sep1 Above"
sep1 _ (Beside {}) _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "sep1 Beside"

{- Specification: sepNB p k ys = sep1 (text "" <> p) k ys
Called when we have already found some text in the first item
We have to eat up nests -}

sepNB :: Bool -> Doc -> Int -> [Doc] -> Doc

sepNB :: Bool -> Doc -> Int -> [Doc] -> Doc
sepNB g :: Bool
g (Nest _ p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
sepNB Bool
g Doc
p Int
k [Doc]
ys
                            -- Never triggered, because of invariant (2)

sepNB g :: Bool
g Empty k :: Int
k ys :: [Doc]
ys = Doc -> Doc
oneLiner (Bool -> Doc -> Doc
nilBeside Bool
g (Doc -> Doc
reduceDoc Doc
rest))
                                Doc -> Doc -> Doc
`mkUnion`
                            Bool -> Int -> Doc -> Doc
nilAboveNest Bool
True Int
k (Doc -> Doc
reduceDoc ([Doc] -> Doc
vcat [Doc]
ys))
                          where
                            rest :: Doc
rest | Bool
g = [Doc] -> Doc
hsep [Doc]
ys
                                 | Bool
otherwise = [Doc] -> Doc
hcat [Doc]
ys

sepNB g :: Bool
g p :: Doc
p k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
sep1 Bool
g Doc
p Int
k [Doc]
ys

{- ---------------------------------------------------------------------------
@fill@ -}

fsep :: [Doc] -> Doc
fsep = Bool -> [Doc] -> Doc
fill Bool
True
fcat :: [Doc] -> Doc
fcat = Bool -> [Doc] -> Doc
fill Bool
False

-- Specification:
--
-- fill g docs = fillIndent 0 docs
--
{- fillIndent k [] = []
fillIndent k [p] = p
fillIndent k (p1:p2:ps) =
oneLiner p1 <g> fillIndent (k + length p1 + g ? 1 : 0)
(remove_nests (oneLiner p2) : ps)
`Union`
(p1 $*$ nest (-k) (fillIndent 0 ps)) -}
--
{- $*$ is defined for layouts (not Docs) as
layout1 $*$ layout2 | hasMoreThanOneLine layout1 = layout1 $$ layout2
otherwise                  = layout1 $+$ layout2 -}

fill :: Bool -> [Doc] -> RDoc
fill :: Bool -> [Doc] -> Doc
fill _ [] = Doc
empty
fill g :: Bool
g (p :: Doc
p : ps :: [Doc]
ps) = Bool -> Doc -> Int -> [Doc] -> Doc
fill1 Bool
g (Doc -> Doc
reduceDoc Doc
p) 0 [Doc]
ps


fill1 :: Bool -> RDoc -> Int -> [Doc] -> Doc
fill1 :: Bool -> Doc -> Int -> [Doc] -> Doc
fill1 _ _ k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
fill1 _ NoDoc _ _ = Doc
NoDoc
fill1 g :: Bool
g (p :: Doc
p `Union` q :: Doc
q) k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
fill1 Bool
g Doc
p Int
k [Doc]
ys
                                   Doc -> Doc -> Doc
`union_`
                                   Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
q Bool
False Int
k (Bool -> [Doc] -> Doc
fill Bool
g [Doc]
ys)

fill1 g :: Bool
g Empty k :: Int
k ys :: [Doc]
ys = Int -> Doc -> Doc
mkNest Int
k (Bool -> [Doc] -> Doc
fill Bool
g [Doc]
ys)
fill1 g :: Bool
g (Nest n :: Int
n p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Int -> Doc -> Doc
nest_ Int
n (Bool -> Doc -> Int -> [Doc] -> Doc
fill1 Bool
g Doc
p (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
n) [Doc]
ys)

fill1 g :: Bool
g (NilAbove p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Doc -> Doc
nilAbove_ (Doc -> Bool -> Int -> Doc -> Doc
aboveNest Doc
p Bool
False Int
k (Bool -> [Doc] -> Doc
fill Bool
g [Doc]
ys))
fill1 g :: Bool
g (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) k :: Int
k ys :: [Doc]
ys = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl (Bool -> Doc -> Int -> [Doc] -> Doc
fillNB Bool
g Doc
p (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl) [Doc]
ys)
fill1 _ (Above {}) _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "fill1 Above"
fill1 _ (Beside {}) _ _ = String -> Doc
forall a. HasCallStack => String -> a
error "fill1 Beside"

fillNB :: Bool -> Doc -> Int -> [Doc] -> Doc
fillNB :: Bool -> Doc -> Int -> [Doc] -> Doc
fillNB _ _ k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = Doc
forall a. HasCallStack => a
undefined
fillNB g :: Bool
g (Nest _ p :: Doc
p) k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
fillNB Bool
g Doc
p Int
k [Doc]
ys
                             -- Never triggered, because of invariant (2)
fillNB _ Empty _ [] = Doc
Empty
fillNB g :: Bool
g Empty k :: Int
k (Empty : ys :: [Doc]
ys) = Bool -> Doc -> Int -> [Doc] -> Doc
fillNB Bool
g Doc
Empty Int
k [Doc]
ys
fillNB g :: Bool
g Empty k :: Int
k (y :: Doc
y : ys :: [Doc]
ys) = Bool -> Int -> Doc -> [Doc] -> Doc
fillNBE Bool
g Int
k Doc
y [Doc]
ys
fillNB g :: Bool
g p :: Doc
p k :: Int
k ys :: [Doc]
ys = Bool -> Doc -> Int -> [Doc] -> Doc
fill1 Bool
g Doc
p Int
k [Doc]
ys

fillNBE :: Bool -> Int -> Doc -> [Doc] -> Doc
fillNBE :: Bool -> Int -> Doc -> [Doc] -> Doc
fillNBE g :: Bool
g k :: Int
k y :: Doc
y ys :: [Doc]
ys = Bool -> Doc -> Doc
nilBeside Bool
g
                             (Bool -> Doc -> Int -> [Doc] -> Doc
fill1 Bool
g ((Doc -> Doc
elideNest (Doc -> Doc) -> (Doc -> Doc) -> Doc -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Doc -> Doc
oneLiner (Doc -> Doc) -> (Doc -> Doc) -> Doc -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Doc -> Doc
reduceDoc) Doc
y)
                                      Int
k1 [Doc]
ys)
                             Doc -> Doc -> Doc
`mkUnion`
                             Bool -> Int -> Doc -> Doc
nilAboveNest Bool
True Int
k (Bool -> [Doc] -> Doc
fill Bool
g (Doc
y Doc -> [Doc] -> [Doc]
forall a. a -> [a] -> [a]
: [Doc]
ys))
                           where
                             k1 :: Int
k1 | Bool
g = Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- 1
                                | Bool
otherwise = Int
k

elideNest :: Doc -> Doc
elideNest :: Doc -> Doc
elideNest (Nest _ d :: Doc
d) = Doc
d
elideNest d :: Doc
d = Doc
d

{- ---------------------------------------------------------------------------
Selecting the best layout -}

best :: Mode
     -> Int             -- Line length
     -> Int             -- Ribbon length
     -> RDoc
     -> RDoc            -- No unions in here!

best :: Mode -> Int -> Int -> Doc -> Doc
best OneLineMode _ _ p0 :: Doc
p0
  = Doc -> Doc
get Doc
p0 -- unused, due to the use of easy_display in full_render
  where
    get :: Doc -> Doc
get Empty = Doc
Empty
    get NoDoc = Doc
NoDoc
    get (NilAbove p :: Doc
p) = Doc -> Doc
nilAbove_ (Doc -> Doc
get Doc
p)
    get (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl (Doc -> Doc
get Doc
p)
    get (Nest _ p :: Doc
p) = Doc -> Doc
get Doc
p             -- Elide nest
    get (p :: Doc
p `Union` q :: Doc
q) = Doc -> Doc -> Doc
first (Doc -> Doc
get Doc
p) (Doc -> Doc
get Doc
q)
    get (Above {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best OneLineMode get Above"
    get (Beside {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best OneLineMode get Beside"

best _ w0 :: Int
w0 r :: Int
r p0 :: Doc
p0
  = Int -> Doc -> Doc
get Int
w0 Doc
p0
  where
    get :: Int          -- (Remaining) width of line
        -> Doc -> Doc
    get :: Int -> Doc -> Doc
get w :: Int
w _ | Int
w Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0 Bool -> Bool -> Bool
&& Bool
False = Doc
forall a. HasCallStack => a
undefined
    get _ Empty = Doc
Empty
    get _ NoDoc = Doc
NoDoc
    get w :: Int
w (NilAbove p :: Doc
p) = Doc -> Doc
nilAbove_ (Int -> Doc -> Doc
get Int
w Doc
p)
    get w :: Int
w (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl (Int -> Int -> Doc -> Doc
get1 Int
w Int
sl Doc
p)
    get w :: Int
w (Nest k :: Int
k p :: Doc
p) = Int -> Doc -> Doc
nest_ Int
k (Int -> Doc -> Doc
get (Int
w Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
k) Doc
p)
    get w :: Int
w (p :: Doc
p `Union` q :: Doc
q) = Int -> Int -> Doc -> Doc -> Doc
nicest Int
w Int
r (Int -> Doc -> Doc
get Int
w Doc
p) (Int -> Doc -> Doc
get Int
w Doc
q)
    get _ (Above {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best get Above"
    get _ (Beside {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best get Beside"

    get1 :: Int         -- (Remaining) width of line
         -> Int         -- Amount of first line already eaten up
         -> Doc         -- This is an argument to TextBeside => eat Nests
         -> Doc         -- No unions in here!

    get1 :: Int -> Int -> Doc -> Doc
get1 w :: Int
w _ _ | Int
w Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0 Bool -> Bool -> Bool
&& Bool
False = Doc
forall a. HasCallStack => a
undefined
    get1 _ _ Empty = Doc
Empty
    get1 _ _ NoDoc = Doc
NoDoc
    get1 w :: Int
w sl :: Int
sl (NilAbove p :: Doc
p) = Doc -> Doc
nilAbove_ (Int -> Doc -> Doc
get (Int
w Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl) Doc
p)
    get1 w :: Int
w sl :: Int
sl (TextBeside t :: TextDetails
t tl :: Int
tl p :: Doc
p) = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
t Int
tl (Int -> Int -> Doc -> Doc
get1 Int
w (Int
sl Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
tl) Doc
p)
    get1 w :: Int
w sl :: Int
sl (Nest _ p :: Doc
p) = Int -> Int -> Doc -> Doc
get1 Int
w Int
sl Doc
p
    get1 w :: Int
w sl :: Int
sl (p :: Doc
p `Union` q :: Doc
q) = Int -> Int -> Int -> Doc -> Doc -> Doc
nicest1 Int
w Int
r Int
sl (Int -> Int -> Doc -> Doc
get1 Int
w Int
sl Doc
p)
                                                   (Int -> Int -> Doc -> Doc
get1 Int
w Int
sl Doc
q)
    get1 _ _ (Above {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best get1 Above"
    get1 _ _ (Beside {}) = String -> Doc
forall a. HasCallStack => String -> a
error "best get1 Beside"

nicest :: Int -> Int -> Doc -> Doc -> Doc
nicest :: Int -> Int -> Doc -> Doc -> Doc
nicest w :: Int
w r :: Int
r = Int -> Int -> Int -> Doc -> Doc -> Doc
nicest1 Int
w Int
r 0

nicest1 :: Int -> Int -> Int -> Doc -> Doc -> Doc
nicest1 :: Int -> Int -> Int -> Doc -> Doc -> Doc
nicest1 w :: Int
w r :: Int
r sl :: Int
sl p :: Doc
p q :: Doc
q | Int -> Doc -> Bool
fits ((Int
w Int -> Int -> Int
`minn` Int
r) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl) Doc
p = Doc
p
                   | Bool
otherwise = Doc
q

fits :: Int     -- Space available
     -> Doc
     -> Bool    -- True if *first line* of Doc fits in space available

fits :: Int -> Doc -> Bool
fits n :: Int
n _ | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< 0 = Bool
False
fits _ NoDoc = Bool
False
fits _ Empty = Bool
True
fits _ (NilAbove _) = Bool
True
fits n :: Int
n (TextBeside _ sl :: Int
sl p :: Doc
p) = Int -> Doc -> Bool
fits (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
sl) Doc
p
fits _ (Above {}) = String -> Bool
forall a. HasCallStack => String -> a
error "fits Above"
fits _ (Beside {}) = String -> Bool
forall a. HasCallStack => String -> a
error "fits Beside"
fits _ (Union {}) = String -> Bool
forall a. HasCallStack => String -> a
error "fits Union"
fits _ (Nest {}) = String -> Bool
forall a. HasCallStack => String -> a
error "fits Nest"

minn :: Int -> Int -> Int
minn :: Int -> Int -> Int
minn x :: Int
x y :: Int
y | Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
y = Int
x
         | Bool
otherwise = Int
y

{- @first@ and @nonEmptySet@ are similar to @nicest@ and @fits@, only simpler.
@first@ returns its first argument if it is non-empty, otherwise its second. -}

first :: Doc -> Doc -> Doc
first :: Doc -> Doc -> Doc
first p :: Doc
p q :: Doc
q | Doc -> Bool
nonEmptySet Doc
p = Doc
p -- unused, because (get OneLineMode) is unused
          | Bool
otherwise = Doc
q

nonEmptySet :: Doc -> Bool
nonEmptySet :: Doc -> Bool
nonEmptySet NoDoc = Bool
False
nonEmptySet (_ `Union` _) = Bool
True
nonEmptySet Empty = Bool
True
nonEmptySet (NilAbove _) = Bool
True           -- NoDoc always in first line
nonEmptySet (TextBeside _ _ p :: Doc
p) = Doc -> Bool
nonEmptySet Doc
p
nonEmptySet (Nest _ p :: Doc
p) = Doc -> Bool
nonEmptySet Doc
p
nonEmptySet (Above {}) = String -> Bool
forall a. HasCallStack => String -> a
error "nonEmptySet Above"
nonEmptySet (Beside {}) = String -> Bool
forall a. HasCallStack => String -> a
error "nonEmptySet Beside"

-- @oneLiner@ returns the one-line members of the given set of @Doc@s.

oneLiner :: Doc -> Doc
oneLiner :: Doc -> Doc
oneLiner NoDoc = Doc
NoDoc
oneLiner Empty = Doc
Empty
oneLiner (NilAbove _) = Doc
NoDoc
oneLiner (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) = TextDetails -> Int -> Doc -> Doc
textBeside_ TextDetails
s Int
sl (Doc -> Doc
oneLiner Doc
p)
oneLiner (Nest k :: Int
k p :: Doc
p) = Int -> Doc -> Doc
nest_ Int
k (Doc -> Doc
oneLiner Doc
p)
oneLiner (p :: Doc
p `Union` _) = Doc -> Doc
oneLiner Doc
p
oneLiner (Above {}) = String -> Doc
forall a. HasCallStack => String -> a
error "oneLiner Above"
oneLiner (Beside {}) = String -> Doc
forall a. HasCallStack => String -> a
error "oneLiner Beside"


{- ---------------------------------------------------------------------------
Displaying the best layout -}

renderStyle :: Style -> Doc -> String
renderStyle the_style :: Style
the_style
  = Mode
-> Int
-> Float
-> (TextDetails -> ShowS)
-> String
-> Doc
-> String
forall a.
Mode -> Int -> Float -> (TextDetails -> a -> a) -> a -> Doc -> a
fullRender (Style -> Mode
mode Style
the_style)
               (Style -> Int
lineLength Style
the_style)
               (Style -> Float
ribbonsPerLine Style
the_style)
               TextDetails -> ShowS
string_txt
               ""

render :: Doc -> String
render doc :: Doc
doc = Doc -> ShowS
showDoc Doc
doc ""

showDoc :: Doc -> String -> String
showDoc :: Doc -> ShowS
showDoc doc :: Doc
doc rest :: String
rest = Mode
-> Int
-> Float
-> (TextDetails -> ShowS)
-> String
-> Doc
-> String
forall a.
Mode -> Int -> Float -> (TextDetails -> a -> a) -> a -> Doc -> a
fullRender Mode
PageMode 100 1.5 TextDetails -> ShowS
string_txt String
rest Doc
doc

string_txt :: TextDetails -> String -> String
string_txt :: TextDetails -> ShowS
string_txt (Chr c :: Char
c) s :: String
s = Char
c Char -> ShowS
forall a. a -> [a] -> [a]
: String
s
string_txt (Str s1 :: String
s1) s2 :: String
s2 = String
s1 String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
s2
string_txt (PStr s1 :: String
s1) s2 :: String
s2 = String
s1 String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
s2


fullRender :: Mode -> Int -> Float -> (TextDetails -> a -> a) -> a -> Doc -> a
fullRender OneLineMode _ _ txt :: TextDetails -> a -> a
txt end :: a
end doc :: Doc
doc
  = TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
forall a. TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
easy_display TextDetails
space_text TextDetails -> a -> a
txt a
end (Doc -> Doc
reduceDoc Doc
doc)
fullRender LeftMode _ _ txt :: TextDetails -> a -> a
txt end :: a
end doc :: Doc
doc
  = TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
forall a. TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
easy_display TextDetails
nl_text TextDetails -> a -> a
txt a
end (Doc -> Doc
reduceDoc Doc
doc)

fullRender the_mode :: Mode
the_mode line_length :: Int
line_length ribbons_per_line :: Float
ribbons_per_line txt :: TextDetails -> a -> a
txt end :: a
end doc :: Doc
doc
  = Mode -> Int -> Int -> (TextDetails -> a -> a) -> a -> Doc -> a
forall a.
Mode -> Int -> Int -> (TextDetails -> a -> a) -> a -> Doc -> a
display Mode
the_mode Int
line_length Int
ribbon_length TextDetails -> a -> a
txt a
end Doc
best_doc
  where
    best_doc :: Doc
best_doc = Mode -> Int -> Int -> Doc -> Doc
best Mode
the_mode Int
hacked_line_length Int
ribbon_length (Doc -> Doc
reduceDoc Doc
doc)

    hacked_line_length, ribbon_length :: Int
    ribbon_length :: Int
ribbon_length = Float -> Int
forall a b. (RealFrac a, Integral b) => a -> b
round (Int -> Float
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
line_length Float -> Float -> Float
forall a. Fractional a => a -> a -> a
/ Float
ribbons_per_line)
    hacked_line_length :: Int
hacked_line_length = case Mode
the_mode of
                         ZigZagMode -> Int
forall a. Bounded a => a
maxBound
                         _ -> Int
line_length

display :: Mode -> Int -> Int -> (TextDetails -> a -> a) -> a -> Doc -> a
display :: Mode -> Int -> Int -> (TextDetails -> a -> a) -> a -> Doc -> a
display the_mode :: Mode
the_mode page_width :: Int
page_width ribbon_width :: Int
ribbon_width txt :: TextDetails -> a -> a
txt end :: a
end doc :: Doc
doc
  = case Int
page_width Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
ribbon_width of { gap_width :: Int
gap_width ->
    case Int
gap_width Int -> Int -> Int
forall a. Integral a => a -> a -> a
`quot` 2 of { shift :: Int
shift ->
    let
        lay :: Int -> Doc -> a
lay k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = a
forall a. HasCallStack => a
undefined
        lay k :: Int
k (Nest k1 :: Int
k1 p :: Doc
p) = Int -> Doc -> a
lay (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
k1) Doc
p
        lay _ Empty = a
end
        lay _ (Above {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay Above"
        lay _ (Beside {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay Beside"
        lay _ NoDoc = String -> a
forall a. HasCallStack => String -> a
error "display lay NoDoc"
        lay _ (Union {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay Union"

        lay k :: Int
k (NilAbove p :: Doc
p) = TextDetails
nl_text TextDetails -> a -> a
`txt` Int -> Doc -> a
lay Int
k Doc
p

        lay k :: Int
k (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p)
            = case Mode
the_mode of
                    ZigZagMode | Int
k Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
gap_width
                               -> TextDetails
nl_text TextDetails -> a -> a
`txt` (
                                  String -> TextDetails
Str (Int -> Char -> String
forall a. Int -> a -> [a]
replicate Int
shift '/') TextDetails -> a -> a
`txt` (
                                  TextDetails
nl_text TextDetails -> a -> a
`txt`
                                  Int -> TextDetails -> Int -> Doc -> a
lay1 (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
shift) TextDetails
s Int
sl Doc
p ))

                               | Int
k Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< 0
                               -> TextDetails
nl_text TextDetails -> a -> a
`txt` (
                                  String -> TextDetails
Str (Int -> Char -> String
forall a. Int -> a -> [a]
replicate Int
shift '\\') TextDetails -> a -> a
`txt` (
                                  TextDetails
nl_text TextDetails -> a -> a
`txt`
                                  Int -> TextDetails -> Int -> Doc -> a
lay1 (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
shift) TextDetails
s Int
sl Doc
p ))

                    _ -> Int -> TextDetails -> Int -> Doc -> a
lay1 Int
k TextDetails
s Int
sl Doc
p

        lay1 :: Int -> TextDetails -> Int -> Doc -> a
lay1 k :: Int
k _ sl :: Int
sl _ | Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sl Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = a
forall a. HasCallStack => a
undefined
        lay1 k :: Int
k s :: TextDetails
s sl :: Int
sl p :: Doc
p = String -> TextDetails
Str (Int -> String
indent Int
k) TextDetails -> a -> a
`txt` (TextDetails
s TextDetails -> a -> a
`txt` Int -> Doc -> a
lay2 (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sl) Doc
p)

        lay2 :: Int -> Doc -> a
lay2 k :: Int
k _ | Int
k Int -> Bool -> Bool
forall a b. a -> b -> b
`seq` Bool
False = a
forall a. HasCallStack => a
undefined
        lay2 k :: Int
k (NilAbove p :: Doc
p) = TextDetails
nl_text TextDetails -> a -> a
`txt` Int -> Doc -> a
lay Int
k Doc
p
        lay2 k :: Int
k (TextBeside s :: TextDetails
s sl :: Int
sl p :: Doc
p) = TextDetails
s TextDetails -> a -> a
`txt` Int -> Doc -> a
lay2 (Int
k Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
sl) Doc
p
        lay2 k :: Int
k (Nest _ p :: Doc
p) = Int -> Doc -> a
lay2 Int
k Doc
p
        lay2 _ Empty = a
end
        lay2 _ (Above {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay2 Above"
        lay2 _ (Beside {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay2 Beside"
        lay2 _ NoDoc = String -> a
forall a. HasCallStack => String -> a
error "display lay2 NoDoc"
        lay2 _ (Union {}) = String -> a
forall a. HasCallStack => String -> a
error "display lay2 Union"
    in
    Int -> Doc -> a
lay 0 Doc
doc
    }}

cant_fail :: a
cant_fail :: a
cant_fail = String -> a
forall a. HasCallStack => String -> a
error "easy_display: NoDoc"

easy_display :: TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
easy_display :: TextDetails -> (TextDetails -> a -> a) -> a -> Doc -> a
easy_display nl_space_text :: TextDetails
nl_space_text txt :: TextDetails -> a -> a
txt end :: a
end doc :: Doc
doc
  = Doc -> a -> a
lay Doc
doc a
forall a. a
cant_fail
  where
    lay :: Doc -> a -> a
lay NoDoc no_doc :: a
no_doc = a
no_doc
    lay (Union _p :: Doc
_p q :: Doc
q) _ = {- lay p -} Doc -> a -> a
lay Doc
q a
forall a. a
cant_fail
        -- Second arg can't be NoDoc
    lay (Nest _ p :: Doc
p) no_doc :: a
no_doc = Doc -> a -> a
lay Doc
p a
no_doc
    lay Empty _ = a
end
    lay (NilAbove p :: Doc
p) _ = TextDetails
nl_space_text TextDetails -> a -> a
`txt` Doc -> a -> a
lay Doc
p a
forall a. a
cant_fail
        -- NoDoc always on first line
    lay (TextBeside s :: TextDetails
s _ p :: Doc
p) no_doc :: a
no_doc = TextDetails
s TextDetails -> a -> a
`txt` Doc -> a -> a
lay Doc
p a
no_doc
    lay (Above {}) _ = String -> a
forall a. HasCallStack => String -> a
error "easy_display Above"
    lay (Beside {}) _ = String -> a
forall a. HasCallStack => String -> a
error "easy_display Beside"

-- an old version inserted tabs being 8 columns apart in the output.
indent :: Int -> String
indent :: Int -> String
indent n :: Int
n = Int -> Char -> String
forall a. Int -> a -> [a]
replicate Int
n ' '

{-
Q: What is the reason for negative indentation (i.e. argument to indent
   is < 0) ?

A:
This indicates an error in the library client's code.
If we compose a <> b, and the first line of b is more indented than some
other lines of b, the law <n6> (<> eats nests) may cause the pretty
printer to produce an invalid layout:

doc       |0123345
------------------
d1        |a...|
d2        |...b|
          |c...|

d1<>d2    |ab..|
         c|....|

Consider a <> b, let `s' be the length of the last line of `a', `k' the
indentation of the first line of b, and `k0' the indentation of the
left-most line b_i of b.

The produced layout will have negative indentation if `k - k0 > s', as
the first line of b will be put on the (s+1)th column, effectively
translating b horizontally by (k-s). Now if the i^th line of b has an
indentation k0 < (k-s), it is translated out-of-page, causing
`negative indentation'.
-}