tilia-0.2.0.0: src/Tilia/Cpp/Place.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
-- | Placing elements that the configurations of a module do not print (CPP
-- conditionals, directives, and comments).
module Tilia.Cpp.Place
( CommentSummary,
summarizeComments,
carriedBetween,
readDifferently,
restoreUnprinted,
)
where
import Control.Applicative ((<|>))
import Control.Monad (foldM)
import Data.Char (isSpace)
import Data.Foldable (traverse_)
import Data.List (find, sortOn, unsnoc)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, isJust, isNothing, listToMaybe, mapMaybe)
import Data.Monoid (Any (..))
import Data.Ord (Down (..))
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import Tilia.Comments
( Comment (..),
commentPragma,
transcendentComment,
)
import Tilia.Comments.Attach (Margin (..), attachScopedComments)
import Tilia.Cpp.Directives
( CppError (..),
Directive (..),
GroupSpec (..),
Guard (..),
allGroups,
dSpan,
directives,
opaqueDirectives,
readConditionals,
)
import Tilia.Doc
( Conditional (..),
Doc (..),
SeparatorSide (..),
conditionalRange,
foldChildren,
foldRegions,
mapChildren,
onlySpacing,
referentIn,
regionOf,
separatorSide,
spine,
unwrap,
wrap,
pattern Cat,
)
import Tilia.Doc.Combinators
( DeclDelimiterStyle (..),
declDelimiter,
includeWhen,
newline,
)
import Tilia.Source
( Lines,
Written (..),
blankAt,
directiveWrittenOnLine,
isDirective,
lineAt,
lineTextsFrom,
linesOf,
)
import Tilia.Span (Span (..), farRight, mkSpan, startPoint)
-- | What the configurations of a module had besides their code.
data CommentSummary = CommentSummary
{ -- | The comments no syntax tree carries, by where they were written.
summaryLoose :: Map Span Comment,
-- | Where every comment was written, whether a tree carries it or not.
summaryComments :: Set Span,
-- | Where every Haddock a tree carries begins.
summaryCarried :: Set (Int, Int)
}
-- | What two sets of configurations found between them.
--
-- A comment is the same comment in every configuration it is in, except
-- for whether it wants an empty line either side of it, which is asked of
-- what it is written next to and so can come out differently. It gets one
-- wherever any configuration wanted one.
instance Semigroup CommentSummary where
a <> b =
CommentSummary
{ summaryLoose = Map.unionWith either' (summaryLoose a) (summaryLoose b),
summaryComments = Set.union (summaryComments a) (summaryComments b),
summaryCarried = Set.union (summaryCarried a) (summaryCarried b)
}
where
either' x y =
x
{ commentGapAbove = commentGapAbove x || commentGapAbove y,
commentGapBelow = commentGapBelow x || commentGapBelow y
}
instance Monoid CommentSummary where
mempty = CommentSummary Map.empty Set.empty Set.empty
-- | What one configuration found.
summarizeComments ::
-- | Where the Haddocks its syntax tree carries begin.
[(Int, Int)] ->
-- | The comments its syntax tree does not carry.
[Comment] ->
-- | Every comment in it.
[Comment] ->
CommentSummary
summarizeComments carried loose every =
CommentSummary
{ summaryLoose = Map.fromList [(commentSpan c, c) | c <- loose],
summaryComments = Set.fromList (fmap commentSpan every),
summaryCarried = Set.fromList carried
}
-- | What was found, with the Haddocks a tree carries kept only between the
-- lines given.
carriedBetween ::
-- | The last line before them and the first line after them.
(Int, Int) ->
-- | What was found.
CommentSummary ->
CommentSummary
carriedBetween (low, high) found =
found
{ summaryCarried =
Set.filter (\(l, _) -> low < l && l < high) (summaryCarried found)
}
-- | The line of the first Haddock that some configurations read and others
-- ignore.
readDifferently :: CommentSummary -> Maybe Int
readDifferently found =
fst
<$> Set.lookupMin
( Set.intersection
(summaryCarried found)
(Set.map startPoint (Map.keysSet (summaryLoose found)))
)
-- | Put the conditionals, comments, opaque directives and macro lines back
-- into the document the configurations were merged into.
restoreUnprinted ::
-- | The module as written.
Text ->
-- | Its macro lines, which its configurations left out.
[(Int, Text)] ->
-- | What its configurations found.
CommentSummary ->
-- | The document its configurations were merged into.
Doc ->
Either CppError Doc
restoreUnprinted source macros found doc = do
forest <- readConditionals source
traverse_ (Left . quotedDirective) . find (quoted . dLine) $
filter (not . inComment . dLine) (directives source)
let groups = [gs | gs <- allGroups forest, not (inComment (fst (gsWhole gs)))]
notes =
[ if any directiveAt [spanStartLine s + 1 .. spanEndLine s - 1]
then transcendentComment written c
else c
| c <- Map.elems (summaryLoose found),
let s = commentSpan c
]
let shelled = foldl (restoreConditional written) (widened doc) groups
marked = spacedApart written (realized (widened shelled))
partial = partiallyPrinted writtenIn marked
writtenIn = scopeIn (fmap gsConditional groups)
scope s
| Set.member s partial = Nothing
| otherwise = Just (writtenIn s)
noted = attachScopedComments margin scope notes marked
margin =
Margin
{ marginLine = (`directiveWrittenOnLine` written),
marginComment = isNothing . commentPragma
}
directed <-
foldM
(putDirective written)
noted
(filter (not . inComment . dLine) (opaqueDirectives source))
placed <-
foldM
(putMacroLine written quoted)
directed
(filter (not . inComment . fst) macros)
pure placed
where
written = linesOf (Written source)
directiveAt n =
maybe False isDirective (lineAt n written) || any ((== n) . fst) macros
inComment n =
any
(\s -> spanStartLine s < n && n < spanEndLine s)
(summaryComments found)
quoted = quotedIn doc
quotedDirective d = DirectiveInQuotedText (dLine d) (dKeyword d)
-- | Widen every region to take in the choices printed inside it, each past
-- the end of the last line it prints, after which comes its @#endif@.
widened :: Doc -> Doc
widened = fst . go
where
go = \case
DLocated s x -> let (x', c) = go x in (DLocated (maybe s (s <>) c) x', c)
DFence s x -> let (x', c) = go x in (DFence (maybe s (s <>) c) x', c)
DCppChoice cs bs e ->
let bs' = [(g, go d) | (g, d) <- bs]
(e', c) = go e
choice = DCppChoice cs [(g, x) | (g, (x, _)) <- bs'] e'
in ( choice,
pastTheEnd
<$> foldMap conditionalSpan cs
<> foldMap (snd . snd) bs'
<> c
<> regionOf choice
)
Cat a b ->
let (a', ca) = go a
(b', cb) = go b
in (DCat a' b', ca <> cb)
d@DVariant{} -> (d, Nothing)
d
| Just (w, x) <- unwrap d -> let (x', c) = go x in (wrap w x', c)
| otherwise -> (d, Nothing)
-- | The regions a choice prints in some of its alternatives but not in
-- all, written in a part of the module that holds one of its conditionals.
--
-- Such a region is printed in fewer configurations than the part of the
-- module it was written in holds, so no comment goes next to it: whichever
-- alternatives it is missing from would lose the comment.
partiallyPrinted ::
-- | The part of the module a region was written in.
(Span -> Maybe (Int, Int)) ->
-- | The document.
Doc ->
Set Span
partiallyPrinted writtenIn = go
where
go = \case
DCppChoice cs bs e ->
let alternatives = fmap snd bs <> [e]
held = fmap (foldRegions outside) alternatives
outside s _ inside
| holdsOne (writtenIn s) = Set.insert s inside
| otherwise = Set.empty
holdsOne = \case
Nothing -> True
Just (from, to) ->
any
(\(a, b) -> from < a && b < to)
(mapMaybe conditionalRange cs)
in Set.unions held
`Set.difference` foldl' Set.intersection (Set.unions held) held
<> foldMap go alternatives
d -> foldChildren go d
-- | The lines a conditional was written on, from its @#if@ to its @#endif@,
-- beginning left of the first column: a directive stays at the margin
-- whatever the code's indentation, so nothing lines up with it.
conditionalSpan :: Conditional -> Maybe Span
conditionalSpan c =
(\(from, to) -> mkSpan (from, 0) (to, 1)) <$> conditionalRange c
-- | The part of the module a region was written in: the innermost branch of
-- a conditional holding all of it, or 'Nothing' for the module itself.
--
-- A region is printed in exactly the configurations that take its branch,
-- so this is also which configurations it is in, and a comment written in
-- one branch goes only next to what that branch holds.
scopeIn ::
-- | The conditionals.
[Conditional] ->
-- | Where the region was written.
Span ->
Maybe (Int, Int)
scopeIn conditionals = \s ->
listToMaybe
[ b
| b@(from, to) <- branches,
from < spanStartLine s,
spanEndLine s < to
]
where
branches =
sortOn
(Down . fst)
[ (from, to)
| ls <- fmap conditionalLines conditionals,
(from, to) <- zip ls (drop 1 ls)
]
-- | Mark out every choice the merge made as the region of the input it was
-- printed from, and give every branch of it something to hold on to.
--
-- A choice's region is its conditionals, from the first @#if@ to the last
-- @#endif@, and anything else its alternatives print: a comment written
-- above the @#if@ goes before the whole choice, not into one alternative of
-- it. Every alternative also gets an anchor where its conditional opens, for
-- a comment written above the @#if@ when the alternatives print code from
-- above it too, and one where each branch closes, for a comment written in a
-- branch with nothing after it in that branch.
realized :: Doc -> Doc
realized = \case
DCppChoice cs bs e ->
let alternatives = fmap realized (fmap snd bs <> [e])
bs' =
[ (g, anchoredIn cs k d)
| (k, (g, d)) <- zip [0 ..] (zip (fmap fst bs) alternatives)
]
e' = anchoredIn cs (length bs) (maybe mempty snd (unsnoc alternatives))
inner = DCppChoice cs bs' e'
in maybe
inner
((`DLocated` inner) . pastTheEnd)
(foldMap conditionalSpan cs <> regionOf inner)
d -> mapChildren realized d
-- | A span taken past the end of its last line.
pastTheEnd :: Span -> Span
pastTheEnd s = s{spanEndColumn = farRight}
-- | Space two conditionals that come one right after the other as the
-- author spaced them, where a newline rather than a group's break keeps
-- them apart.
spacedApart ::
-- | The module as written.
Lines ->
-- | The document.
Doc ->
Doc
spacedApart written = go
where
go = \case
d@(Cat _ _) -> mconcat (apart (fmap go (spine d)))
d -> mapChildren go d
apart = \case
x : rest
| Just (_, to) <- ownLines x,
(spacing@(_ : _), y : rest') <- span onlySpacing rest,
Just _ <- ownLines y ->
x
: ( if blankAt (to + 1) written
&& any
(`elem` [DNewline, DDeclDelimiter DeclSeparate])
spacing
then newline <> declDelimiter DeclSeparate
else newline
)
: apart (y : rest')
x : rest -> x : apart rest
[] -> []
ownLines = \case
DLocated s (DCppChoice cs _ _)
| Just c <- foldMap conditionalSpan cs,
spanStartLine c == spanStartLine s,
spanEndLine c == spanEndLine s ->
Just (spanStartLine s, spanEndLine s)
_ -> Nothing
-- | Give one alternative of a choice its anchors.
anchoredIn ::
-- | The conditionals the choice was printed from.
[Conditional] ->
-- | Which alternative this is.
Int ->
-- | The alternative.
Doc ->
Doc
anchoredIn cs k d = foldl' anchor d (filter (here . fst) (concatMap anchors cs))
where
anchor x (n, s) =
fromMaybe
(placeAt (const False) Nothing n (DLocated s mempty) (const id) x)
(beforeWrittenAfter (startPoint s) (DLocated s mempty) x)
here n = case alternativeAt n cs of
Everywhere -> True
Only i -> i == k
Nowhere -> False
anchors c = case conditionalLines c of
ls@(opening : _) ->
(opening, mkSpan (opening, 1) (opening, 2))
: [ (closing, mkSpan (closing - 1, farRight) (closing - 1, farRight))
| (from, closing) <- take 1 (drop k (zip ls (drop 1 ls))),
closing - 1 > from
]
[] -> []
-- | Put a document right before the first region another prints that was
-- written after a point, inside whatever holds that region, if it prints
-- one, as a comment above that region would be.
beforeWrittenAfter ::
-- | The point.
(Int, Int) ->
-- | What to put there.
Doc ->
-- | The document to put it in.
Doc ->
Maybe Doc
beforeWrittenAfter point body = go
where
go = \case
d@(DLocated s x)
| startPoint s > point -> Just (body <> d)
| otherwise -> DLocated s <$> go x
Cat a b -> (`DCat` b) <$> go a <|> DCat a <$> go b
DVariant a b -> DVariant (fromMaybe (a <> body) (go a)) <$> go b
d -> unwrap d >>= \(w, x) -> wrap w <$> go x
-- | Make sure a conditional is in the document, putting it where it was
-- written if the merge left it out.
restoreConditional :: Lines -> Doc -> GroupSpec -> Doc
restoreConditional written doc gs =
placeAt realized' (Just written) opening shell (const id) doc
where
realized' ctx = any (all (`elem` ctx)) (realizations c doc)
c = gsConditional gs
(opening, closing) = gsWhole gs
guards = fmap guardText (gsGuards gs)
shell =
DCppChoice [c] [(g, mempty) | g <- guards] mempty
<> includeWhen
(blankAt (closing + 1) written)
(newline <> declDelimiter DeclSeparate)
-- | Put a directive back where it was written.
putDirective :: Lines -> Doc -> Directive -> Either CppError Doc
putDirective written doc d
| dKeyword d == "include",
commaUnder written (dLastLine d) =
Left (BeforeLeadingComma (dLine d) ("#" <> dText d))
| otherwise =
Right (placeAt (const False) (Just written) (dLine d) body (const id) doc)
where
body =
DCppDirective (dSpan d) (dText d)
<> includeWhen
(any (`blankAt` written) [dLastLine d, dLastLine d + 1])
(newline <> declDelimiter DeclSeparate)
-- | Put a line using a macro back where it was written, at the indentation
-- of the code around it, since what it stands for is code.
putMacroLine ::
-- | The module as written.
Lines ->
-- | Is a line inside something the document reproduces verbatim?
(Int -> Bool) ->
-- | The document.
Doc ->
-- | The line, and what is written on it.
(Int, Text) ->
Either CppError Doc
putMacroLine written quoted doc (n, t)
| quoted n = Left (MacroInQuotedText n t)
| commaUnder written n = Left (BeforeLeadingComma n t)
| otherwise =
Right (placeAt (const False) (Just written) n (line id) nested doc)
where
nested following _ = line (nestedLike following)
line relations =
DLocated
(mkSpan (n, 1) (n, 1))
(DNewline <> relations (DText t) <> DNewline)
<> includeWhen
(blankAt (n + 1) written)
(newline <> declDelimiter DeclSeparate)
-- | Does the code under a line open with a comma, before which the line
-- cannot be put back?
commaUnder ::
-- | The module as written.
Lines ->
-- | The line.
Int ->
Bool
commaUnder written n = case dropWhile passed (lineTextsFrom (n + 1) written) of
l : _ -> T.isPrefixOf "," (T.stripStart l)
[] -> False
where
passed l =
T.all isSpace l || isDirective l || T.isPrefixOf "--" (T.stripStart l)
-- | Is a line inside something the document reproduces verbatim, such as
-- a quasi-quotation, where a line cannot be put back?
quotedIn ::
-- | The document.
Doc ->
-- | The line.
Int ->
Bool
quotedIn doc = \n -> any (\(from, to) -> from < n && n <= to) ranges
where
ranges =
foldRegions
( \s x inner ->
[(spanStartLine s, spanEndLine s) | reproduced x] <> inner
)
doc
reproduced = \case
DVerbatimBreak _ _ -> True
DLocated{} -> False
DFence{} -> False
d -> getAny (foldChildren (Any . reproduced) d)
-- | Put a document at a line of the input, in every alternative that line
-- is printed in.
placeAt ::
-- | Whether what is being put there is there already, for the
-- configurations that take these alternatives.
(Context -> Bool) ->
-- | The module as written, to ask whether the author left an empty line
-- above the line; without it the document goes after whatever space is
-- there.
Maybe Lines ->
-- | The line.
Int ->
-- | What to put there.
Doc ->
-- | How to put it before the given code printed further in, which
-- carries on a line above.
(Doc -> Doc -> Doc) ->
-- | The document to put it in.
Doc ->
Doc
placeAt present written n body continuing = among []
where
within ctx d = case d of
DVariant x y -> DVariant (within ctx x) (within ctx y)
DLocated s x
| spanStartLine s > n -> among ctx d
| otherwise -> DLocated s (within ctx x)
DCppChoice cs bs e
| present ctx -> d
| otherwise -> case alternativeAt n cs of
Everywhere ->
DCppChoice
cs
[(g, among (ctx <> [(cs, k)]) x) | (k, (g, x)) <- zip [0 ..] bs]
(among (ctx <> [(cs, length bs)]) e)
Only k
| k < length bs ->
DCppChoice
cs
( replaced
k
( among
(ctx <> [(cs, k)])
(maybe mempty snd (listToMaybe (drop k bs)))
)
bs
)
e
| otherwise -> DCppChoice cs bs (among (ctx <> [(cs, k)]) e)
Nowhere -> d
_
| Just (w, x) <- unwrap d -> wrap w (within ctx x)
| otherwise -> among ctx d
among ctx d
| present ctx = d
| otherwise = case break startsAfter (spine d) of
(before, after)
| (front, holder : back) <- splitAt (writtenLast before) before,
maybe False (>= n) (endOf holder) ->
mconcat (front <> [within ctx holder] <> back <> after)
| (later, holder : rest) <- break holds after ->
mconcat (before <> later <> [within ctx holder] <> rest)
| Just (printed, anchor, spacing) <- lastBounded before,
Just from <- endOf anchor,
Just ls <- written ->
if any (`blankAt` ls) [from .. n - 1]
|| not (all onlySpacing spacing)
then
let (ahead, led) = break leads spacing
in mconcat
( printed
<> [anchor]
<> ahead
<> [ includeWhen
(blankAt (n - 1) ls)
(newline <> declDelimiter DeclSeparate),
putBefore (led <> after)
]
<> led
<> after
)
else
mconcat
( printed
<> [anchor, putBefore (spacing <> after)]
<> spacing
<> after
)
| next : rest <- after,
any (not . onlySpacing) (takeWhile unbounded (reverse before)) ->
mconcat (before <> [within ctx next] <> rest)
| otherwise -> mconcat (before <> [putBefore after] <> after)
putBefore following =
if maybe False (> 0) (firstNesting (mconcat following))
then continuing (mconcat following) body
else body
writtenLast ds =
case [(from, i) | (i, Just from) <- zip [0 ..] (fmap startOf ds)] of
[] -> length ds
starts -> snd (maximum starts)
holds = \case
DLocated s _ -> spanStartLine s < n && n <= spanEndLine s
_ -> False
startsAfter = \case
DLocated s _ | spanStartColumn s == farRight -> spanStartLine s >= n
x -> maybe False (> n) (startOf x)
lastBounded ds = case break
(maybe False (const True) . boundsOf)
(reverse ds) of
(spacing, x : earlier) -> Just (reverse earlier, x, reverse spacing)
_ -> Nothing
replaced k x bs =
[if i == k then (g, x) else (g, y) | (i, (g, y)) <- zip [0 :: Int ..] bs]
leads = (== Just LeadingSeparator) . separatorSide
unbounded = isNothing . boundsOf
startOf = fmap fst . boundsOf
endOf = fmap snd . boundsOf
-- | Which alternative of which choice, from the outside in: the
-- configurations a place in a document is printed in.
type Context = [([Conditional], Int)]
-- | Every place a choice printed from a conditional is, as the alternatives
-- leading to it.
realizations :: Conditional -> Doc -> [Context]
realizations c = go []
where
go ctx = \case
DCppChoice cs bs e ->
[ctx | c `elem` cs]
<> concat
[ go (ctx <> [(cs, k)]) d
| (k, d) <- zip [0 ..] (fmap snd bs <> [e])
]
d -> foldChildren (go ctx) d
-- | Which alternatives of a choice a line of the input is printed in.
data Alternatives
= -- | Every one: the line is outside the conditionals.
Everywhere
| -- | The one its branch became.
Only Int
| -- | None: its branch is never taken.
Nowhere
-- | Which alternatives of a choice printed from these conditionals a line
-- is printed in.
alternativeAt :: Int -> [Conditional] -> Alternatives
alternativeAt n cs = case branches of
[] -> Everywhere
k : ks
| all (== k) ks -> Only k
| otherwise -> Nowhere
where
branches =
[ k
| ls <- fmap conditionalLines cs,
(k, (from, to)) <- zip [0 ..] (zip ls (drop 1 ls)),
from < n,
n < to
]
-- | How many columns further in than itself a document prints its first
-- text, if it prints any, counting a step as two.
firstNesting :: Doc -> Maybe Int
firstNesting = \case
DText _ -> Just 0
Cat a b -> firstNesting a <|> firstNesting b
DIndented n a x | isJust (referentIn a) -> (+ 2 * n) <$> firstNesting x
DAligned n x -> (+ n) <$> firstNesting x
DVariant _ x -> firstNesting x
DCppChoice _ bs e -> foldr ((<|>) . firstNesting . snd) (firstNesting e) bs
d -> firstNesting . snd =<< unwrap d
-- | A document in the relations the first text of another is printed in.
nestedLike ::
-- | The other document.
Doc ->
-- | The document.
Doc ->
Doc
nestedLike = \case
Cat a b
| isJust (firstNesting a) -> nestedLike a
| otherwise -> nestedLike b
DIndented n a x | isJust (referentIn a) -> DIndented n a . nestedLike x
DAligned n x -> DAligned n . nestedLike x
DVariant _ x -> nestedLike x
DCppChoice _ bs e ->
nestedLike (fromMaybe e (find (isJust . firstNesting) (fmap snd bs)))
d -> maybe id (nestedLike . snd) (unwrap d)
-- | The lines a document was printed from, first and last.
boundsOf :: Doc -> Maybe (Int, Int)
boundsOf = \case
DLocated s _ -> Just (spanStartLine s, spanEndLine s)
DFence s _ -> Just (spanStartLine s, spanEndLine s)
DCppDirective s _ -> Just (spanStartLine s, spanEndLine s)
DCppChoice cs bs e ->
hull
( mapMaybe conditionalRange cs
<> [b | Just b <- boundsOf e : fmap (boundsOf . snd) bs]
)
Cat a b -> case (boundsOf a, boundsOf b) of
(Just (from, _), Just (_, to)) -> Just (from, to)
(found, Nothing) -> found
(Nothing, found) -> found
DVariant _ b -> boundsOf b
d -> boundsOf . snd =<< unwrap d
where
hull = \case
[] -> Nothing
bs -> Just (minimum (fmap fst bs), maximum (fmap snd bs))