tilia-0.2.0.0: src/Tilia/Comments/Attach.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
-- | Attaching comments to a 'Doc'.
module Tilia.Comments.Attach
( attachComments,
attachScopedComments,
Margin (..),
commentText,
joinedLine,
)
where
import Control.Applicative ((<|>))
import Data.Bifunctor (first)
import Data.List.NonEmpty qualified as NE
import Data.Map.Strict qualified as Map
import Data.Maybe (isJust, listToMaybe)
import Data.Set qualified as Set
import Data.Text (Text)
import Tilia.Comments
import Tilia.Comments.Place
import Tilia.Doc
( BracketSide (..),
Doc (..),
SeparatorSide (..),
foldlChildren',
namesOnly,
printsNothing,
unwrap,
wrap,
pattern Cat,
)
import Tilia.Doc.Combinators
import Tilia.Span
-- | Attach comments to a 'Doc'.
attachComments :: [Comment] -> Doc -> Doc
attachComments = attachScopedComments noMargin (const ())
-- | What parts of a comment go at the margin.
data Margin = Margin
{ -- | A line of the module, by its number, that a comment written over it
-- prints at the margin, as a preprocessor directive written in one has
-- to: the preprocessor reads directives out of comments as well.
marginLine :: Int -> Bool,
-- | A comment that goes to the margin when it comes out right above a
-- preprocessor directive, which it then documents.
marginComment :: Comment -> Bool
}
-- | Nothing at the margin that the indentation does not put there.
noMargin :: Margin
noMargin = Margin (const False) (const False)
-- | Attach comments to a 'Doc', each only to a region in the same scope as
-- itself.
--
-- A scope is a part of the input a comment may not be carried out of, such
-- as one branch of a conditional: a comment written in a branch has to stay
-- among what that branch holds, and one written outside it must not end up
-- inside. Placement never looks past a comment's own scope, so where it
-- goes is decided among the regions it could be printed next to in every
-- configuration it is in.
attachScopedComments ::
Ord k =>
-- | What goes at the margin.
Margin ->
-- | The scope of what was written at a span.
(Span -> k) ->
-- | The comments to attach.
[Comment] ->
-- | The document to attach them to.
Doc ->
Doc
attachScopedComments margin scopeOf cs doc =
written <> closingComments margin (unplaced left)
where
(written, left) = walk margin placements doc
found = regionsOf doc
regions = reverse (regionsLocated found)
fences = reverse (regionsFenced found)
openings = reverse (regionsOpenings found)
gaps = findingsGapped (regionsFindings found)
leads = Map.fromList (findingsLeading (regionsFindings found))
elsewhere = Set.fromList (findingsElsewhere (regionsFindings found))
placements =
foldMap
( \k ->
placeComments
(inScope k rs)
leads
elsewhere
openings
gaps
(inScope k fs)
(inScope k xs)
)
(Set.toList (Map.keysSet rs <> Map.keysSet fs <> Map.keysSet xs))
rs = byScope id regions
fs = byScope id fences
xs = byScope commentSpan cs
byScope f ys =
reverse <$> Map.fromListWith (<>) [(scopeOf (f y), [y]) | y <- ys]
inScope = Map.findWithDefault []
-- | The comments nothing came to collect, written after everything.
closingComments ::
-- | What goes at the margin.
Margin ->
-- | The comments.
[Comment] ->
Doc
closingComments margin = foldMap $ \c -> commentDoc c (ownLines margin True c)
-- | What attachment learns of the regions of a document, in one walk over
-- it in the order it prints, each list most recent first.
data Regions = Regions
{ -- | Every 'DLocated'.
regionsLocated :: [Span],
-- | Every 'DFence'.
regionsFenced :: [Span],
-- | Every opening bracket.
regionsOpenings :: [Span],
-- | What the walk finds more seldom.
regionsFindings :: !Findings,
-- | The region that finished printing last, if no directive came since.
regionsAbove :: !(Maybe Span),
-- | Whether the declarations have begun.
regionsBegun :: !Bool,
-- | What the walk passed in the innermost region or fence.
regionsPassed :: !Passed
}
-- | What 'regionsOf' finds more seldom than a region, each list most recent
-- first.
data Findings = Findings
{ -- | The region that finishes printing last before each
-- 'DDeclDelimiter' inside a region or among the declarations, where no
-- directive comes after it: the item an empty line is under, which the
-- parts of a module's header are not.
findingsGapped :: [Span],
-- | The innermost region each region prints first, where that one was
-- written above it, as the Haddock of a constructor, a field or an
-- argument is.
findingsLeading :: [(Span, Span)],
-- | The regions that do not print last what was written at their end,
-- where they print anything written that far, as a signature prints
-- the Haddock of its last argument under that argument.
findingsElsewhere :: [Span]
}
-- | What 'regionsOf' passed in the innermost region or fence.
data Passed = Passed
{ -- | The region printed last, and whether it prints what was written at
-- its end elsewhere.
passedLast :: !(Maybe (Span, Bool)),
-- | The region that ends furthest.
passedFurthest :: !(Maybe Span),
-- | The innermost region printed first, in the innermost region only:
-- a fence passes it on.
passedFirst :: !(Maybe Span)
}
-- | What attachment learns of the regions of a document.
regionsOf :: Doc -> Regions
regionsOf =
go False (Regions [] [] [] (Findings [] [] []) Nothing False nothingPassed)
where
nothingPassed = Passed Nothing Nothing Nothing
go inRegion r = \case
DLocated s d -> region inRegion s d r
DFence s d ->
let outer = regionsPassed r
inner =
go
inRegion
r
{ regionsFenced = s : regionsFenced r,
regionsPassed =
nothingPassed{passedFirst = passedFirst outer}
}
d
passed = regionsPassed inner
in inner
{ regionsPassed =
Passed
(Just (s, endsElsewhere s passed))
(furthest s outer passed)
(passedFirst passed)
}
DBracket OpeningBracket (Just s) d ->
go inRegion r{regionsOpenings = s : regionsOpenings r} d
DCppChoice _ bs e ->
let branch r' =
go inRegion r'{regionsAbove = Nothing, regionsBegun = begun}
begun = regionsBegun r
in (foldl' branch r (fmap snd bs <> [e]))
{ regionsAbove = Nothing,
regionsBegun = begun
}
DCppDirective{} -> r{regionsAbove = Nothing}
DDeclarationsStart -> r{regionsBegun = True}
DDeclDelimiter _
| inRegion || regionsBegun r,
Just above <- regionsAbove r ->
let f = regionsFindings r
in r
{ regionsFindings =
f{findingsGapped = above : findingsGapped f}
}
d -> foldlChildren' (go inRegion) r d
region inRegion s d r =
let gapped = not (zeroWidth s || isChoice d)
outer = regionsPassed r
inner =
go
(inRegion || gapped)
r
{ regionsLocated = s : regionsLocated r,
regionsPassed = nothingPassed
}
d
passed = regionsPassed inner
elsewhere = endsElsewhere s passed
led = case passedFirst passed of
Just h | startPoint h < startPoint s -> Just (s, h)
_ -> Nothing
f = regionsFindings inner
in inner
{ regionsFindings =
if elsewhere || isJust led
then
f
{ findingsLeading =
maybe id (:) led (findingsLeading f),
findingsElsewhere =
(if elsewhere then (s :) else id)
(findingsElsewhere f)
}
else f,
regionsAbove = if gapped then Just s else regionsAbove inner,
regionsPassed =
Passed
(Just (s, elsewhere))
(furthest s outer passed)
(passedFirst outer <|> passedFirst passed <|> Just s)
}
endsElsewhere s passed = case (passedLast passed, passedFurthest passed) of
(Just (l, further), Just f) ->
further || endPoint f >= endPoint s && endPoint l /= endPoint s
_ -> False
furthest s outer passed =
Just
$! maybe id endingLater (passedFurthest outer)
$ maybe id endingLater (passedFurthest passed) s
endingLater a b = if endPoint a <= endPoint b then b else a
isChoice = \case
DCppChoice{} -> True
_ -> False
-- | Write the placed comments into the document, each one around the region
-- it was given to. Taking is destructive: the 'Placements' is threaded
-- through the walk and a region's comments are removed as they are written,
-- so a span that occurs twice is served once. The two sides of a 'DVariant'
-- are the exception—they are one piece of code laid out two ways, so both
-- are walked from the same 'Placements' and both come out holding the
-- comment, and only one of them is ever printed. So are the alternatives of
-- a 'DCppChoice', for the same reason: no configuration prints two of them,
-- and a region the merge wrote into several of them is printed once in each
-- configuration, comments and all. What is still unwritten when the walk
-- ends is returned next to the resulting 'Doc'.
walk ::
-- | What goes at the margin.
Margin ->
-- | Where each comment goes.
Placements ->
-- | The document to write them into.
Doc ->
(Doc, Placements)
walk margin = go
where
go p d
| nothingPlaced p = (d, p)
| otherwise = step p d
step p = \case
DIndented n a b | not (namesOnly a) -> both (DIndented n) p a b
Cat a b -> both DCat p a b
DLocated s d -> case claimPlaced s p of
([], p') -> first (DLocated s) (go p' d)
(mine, p') ->
let (d', p'') = go p' d
write = foldMap (uncurry (writtenAs margin (zeroWidth s)))
before' = [(q, c) | (q, c) <- mine, q == Before]
after' =
[(q, c) | (q, c) <- mine, q /= Before, not (linedUpWithIt q)]
under' = [(q, c) | (q, c) <- mine, linedUpWithIt q]
linedUpWithIt = \case
Under ByTheRegion -> True
Under ByTheIndentation -> alignsItself d
_ -> False
withUnder
| null under' = id
| otherwise = \x -> align (x <> write under')
in ( write before' <> withUnder (DLocated s d' <> write after'),
p''
)
DCppChoice cs bs e ->
let bs' = [(c, go p d) | (c, d) <- bs]
(e', pe) = go p e
in ( DCppChoice cs [(c, d') | (c, (d', _)) <- bs'] e',
foldr (unclaimedByEither . snd . snd) pe bs'
)
DVariant a b ->
let (a', _) = go p a
(b', p') = go p b
in (DVariant a' b', p')
d
| Just (w, x) <- unwrap d -> first (wrap w) (go p x)
| otherwise -> (d, p)
both joined p a b
| leadsAnItem a,
(lifted@(_ : _), p0) <- foldl claimed ([], p) (openingRegions b) =
let (a', p') = go p0 a
(b', p'') = go p' b
in ( foldMap (\c -> commentDoc c (ownLines margin False c)) lifted
<> joined a' b',
p''
)
| Just o <- trailingRegion a,
Just s <- regionAfterBreak b <|> openingRegion b,
(passed@(_ : _), p0) <- claimAround o p =
let (a', p') = go p0 a
(b', p'') = go (placedBefore s passed p') b
in (joined a' b', p'')
| otherwise =
let (a', p') = go p a
(b', p'') = go p' b
in (joined a' b', p'')
claimed (cs, p) s = first (cs <>) (claimOwnLines s p)
-- | Does a document line its lines up under the column it begins at?
alignsItself :: Doc -> Bool
alignsItself = \case
DAligned 0 _ -> True
DLocated _ d -> alignsItself d
DFence _ d -> alignsItself d
DGroup _ d -> alignsItself d
_ -> False
-- | Is this a separator hung left of the item it leads, or a comma that
-- leads one where the merge put it in front, alone or after the place the
-- line may break before it?
leadsAnItem :: Doc -> Bool
leadsAnItem = \case
DCat DBreak' d -> leads d
d -> leads d
where
leads = \case
DSeparator LeadingSeparator (DAligned n _) _ -> n < 0
DSeparator LeadingSeparator l t ->
DSeparator TrailingSeparator l t == comma
_ -> False
-- | The region of a separator that trails the part before it, as an
-- operator does, whose comments go past it where one before it is on lines
-- of its own.
trailingRegion :: Doc -> Maybe Span
trailingRegion = \case
DReferent _ d -> trailingRegion d
DSeparator TrailingSeparator l _ -> openingRegion l
_ -> Nothing
-- | The outermost region that begins the line after the first place a
-- document breaks, laid out broken.
regionAfterBreak :: Doc -> Maybe Span
regionAfterBreak d = go False [d]
where
go broke = \case
[] -> Nothing
x : rest -> case x of
DLocated s y
| broke -> Just s
| otherwise -> go broke (y : rest)
DBreak -> go True rest
DBreak' -> go True rest
DNewline -> go True rest
DCat a b -> go broke (a : b : rest)
DIndented _ a b -> go broke (a : b : rest)
DVariant _ brokenD -> go broke (brokenD : rest)
_
| Just (_, y) <- unwrap x -> go broke (y : rest)
| otherwise -> go broke rest
-- | The outermost region a document prints first, past any in front that
-- print nothing, such as the anchor a branch opens with.
openingRegion :: Doc -> Maybe Span
openingRegion = listToMaybe . openingRegions
-- | The regions a document prints first, outermost first, past any in
-- front that print nothing.
openingRegions :: Doc -> [Span]
openingRegions = \case
DLocated s d -> s : openingRegions d
DCat a b -> after a b
DIndented _ a b | not (namesOnly a) -> after a b
DVariant _ b -> openingRegions b
d -> foldMap (openingRegions . snd) (unwrap d)
where
after a b
| printsNothing a = openingRegions b
| otherwise = openingRegions a
-- | Render one 'Comment' where it was placed.
writtenAs ::
-- | What goes at the margin.
Margin ->
-- | Does what follows only mark where the construct ends?
Bool ->
-- | Comment position.
Position ->
-- | The comment to render.
Comment ->
Doc
writtenAs margin atTheEnd position c = commentDoc c $ case placement of
InPlace -> case position of
Before ->
includeUnless glued space
<> DComment InPlace (commentSpan c) body
<> includeUnless atTheEnd space
_ -> space <> DComment InPlace (commentSpan c) body
EndsTheLine -> DComment EndsTheLine (commentSpan c) body <> gapBelow
HeldBack _ ->
DComment
placement
(commentSpan c)
(body <> includeWhen gapLeft (DVerbatimBreak AtIndent TrimWhitespace))
OnItsOwnLines _ -> ownLines margin atTheEnd c
where
placement = commentPlacement position c
glued = commentTrailing c && (not atTheEnd || commentFirstInBrackets c)
body = commentText margin c
gapBelow =
includeWhen
(commentGapBelow c && not atTheEnd)
(declDelimiter DeclSeparate)
gapLeft =
not (commentTrailing c)
&& not (commentJoined c)
&& commentGapBelow c
&& all ((> spanEndLine (commentSpan c) + 1) . fst) (commentNextLine c)
-- | A comment on lines of its own, with the empty lines its author left
-- around it.
ownLines ::
-- | What goes at the margin.
Margin ->
-- | Does what follows only mark where the construct ends?
Bool ->
-- | The comment.
Comment ->
Doc
ownLines margin atTheEnd c =
DComment
(OnItsOwnLines (commentGapAbove c))
(commentSpan c)
(commentText margin c)
<> includeWhen
(commentGapBelow c && not atTheEnd)
(declDelimiter DeclSeparate)
-- | A comment, and the spacing that goes with it, as one region.
commentDoc :: Comment -> Doc -> Doc
commentDoc = located . commentSpan
-- | The text of a comment, laid out as it was written, and the empty line
-- cpp joins to it.
commentText ::
-- | What goes at the margin.
Margin ->
-- | The comment.
Comment ->
Doc
commentText margin c = note . align $ case numbered c of
[] -> mempty
(_, l) : ls ->
txt l
<> foldMap (\(n, x) -> breakBefore n <> txt x) ls
<> joinedLine c
where
breakBefore n
| marginLine margin n = DVerbatimBreak AtMargin TrimWhitespace
| otherwise = DVerbatimBreak AtIndent TrimWhitespace
note
| marginComment margin c = DCppMarginNote
| otherwise = id
-- | The empty line cpp joins to a comment, if it joins one, reproduced
-- under it.
joinedLine :: Comment -> Doc
joinedLine c =
includeWhen (commentJoined c) (DVerbatimBreak AtMargin TrimWhitespace)
-- | The lines of a comment, each with the number of the line of the module
-- it was written on.
numbered :: Comment -> [(Int, Text)]
numbered c = zip [spanStartLine (commentSpan c) ..] (NE.toList (commentBody c))