tilia-0.2.0.0: src/Tilia/Render/Block.hs
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
-- | Runs of things: statements, bindings, equations, list elements.
module Tilia.Render.Block
( Bracing (..),
items,
braced,
itemsSepBy,
keepBlanks,
Rank (..),
ranked,
)
where
import Data.Choice (Choice, isTrue, pattern Without)
import Prelude hiding (break)
import Tilia.Doc.Combinators
import Tilia.Span
-- | May a block put braces around itself when it is laid out on one line?
data Bracing
= MayBrace
| NoBrace
deriving (Eq, Show)
-- | A block: one item per line when broken, semicolons when flat.
items :: Bracing -> [Doc] -> Doc
items = itemsSepBy (Without #semisWhenBroken)
-- | 'items', with control over whether the broken form carries semicolons
-- too.
itemsSepBy ::
-- | Semicolons in the broken layout as well?
Choice "semisWhenBroken" ->
-- | Whether the block may brace itself when flat.
Bracing ->
-- | The items.
[Doc] ->
Doc
itemsSepBy semisWhenBroken bracing xs = case (bracing, xs) of
(NoBrace, [x]) -> x
_ -> variant flatForm brokenForm
where
flatForm = case (bracing, xs) of
(MayBrace, []) -> opening <> closing
(NoBrace, []) -> mempty
(MayBrace, _) -> opening <> space <> joined <> space <> closing
(NoBrace, _) -> joined
opening = openingAt Nothing "{"
closing = closingAt Nothing "}"
joined = sepBy (txt ";" <> space) xs
brokenForm =
sepBy (includeWhen (isTrue semisWhenBroken) (txt ";") <> newline) xs
-- | A block written between braces, which keeps them: its items separated
-- by semicolons on one line, and across lines each after the first led by
-- one under the opening brace.
braced ::
-- | Where the braces were written.
(Maybe Span, Maybe Span) ->
-- | Was there an empty line between two items?
(Maybe Span -> Maybe Span -> Bool) ->
-- | Where each item was, and what it prints as.
[(Maybe Span, Doc)] ->
Doc
braced (o, c) blank = \case
[] -> openingAt o "{" <> closing
x : xs ->
openingAt o "{"
<> space
<> align
( mconcat
(keepBlanks blank (x : fmap led xs))
)
<> break
<> closing
where
closing = foldMap (emptyAnchor . endOf) c <> closingAt c "}"
led (here, d) = (here, separatingSemicolon <> d)
-- | Put back the empty lines the author left between items.
keepBlanks ::
-- | Was there an empty line between two items?
(Maybe Span -> Maybe Span -> Bool) ->
-- | Where each item was, and what it prints as.
[(Maybe Span, Doc)] ->
[Doc]
keepBlanks blank xs = zipWith gap (Nothing : fmap fst xs) xs
where
gap previous (here, d) =
includeWhen (blank previous here) (newline <> declDelimiter DeclSeparate)
<> d
-- | Where an item sits among its siblings.
data Rank
= Only
| First
| Middle
| Last
deriving (Eq, Show)
-- | Label each item of a list with its rank.
ranked :: [a] -> [(Rank, a)]
ranked [] = []
ranked [x] = [(Only, x)]
ranked (x : xs) = (First, x) : go xs
where
go [] = []
go [y] = [(Last, y)]
go (y : ys) = (Middle, y) : go ys