tilia-0.2.0.0: src/Tilia/Render/Header.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | The module header, and the module as a whole.
module Tilia.Render.Header
( HeaderPragma (..),
takeHeaderPragmas,
takeStackHeader,
ModuleCtx (..),
hsModule,
)
where
import Control.Applicative ((<|>))
import Data.Choice (fromBool)
import Data.Function (on)
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IntMap
import Data.List (delete, insert, minimumBy, sortOn, tails)
import Data.List.NonEmpty (NonEmpty)
import Data.List.NonEmpty qualified as NE
import Data.Maybe (isJust, isNothing)
import Data.Ord (comparing)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Hs
import GHC.LanguageExtensions.Type (Extension (..))
import GHC.Types.PkgQual (RawPkgQual (..))
import GHC.Types.SrcLoc (GenLocated (..), unLoc)
import Prelude hiding (break)
import Tilia.Comments (Comment (..), commentPragma)
import Tilia.Doc.Combinators
import Tilia.Imports (normalizeImports)
import Tilia.Parser (writtenInHeader)
import Tilia.Pragma
( Pragma (..),
commute,
languageNames,
lookupEdition,
switchedBy,
)
import Tilia.Render.Block
import Tilia.Render.Context
import Tilia.Render.Declaration (topLevelDecls)
import Tilia.Render.Haddock
import Tilia.Render.Literal (writtenString)
import Tilia.Render.Name
import Tilia.Render.Pragma (warningSquares, warningTxt)
import Tilia.Source (Source, directivePresentOnLine, sourceLines)
import Tilia.Source qualified as Source
import Tilia.Span
import Tilia.Span.Ghc
-- | A pragma of the file header.
data HeaderPragma = HeaderPragma
{ -- | The region it was written in.
hpSpan :: Span,
-- | How many preprocessor directives the header has above it.
hpRun :: Int,
-- | @LANGUAGE@, @OPTIONS_GHC@, @OPTIONS@ or @OPTIONS_HADDOCK@.
hpName :: Text,
-- | One extension, or the whole of an options string.
hpBody :: Text,
-- | The lines it was written on, where it is a language pragma holding a
-- comment, which it keeps as written.
hpWritten :: Maybe (NonEmpty Text)
}
deriving (Eq, Show)
-- | Where a pragma sorts among the others.
--
-- The derived ordering is the policy wherever it leaves the same extensions
-- in force: the editions first, in the order they are written, then the
-- other language pragmas, by name, then @OPTIONS_GHC@ and @OPTIONS@, then
-- @OPTIONS_HADDOCK@.
data PragmaOrder
= EditionOrder
| LanguageOrder
| OptionsGhcOrder
| OptionsHaddockOrder
deriving (Eq, Ord, Show)
-- | Pick the header pragmas out of a comment stream.
takeHeaderPragmas ::
-- | The module as written.
Source ->
-- | Where the header ends.
Maybe Span ->
-- | The comment stream.
[Comment] ->
([HeaderPragma], [Comment])
takeHeaderPragmas src headerEnd comments = (pragmas, plain)
where
recognised = [(c, headerPragma c) | c <- comments]
pragmas = [entry c p | (c, Just p) <- recognised]
plain =
[ if rightAbovePragma c then airless c else c
| (c, Nothing) <- recognised
]
rightAbovePragma c =
Set.member (below (spanEndLine (commentSpan c) + 1)) pragmaStarts
below n =
if directivePresentOnLine n (sourceLines src) then below (n + 1) else n
pragmaStarts =
Set.fromList [spanStartLine (commentSpan c) | (c, Just _) <- recognised]
airless c = c{commentGapAbove = False, commentGapBelow = False}
directivesAbove n =
length [k | k <- [1 .. n - 1], directivePresentOnLine k (sourceLines src)]
entry c p =
HeaderPragma
{ hpSpan = commentSpan c,
hpRun = directivesAbove (spanStartLine (commentSpan c)),
hpName = pragmaName p,
hpBody = pragmaBody p,
hpWritten =
if pragmaCommented p then Just (commentBody c) else Nothing
}
headerPragma c = do
p <- commentPragma c
_ <- pragmaOrder (pragmaName p) (pragmaBody p)
if writtenInHeader headerEnd (commentSpan c) then Just p else Nothing
-- | Where a pragma sorts, given its name and its body, or 'Nothing' for one
-- the header does not hoist.
pragmaOrder :: Text -> Text -> Maybe PragmaOrder
pragmaOrder named body = case named of
"LANGUAGE"
| namesAnEdition body -> Just EditionOrder
| otherwise -> Just LanguageOrder
"OPTIONS_GHC" -> Just OptionsGhcOrder
"OPTIONS" -> Just OptionsGhcOrder
"OPTIONS_HADDOCK" -> Just OptionsHaddockOrder
_ -> Nothing
-- | Take the Stack script header off the front of a comment stream: the
-- comment whose first word is @stack@ at the margin of the first line, or
-- of the line under the @#!@ line, which Stack reads its options from.
takeStackHeader ::
-- | The lines above the module that the parser never sees.
[Text] ->
-- | The comment stream.
[Comment] ->
(Doc, [Comment])
takeStackHeader prologue = \case
(c : cs)
| isStackHeader c ->
(reproduce c <> newline <> declDelimiter DeclSeparate, cs)
cs -> (mempty, cs)
where
isStackHeader c =
startPoint (commentSpan c) == (if null prologue then 1 else 2, 1)
&& take 1 (T.words (T.drop 2 (NE.head (commentBody c)))) == ["stack"]
reproduce c =
verbatimLines AtMargin TrimWhitespace (NE.toList (commentBody c))
-- | The pragmas of a header, one per line, with the options in the order
-- they were written, which is the order GHC reads their flags in, and every
-- one of them kept, since a flag such as @-fplugin-opt@ counts each time it
-- is given.
--
-- The pragmas between two directives are sorted, but a pragma stays ahead of
-- a later one that sorts alike or that it does not commute with, so that the
-- same edition and extensions are left in force.
pragmaBlock :: [HeaderPragma] -> Doc
pragmaBlock =
foldMap render
. dedupe
. concatMap (sorted . NE.toList)
. NE.groupBy ((==) `on` hpRun)
. concatMap split
where
sorted run
| and [commute a b | a : later <- tails switches, b <- later] =
sortOn order run
| otherwise = arrange (zip run switches)
where
switches = fmap switched run
arrange = \case
[] -> []
ps ->
let free =
[ p
| (i, p) <- zip [0 ..] ps,
not (any (`ahead` p) (take i ps))
]
next = minimumBy (comparing (order . fst)) free
in fst next : arrange (delete next ps)
ahead (a, sa) (b, sb) = order a == order b || not (commute sa sb)
switched p = switchedBy (hpName p) (hpBody p)
order p = (orderOf p, extension p)
extension p
| orderOf p == Just LanguageOrder = hpBody p
| otherwise = ""
key p = (hpRun p, orderOf p, hpBody p)
orderOf p = pragmaOrder (hpName p) (hpBody p)
dedupe = fmap NE.head . NE.groupBy repeated
repeated a b =
hpName a == "LANGUAGE" && isNothing (hpWritten b) && key a == key b
split p
| hpName p == "LANGUAGE",
isNothing (hpWritten p) =
[ p{hpBody = body}
| body <- languageNames (hpBody p)
]
| otherwise = [p]
render p = located (hpSpan p) (written p) <> newline
written p = case hpWritten p of
Nothing ->
txt "{-# "
<> txt (hpName p)
<> includeUnless (T.null (hpBody p)) (space <> txt (hpBody p))
<> txt " #-}"
Just ls -> verbatim (T.intercalate "\n" (NE.toList ls))
-- | Does this name a whole edition of the language rather than one
-- extension of it?
namesAnEdition :: Text -> Bool
namesAnEdition = isJust . lookupEdition
-- | What printing the top level of a module takes beyond 'Ctx'.
data ModuleCtx = ModuleCtx
{ -- | The empty line that opens the imports, where the comments written
-- above it stay.
mcOpening :: Maybe Int,
-- | The empty lines under the comments that head stretches of the
-- imports, which they are not sorted across.
mcHeadings :: [Int],
-- | The empty line under the comments written right under an import but
-- the last, by the line the import begins on, so that they go wherever
-- it does.
mcUnderImports :: IntMap Int,
-- | The empty line under the comments written right under the last
-- import of any configuration, which stay at the end of the imports.
mcBelowImports :: Maybe Int,
-- | The first and last line of each stretch a @{- TILIA_OFF -}@ leaves
-- as written.
mcMagicCommentRanges :: [(Int, Int)]
}
-- | A whole module.
hsModule ::
-- | The context.
Ctx ->
-- | What printing its top level takes.
ModuleCtx ->
-- | The pragmas the header hoists.
[HeaderPragma] ->
-- | The module.
HsModule GhcPs ->
Doc
hsModule ctx ModuleCtx{..} pragmas HsModule{hsmodExt = XModulePs{..}, ..} =
pragmaBlock pragmas
<> newline
<> declDelimiter DeclSeparate
<> moduleLine
<> newline
<> declDelimiter DeclSeparate
<> foldMap anchor mcOpening
<> importLines mcHeadings False imports
<> includeUnless
(null hsmodDecls && null mcMagicCommentRanges)
( declDelimiter DeclSeparate
<> declarationsStart
<> declarationLayout
(topLevelDecls ctx mcMagicCommentRanges hsmodDecls)
)
where
imports =
normalizeImports
(fromBool (extensionOn ctx ImplicitPrelude))
(rcOwnModules (ctxRender ctx))
(foldr insert (rcImportBarriers (ctxRender ctx)) mcHeadings)
(rcDirectiveLines (ctxRender ctx))
(Source.comments (ctxSource ctx))
hsmodImports
importLines pending later = \case
[] -> mempty
[] : runs -> importLines pending True runs
((i, written) : is) : runs ->
foldMap anchor above
<> includeWhen later (declDelimiter DeclSeparate)
<> at ctx i ((<> endings) . importDecl ctx)
<> foldMap
(foldMap anchor . (`IntMap.lookup` mcUnderImports) . spanStartLine)
written
<> includeWhen (null is && null runs) (foldMap anchor mcBelowImports)
<> newline
<> importLines rest False (is : runs)
where
start = maybe 0 spanStartLine (spanOf i)
(above, rest) = span (< start) pending
endings = case written of
_ : _ : _ -> foldMap ending written
_ -> mempty
anchor l = located (mkSpan (l, 1) (l, 2)) mempty
ending s =
emptyAnchor (mkSpan (spanEndLine s, farRight) (spanEndLine s, farRight))
declarationLayout = case (hsmodDecls, spansOf hsmodDecls) of
(_ : _ : _, Just s) | isSingleLine s -> flat
_ -> id
exports = maybe [] unLoc hsmodExports
headerSpan =
foldMap (\w -> foldMap spanOf hsmodName <> spanOf w) hsmodDeprecMessage
<> foldMap spanOf hsmodExports
headerLayout
| any (isDocEntry . unLoc) exports = id
| maybe True isSingleLine headerSpan = frangible
| otherwise = id
moduleLine = case hsmodName of
Nothing -> mempty
Just modName ->
documentation
<> ref (headName modName)
<> headerLayout
( break
<> foldMap (warning modName) hsmodDeprecMessage
<> foldMap (exports' modName) hsmodExports
)
<> keywordAt (spanOf (am_where (anns hsmodAnn))) "where"
<> newline
documentation =
foldMap ((<> newline) . haddock ctx Pipe) hsmodHaddockModHeader
warning modName w =
at
ctx
w
(indent 1 (ptr (headName modName)) . warningTxt ctx (warningSquares w))
<> break
exports' modName l@(L ann _) =
at
ctx
l
( indent 1 (ptr (headName modName))
. exportList ctx (spanOf l) (bracketSpans (al_brackets (anns ann)))
)
<> break
headName =
moduleHeadName
ctx
(spanOf (am_mod moduleAnns) <> spanOf (am_sig moduleAnns))
moduleAnns = anns hsmodAnn
-- | The parenthesised list after a module name.
exportList ::
-- | The context.
Ctx ->
-- | Where the list was written.
Maybe Span ->
-- | Where its parentheses were written.
(Maybe Span, Maybe Span) ->
-- | The items.
[LIE GhcPs] ->
Doc
exportList ctx enclosing brackets xs =
layoutHere . parens brackets . insideBrackets enclosing $
importExportItems ctx xs
where
layoutHere
| any (isDocEntry . unLoc) xs = broken
| otherwise = layoutFrom ctx enclosing
-- | The items of an import or export list, with the documentation among
-- them lined up with the items rather than with leading commas.
importExportItems ::
-- | The context.
Ctx ->
-- | The items.
[LIE GhcPs] ->
Doc
importExportItems ctx xs = case ctxCommaStyle ctx of
TrailingCommas -> variant (laidOut False) (laidOut True)
LeadingCommas -> mconcat (zipWith3 commaLed previous afterItem xs)
where
previous = Nothing : fmap Just xs
afterItem = scanl (||) False (fmap (not . isDocEntry . unLoc) xs)
laidOut broken' =
sepBy break (zipWith (item broken') previous (ranked xs))
item broken' before (rank, x) =
gapAbove before x <> entry (comma' broken' rank) x
commaLed before afterAnItem x = case before of
Nothing -> entry False x
Just _
| afterAnItem,
not (isDocEntry (unLoc x)) ->
separatingComma LeadingCommas <> entry False x
_ -> break <> gapAbove before x <> entry False x
entry withComma x@(L _ ie) =
align . atSpan ctx (spanOf (widenToDoc x)) $
ieItem ctx (spanOf x) ie
<> includeWhen (withComma && not (isDocEntry ie)) comma
<> foldMap
(\d -> break <> haddock ctx Caret d)
(itemDoc ie)
gapAbove before x@(L _ here) = case before of
Nothing -> mempty
Just p
| isSection here ->
declDelimiter DeclSeparate
| isPipe here,
runsOn (unLoc p) || separatedByBlank ctx (spanOf p) (spanOf x) ->
declDelimiter DeclSeparate
| otherwise -> mempty
isSection = \case
IEGroup{} -> True
_ -> False
isPipe = \case
IEDoc{} -> True
_ -> False
runsOn = \case
IEDoc{} -> True
IEDocNamed{} -> True
_ -> False
comma' broken' rank
| broken' = True
| otherwise = rank == First || rank == Middle
-- | Widen an item's span to take in the documentation printed with it, so
-- that a documented item is laid out as one thing.
widenToDoc :: LIE GhcPs -> LIE GhcPs
widenToDoc l@(L ann ie) = case itemDoc ie of
Nothing -> l
Just (L docSpan _) -> L (ann <> noAnnSrcSpan docSpan) ie
-- | One item of an import or export list, without the comma after it and
-- the Haddock after that, in a region of its own unless it is a name
-- alone, which has the name's.
ieItem ::
-- | The context.
Ctx ->
-- | Where the item was written.
Maybe Span ->
-- | The item.
IE GhcPs ->
Doc
ieItem ctx here = \case
IEVar warning n _ -> plain warning n
IEThingAbs warning n _ -> plain warning n
IEThingAll (warning, (open, dots, close)) n _ ->
region $
exportWarning warning
<> at ctx n (wrappedName ctx)
<> space
<> openingAt (spanOf open) "("
<> keywordAt (spanOf dots) ".."
<> closingAt (spanOf close) ")"
IEThingWith (warning, (open, dots, _, close)) n wildcard members _ ->
region . align $
( exportWarning warning
<> ( at ctx n (wrappedName ctx)
>+> layoutFrom
ctx
(spanOf open <> spanOf close <|> here)
( break
<> parens
(spanOf open, spanOf close)
(insideBrackets here listed)
)
)
)
where
listed = commaSep (ctxCommaStyle ctx) (align <$> withWildcard)
rendered = fmap (at_ ctx (wrappedName ctx)) members
withWildcard = case wildcard of
NoIEWildcard -> rendered
IEWildcard n' ->
let (before, after) = splitAt n' rendered
in before <> [keywordAt (spanOf dots) ".."] <> after
IEModuleContents (warning, _) m ->
region $
exportWarning warning
<> at ctx m (\n -> txt "module" <> space <> outputable n)
IEGroup NoExtField n str -> haddock ctx (Section n) str
IEDoc NoExtField str -> haddock ctx Pipe str
IEDocNamed NoExtField n -> case writtenHaddock ctx here of
Just c -> verbatimLines AtIndent TrimWhitespace (NE.toList (commentBody c))
Nothing -> txt (docSectionName n)
where
plain warning n = case warning of
Nothing -> at ctx n (wrappedName ctx)
Just _ -> region (exportWarning warning <> at ctx n (wrappedName ctx))
region = maybe id located here
exportWarning =
foldMap
(\w -> at ctx w (warningTxt ctx (warningSquares w)) <> break)
-- | The documentation written with an export list item, if any.
itemDoc :: IE GhcPs -> Maybe (ExportDoc GhcPs)
itemDoc = \case
IEVar _ _ doc -> doc
IEThingAbs _ _ doc -> doc
IEThingAll _ _ doc -> doc
IEThingWith _ _ _ _ doc -> doc
_ -> Nothing
-- | Does this export list entry carry documentation?
isDocEntry :: IE GhcPs -> Bool
isDocEntry = \case
IEDoc{} -> True
IEGroup{} -> True
IEDocNamed{} -> True
_ -> False
-- | One import declaration: its keyword, then what it imports, its alias,
-- and its import list, each a node of its own past the keyword's column.
importDecl :: Ctx -> ImportDecl GhcPs -> Doc
importDecl ctx ImportDecl{..} =
ref keyword
<> indent
1
(ptr keyword)
( space
<> includeWhen (ideclSource == IsBoot) (txt "{-# SOURCE #-}")
<> space
<> includeWhen
ideclSafe
(keywordAt (spanOf =<< importDeclAnnSafe annotation) "safe")
<> space
<> levelBefore
<> space
<> includeWhen (isQualified && not qualifiedLast) qualified
<> space
<> packageQualifier
<> space
<> at ctx ideclName outputable
<> space
<> levelAfter
<> includeWhen (isQualified && qualifiedLast) (space <> qualified)
)
<> foldMap
( \a ->
indent
1
(ptr keyword)
( space
<> keywordAt (spanOf =<< importDeclAnnAs annotation) "as"
<> space
<> at ctx a outputable
)
)
ideclAs
<> foldMap (indent 1 (ptr keyword) . (space <>)) importList
where
keyword = keywordAt (spanOf (importDeclAnnImport annotation)) "import"
annotation = anns (ideclAnn ideclExt)
qualified =
keywordAt (spanOf =<< importDeclAnnQualified annotation) "qualified"
qualifiedLast = extensionOn ctx ImportQualifiedPost
isQualified = isImportDeclQualified ideclQualified
packageQualifier = case ideclPkgQual of
NoRawPkgQual -> mempty
RawPkgQual literal -> writtenString literal
levelBefore = case ideclLevelSpec of
LevelStylePre l -> declLevel l
_ -> mempty
levelAfter = case ideclLevelSpec of
LevelStylePost l -> declLevel l
_ -> mempty
importList = flip fmap ideclImportList $ \(interpretation, L listLoc xs) ->
let hidden = case interpretation of
Exactly -> mempty
EverythingBut ->
keywordAt (spanOf (fst (al_rest (anns listLoc)))) "hiding"
listSpan = spanOfSrcSpan (locA listLoc)
parensSpan = bracketsSpan (al_brackets (anns listLoc)) <|> listSpan
in layoutFrom ctx parensSpan $
hidden
<> break
<> fence
parensSpan
( parens
(bracketSpans (al_brackets (anns listLoc)))
(insideBrackets listSpan (importExportItems ctx xs))
)
-- | The keyword an import's level is written with.
declLevel :: ImportDeclLevel -> Doc
declLevel = \case
ImportDeclSplice -> txt "splice"
ImportDeclQuote -> txt "quote"