packages feed

tilia-0.2.0.0: src/Tilia/Render/Declaration.hs

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}

-- | Declarations: dispatching to the right printer, and grouping.
module Tilia.Render.Declaration
  ( decls,
    topLevelDecls,
  )
where

import Data.Choice (pattern Don't)
import Data.Foldable (toList)
import Data.List (sort)
import Data.List.NonEmpty (NonEmpty (..), (<|))
import Data.List.NonEmpty qualified as NE
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Text qualified as T
import GHC.Data.FastString (unpackFS)
import GHC.Hs
import GHC.Types.ForeignCall (CExportSpec (..))
import GHC.Types.Name.Occurrence (occNameFS)
import GHC.Types.Name.Reader (RdrName, rdrNameOcc)
import GHC.Types.SourceText
import GHC.Types.SrcLoc (GenLocated (..), isGoodSrcSpan, unLoc)
import Prelude hiding (break)

import Tilia.Doc (printsOnOneLine)
import Tilia.Doc.Combinators
import Tilia.Render.Block
import Tilia.Render.Class
import Tilia.Render.Context
import Tilia.Render.Data
import Tilia.Render.Expression
import Tilia.Render.Haddock
import Tilia.Render.Literal (stringLiteral)
import Tilia.Render.Name
import Tilia.Render.Pragma
import Tilia.Render.Signature
import Tilia.Render.Type
import Tilia.Source (SourceType (..), blankAt, lineAt, sourceLines)
import Tilia.Span
import Tilia.Span.Ghc

-- | The top-level declarations of a module, with the lines a
-- @{- TILIA_OFF -}@ leaves as written printed as written.
topLevelDecls ::
  -- | The context.
  Ctx ->
  -- | The first and last line of each stretch a @{- TILIA_OFF -}@ leaves as
  -- written.
  [(Int, Int)] ->
  -- | The declarations.
  [LHsDecl GhcPs] ->
  Doc
topLevelDecls ctx magicCommentRanges ds = case magicCommentRanges of
  [] -> decls ctx Free ds
  kept -> sepBy newline (zipWith joined (Nothing : fmap Just ps) ps)
    where
      ps = pieces kept ds
  where
    ls = sourceLines (ctxSource ctx)
    joined previous piece =
      includeWhen gap (declDelimiter DeclSeparate) <> printed piece
      where
        gap = any (`blankAt` ls) (gapAbove piece <> foldMap gapBelow previous)
    gapAbove = \case
      Preserved from _ -> [from - 1]
      Formatted _ -> []
    gapBelow = \case
      Preserved _ to -> [to + 1]
      Formatted _ -> []
    printed = \case
      Formatted run -> decls ctx Free (NE.toList run)
      Preserved from to ->
        located
          (mkSpan (from, 1) (to, maybe 1 ((+ 1) . T.length) (lineAt to ls)))
          ( verbatimLines AtMargin KeepWhitespace $
              mapMaybe (`lineAt` ls) [from .. to]
          )

-- | A part of the top-level declarations: those formatted together, or the
-- lines a @{- TILIA_OFF -}@ leaves as written.
data Piece
  = -- | Declarations formatted together.
    Formatted (NonEmpty (LHsDecl GhcPs))
  | -- | The first and last line of a stretch left as written.
    Preserved Int Int

-- | Cut the top-level declarations at the lines left as written.
pieces ::
  -- | The first and last line of each stretch left as written.
  [(Int, Int)] ->
  -- | The declarations.
  [LHsDecl GhcPs] ->
  [Piece]
pieces kept ds = case kept of
  [] -> run ds
  (from, to) : rest ->
    let (before, after) = span (startsBefore from) ds
     in run before
          <> [Preserved from to]
          <> pieces rest (dropWhile (startsBefore (to + 1)) after)
  where
    run = foldMap (pure . Formatted) . NE.nonEmpty
    startsBefore n d = maybe False ((< n) . spanStartLine) (spanOf d)

-- | A run of declarations, with an empty line wherever the author left one
-- and between groups kept apart.
--
-- Standing on their own, the one-line declarations of one kind the author
-- wrote together are kept together; in a class or an instance, the groups
-- the author made are.
decls ::
  -- | The context.
  Ctx ->
  -- | Whether they stand on their own or in a class or an instance.
  FamilyStyle ->
  -- | The declarations.
  [LHsDecl GhcPs] ->
  Doc
decls ctx style ds =
  items
    NoBrace
    [ gap <> printed
    | (current, above) <- zip groups (mempty : links),
      (gap, (_, printed)) <- zip (above : repeat mempty) (NE.toList current)
    ]
  where
    isSignatureFile = ctxSourceType ctx == SignatureSource
    declaration d = at ctx d (hsDecl ctx style)
    groups =
      fmap (\d -> (d, declaration d))
        <$> groupDecls ctx isSignatureFile ds

    -- The boundary between each two neighbouring groups: with the empty
    -- line between them where there is one, and holding them on their
    -- lines where they are written together and not kept apart.
    links = zipWith link groups (drop 1 groups)
    link previous current
      | separatedByBlank ctx ended began = declDelimiter DeclSeparate
      | isHeading (unLoc (fst (NE.last previous))) = together DeclAdjacent
      | apart previous current = declDelimiter DeclSeparate
      | otherwise = together DeclJoined
      where
        together = includeWhen (style == Free) . declDelimiter
        ended = spanOf (fst (NE.last previous))
        began = spanOf (fst (NE.head current))

    isHeading = \case
      DocD _ DocGroup{} -> True
      _ -> False

    apart previous current = case style of
      Free ->
        kindOf previous /= kindOf current
          || any standsApart (withoutDistantHaddock previous)
          || any standsApart current
      Associated -> any documented previous || any documented current
    standsApart (d, printed) =
      isDoc (unLoc d)
        || not (printsOnOneLine Broken printed)
    withoutDistantHaddock group = case NE.toList group of
      (doc, _) : rest@((d, _) : _)
        | DocD _ DocCommentNext{} <- unLoc doc,
          directiveBetween ctx (spanOf doc) (spanOf d) ->
            rest
      xs -> xs
    kindOf group =
      listToMaybe
        [ k
        | (d, _) <- reverse (NE.toList group),
          let k = fst (declKind (unLoc d)),
          k /= PragmaDeclaration
        ]
    documented (d, _) = case unLoc d of
      DocD _ (DocCommentNext _) -> True
      DocD _ (DocCommentPrev _) -> True
      _ -> False

-- | Gather declarations that belong together.
groupDecls ::
  -- | The context.
  Ctx ->
  -- | Are these the declarations of a signature file?
  Bool ->
  -- | The declarations.
  [LHsDecl GhcPs] ->
  [NonEmpty (LHsDecl GhcPs)]
groupDecls _ _ [] = []
groupDecls ctx isSignatureFile (d : ds)
  | isDocNext (unLoc d) = case groupDecls ctx isSignatureFile ds of
      [] -> [d :| []]
      (g : gs)
        | isDoc (unLoc (NE.head g)) -> (d :| []) : g : gs
        | otherwise -> (d <| g) : gs
  | otherwise =
      let (together, rest) = gather (d :| []) ds
       in (d :| together) : groupDecls ctx isSignatureFile rest
  where
    gather gathered = \case
      current : more
        | belongs gathered current ->
            let (together, rest) = gather (current <| gathered) more
             in (current : together, rest)
      doc : current : more
        | isDocNext (unLoc doc),
          isPragma (NE.head gathered),
          relatedDecls (NE.head gathered) current ->
            let (together, rest) = gather (current <| doc <| gathered) more
             in (doc : current : together, rest)
      remaining -> ([], remaining)
    isDocNext = \case
      DocD _ (DocCommentNext _) -> True
      _ -> False
    belongs gathered current =
      (not isSignatureFile && isSignatureSeries previous current)
        || isSeries ctx previous current
        || signsAcrossDirective ctx gathered current
        || ( any (`relatedDecls` current) gathered
               && not (separatedByBlank ctx (spanOf previous) (spanOf current))
           )
        || relatedDecls previous current
      where
        previous = NE.head gathered

-- | Type signatures one after another are a list, and a list reads better
-- without gaps in it.
isSignatureSeries ::
  -- | The first declaration.
  LHsDecl GhcPs ->
  -- | The one after it.
  LHsDecl GhcPs ->
  Bool
isSignatureSeries (L _ a) (L _ b) = case (a, b) of
  (SigD _ TypeSig{}, SigD _ TypeSig{}) -> True
  _ -> False

-- | Two standalone @deriving@ declarations, or two splices, the author ran
-- together.
isSeries :: Ctx -> LHsDecl GhcPs -> LHsDecl GhcPs -> Bool
isSeries ctx x@(L _ a) y@(L _ b) = case (a, b) of
  (DerivD{}, DerivD{}) -> ranTogether
  (SpliceD{}, SpliceD{}) -> ranTogether
  _ -> False
  where
    ranTogether = not (separatedByBlank ctx (spanOf x) (spanOf y))

-- | A type signature and the binding under it, past any pragmas, that a
-- directive separates with no empty line between, whatever each names.
signsAcrossDirective ::
  -- | The context.
  Ctx ->
  -- | The declarations gathered above the binding, the nearest first.
  NonEmpty (LHsDecl GhcPs) ->
  -- | The binding.
  LHsDecl GhcPs ->
  Bool
signsAcrossDirective ctx above y =
  case (unLoc y, NE.dropWhile isPragma above) of
    (ValD _ FunBind{}, x@(L _ (SigD _ TypeSig{})) : _) ->
      directiveBetween ctx (spanOf x) (spanOf y)
        && not (separatedByBlank ctx (spanOf x) (spanOf y))
    _ -> False

-- | Is this declaration a pragma?
isPragma :: LHsDecl GhcPs -> Bool
isPragma = (== PragmaDeclaration) . fst . declKind . unLoc

-- | The kinds of declaration that grouping distinguishes.
data Kind
  = TypeSignature
  | FunctionBody
  | PatternSignature
  | PatternDefinition
  | DataDeclaration
  | ClassDeclaration
  | KindSignature
  | FamilyDeclaration
  | TypeSynonym
  | PragmaDeclaration
  | FixityDeclaration
  | InstanceDeclaration
  | TypeInstance
  | DataInstance
  | DerivingDeclaration
  | SpliceDeclaration
  | ForeignDeclaration
  | RoleAnnotation
  | DefaultDeclaration
  | DocumentsPrevious
  | Unremarkable
  deriving (Eq, Show)

-- | What a declaration is, and what it names.
declKind :: HsDecl GhcPs -> (Kind, [RdrName])
declKind = \case
  SigD _ (TypeSig _ ns _) -> (TypeSignature, fmap unLoc ns)
  SigD _ (ClassOpSig _ _ ns _) -> (TypeSignature, fmap unLoc ns)
  SigD _ (PatSynSig _ ns _) -> (PatternSignature, fmap unLoc ns)
  SigD _ (InlineSig _ (L _ n) _) -> (PragmaDeclaration, [n])
  SigD _ (SCCFunSig _ (L _ n) _) -> (PragmaDeclaration, [n])
  SigD _ sig
    | Just n <- specialisedName sig -> (PragmaDeclaration, [n])
  SigD _ CompleteMatchSig{} -> (PragmaDeclaration, [])
  SigD _ (FixSig _ (FixitySig _ ns _)) -> (FixityDeclaration, fmap unLoc ns)
  ValD _ (FunBind _ (L _ n) _) -> (FunctionBody, [n])
  ValD _ (PatBind _ p _ _) ->
    (FunctionBody, collectPatBinders CollNoDictBinders p)
  ValD _ (PatSynBind _ (PSB _ (L _ n) _ _ _)) -> (PatternDefinition, [n])
  AnnD _ (HsAnnotation _ (ValueAnnProvenance (L _ n)) _) ->
    (PragmaDeclaration, [n])
  AnnD _ (HsAnnotation _ (TypeAnnProvenance (L _ n)) _) ->
    (PragmaDeclaration, [n])
  AnnD _ (HsAnnotation _ ModuleAnnProvenance _) -> (PragmaDeclaration, [])
  RuleD{} -> (PragmaDeclaration, [])
  WarningD _ (Warnings _ ws) ->
    (PragmaDeclaration, [unLoc n | L _ (Warning _ ns _) <- ws, n <- ns])
  TyClD _ d@(DataDecl _ (L _ n) _ _ _) -> (DataDeclaration, n : memberNames d)
  TyClD _ d@ClassDecl{tcdLName = L _ n} -> (ClassDeclaration, n : memberNames d)
  TyClD _ (SynDecl _ (L _ n) _ _ _) -> (TypeSynonym, [n])
  TyClD _ (FamDecl _ (FamilyDecl _ _ _ (L _ n) _ _ _ _)) ->
    (FamilyDeclaration, [n])
  KindSigD _ (StandaloneKindSig _ (L _ n) _) -> (KindSignature, [n])
  InstD _ (ClsInstD _ d) ->
    ( InstanceDeclaration,
      foldMap
        (constructorNames . hsDataFamInstBinders . unLoc)
        (cid_datafam_insts d)
    )
  InstD _ TyFamInstD{} -> (TypeInstance, [])
  InstD _ (DataFamInstD _ d) ->
    (DataInstance, constructorNames (hsDataFamInstBinders d))
  DerivD{} -> (DerivingDeclaration, [])
  SpliceD{} -> (SpliceDeclaration, [])
  ForD _ d -> (ForeignDeclaration, unLoc <$> hsForeignDeclsBinders [noLocA d])
  RoleAnnotD{} -> (RoleAnnotation, [])
  DefD{} -> (DefaultDeclaration, [])
  DocD _ (DocCommentPrev _) -> (DocumentsPrevious, [])
  _ -> (Unremarkable, [])

-- | Is this a Haddock?
isDoc :: HsDecl GhcPs -> Bool
isDoc = \case
  DocD{} -> True
  _ -> False

-- | Should these two declarations be printed with no blank line between
-- them?
relatedDecls ::
  -- | The declaration above.
  LHsDecl GhcPs ->
  -- | The declaration under it.
  LHsDecl GhcPs ->
  Bool
relatedDecls a b = case (kindA, kindB) of
  (_, DocumentsPrevious) -> not (isDoc (unLoc a))
  pair
    | pair `elem` relatedKinds
        || PragmaDeclaration `elem` [kindA, kindB]
          && FixityDeclaration `notElem` [kindA, kindB] ->
        shareAName namesA namesB
  _ -> False
  where
    (kindA, namesA) = declKind (unLoc a)
    (kindB, namesB) = declKind (unLoc b)

-- | The pairs of declaration kinds that group when they name something in
-- common, besides a pragma, which groups with whatever it names but a fixity
-- declaration.
relatedKinds :: [(Kind, Kind)]
relatedKinds =
  [ (TypeSignature, FunctionBody),
    (TypeSignature, TypeSignature),
    (PatternSignature, PatternDefinition),
    (KindSignature, DataDeclaration),
    (KindSignature, ClassDeclaration),
    (KindSignature, FamilyDeclaration),
    (KindSignature, TypeSynonym)
  ]

-- | The names a type declaration gives its constructors, fields, methods and
-- associated types.
memberNames :: TyClDecl GhcPs -> [RdrName]
memberNames d =
  fmap (unLoc . fst) tyDeclATs
    <> fmap unLoc tyDeclOpSigs
    <> constructorNames tyDeclConsWithFields
  where
    TyDeclBinders{..} = hsLTyClDeclBinders (noLocA d)

-- | The names of constructors and their fields.
constructorNames :: LConsWithFields 'Parsed -> [RdrName]
constructorNames LConsWithFields{..} =
  fmap (unLoc . fst) consWithFieldIndices
    <> fmap (unLoc . foLabel . unLoc) (toList consFields)

-- | Do the two declarations name anything in common?
shareAName :: [RdrName] -> [RdrName] -> Bool
shareAName xs ys = overlaps (sort (fmap spelling xs)) (sort (fmap spelling ys))
  where
    spelling :: RdrName -> String
    spelling = unpackFS . occNameFS . rdrNameOcc
    overlaps (a : as) (b : bs)
      | a < b = overlaps as (b : bs)
      | a > b = overlaps (a : as) bs
      | otherwise = True
    overlaps _ _ = False

-- | Print one declaration.
hsDecl :: Ctx -> FamilyStyle -> HsDecl GhcPs -> Doc
hsDecl ctx style = \case
  TyClD _ x -> tyClDecl ctx style x
  ValD _ x -> valDecl ctx NoBrace x
  SigD _ x -> sigDecl ctx x
  InstD _ x -> instDecl ctx style x
  DerivD _ x -> standaloneDerivDecl ctx x
  DefD _ x -> defaultDecl ctx x
  ForD _ x -> foreignDecl ctx x
  WarningD _ x -> warnDecls ctx x
  AnnD _ x -> annDecl ctx x
  RuleD _ x -> ruleDecls ctx x
  SpliceD _ (SpliceDecl NoExtField splice deco) ->
    at ctx splice (untypedSplice ctx deco)
  RoleAnnotD _ x -> roleAnnot ctx x
  KindSigD _ x -> standaloneKindSig ctx x
  DocD _ x -> case x of
    DocCommentNext str -> haddock ctx Pipe str
    DocCommentPrev str -> haddock ctx Caret str
    DocCommentNamed n str -> haddock ctx (Chunk n) str
    DocGroup n str -> haddock ctx (Section n) str

-- | A type, class or family declaration.
tyClDecl :: Ctx -> FamilyStyle -> TyClDecl GhcPs -> Doc
tyClDecl ctx style = \case
  FamDecl _ x -> famDecl ctx style x
  SynDecl{..} ->
    synDecl ctx tcdSExt tcdLName tcdFixity tcdTyVars tcdRhs
  DataDecl{..} ->
    dataDecl
      ctx
      (Don't #instanceWord)
      tcdLName
      (hsq_explicit tcdTyVars)
      spanOf
      (at_ ctx (tyVarBndr ctx))
      tcdFixity
      ( outerBracketSpans
          (andd_openp (dd_ext tcdDataDefn))
          (andd_closep (dd_ext tcdDataDefn))
      )
      mempty
      tcdDataDefn
  ClassDecl{tcdCExt = (anns, _, _), ..} ->
    classDecl
      ctx
      anns
      tcdCtxt
      tcdLName
      tcdTyVars
      tcdFixity
      tcdFDs
      tcdSigs
      tcdMeths
      tcdATs
      tcdATDefs
      tcdDocs

-- | An instance of a class, or of a type or data family.
instDecl :: Ctx -> FamilyStyle -> InstDecl GhcPs -> Doc
instDecl ctx style = \case
  ClsInstD _ x -> clsInstDecl ctx x
  TyFamInstD _ x -> tyFamInstDecl ctx style x
  DataFamInstD _ x -> dataFamInstDecl ctx style x

-- | A @default@ declaration.
defaultDecl ::
  -- | The context.
  Ctx ->
  -- | The declaration.
  DefaultDecl GhcPs ->
  Doc
defaultDecl ctx (DefaultDecl (keyword, open, close) className types) =
  keywordAt (spanOf keyword) "default"
    >+> foldMap (\c -> space <> name ctx c) className
      <> break
      <> parens
        (spanOf open, spanOf close)
        (commaSep (ctxCommaStyle ctx) (fmap (align . hsType ctx) types))

-- | An @ANN@ pragma.
annDecl :: Ctx -> AnnDecl GhcPs -> Doc
annDecl ctx (HsAnnotation _ provenance e) =
  pragma "ANN" $
    subject <> break <> hsExpr ctx e
  where
    subject = case provenance of
      ValueAnnProvenance n -> name ctx n
      TypeAnnProvenance n -> txt "type" <> space <> name ctx n
      ModuleAnnProvenance -> txt "module"

-- | A foreign import or export.
foreignDecl ::
  -- | The context.
  Ctx ->
  -- | The declaration.
  ForeignDecl GhcPs ->
  Doc
foreignDecl ctx = \case
  fd@ForeignImport{fd_i_ext = (f, i, _), fd_fi} ->
    keywords f "import" i (foreignImport ctx fd_fi) >+> foreignSig ctx fd
  fd@ForeignExport{fd_e_ext = (f, e, _), fd_fe} ->
    keywords f "export" e (foreignExport ctx fd_fe) >+> foreignSig ctx fd
  where
    keywords f word t rest =
      keywordAt (spanOf f) "foreign"
        >+> space
          <> keywordAt (spanOf t) word
          <> space
          <> rest

-- | The name and type that end a foreign declaration.
foreignSig :: Ctx -> ForeignDecl GhcPs -> Doc
foreignSig ctx fd =
  break
    <> layoutFrom
      ctx
      (spanOf (fd_name fd) <> spanOf (fd_sig_ty fd))
      ( name ctx (fd_name fd)
          >+> typeAscription ctx (spanOf (fd_name fd)) (fd_sig_ty fd)
      )

-- | The head of a foreign import after its keywords.
foreignImport ::
  -- | The context.
  Ctx ->
  -- | The import.
  ForeignImport GhcPs ->
  Doc
foreignImport ctx (CImport src callConv safety _ _) =
  ( at ctx callConv outputable
      <> includeWhen
        (isGoodSrcSpan (getLocA safety))
        (space <> outputable safety)
  )
    >+> at
      ctx
      src
      ( \case
          NoSourceText -> mempty
          SourceText lit -> break <> stringLiteral lit
      )

-- | The head of a foreign export after its keywords.
foreignExport ::
  -- | The context.
  Ctx ->
  -- | The export.
  ForeignExport GhcPs ->
  Doc
foreignExport ctx (CExport src (L loc (CExportStatic _ _ callConv))) =
  at ctx (L loc callConv) outputable
    <> space
    <> at ctx src sourceText