packages feed

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

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

-- | Signatures, and the pragmas that are written like them.
module Tilia.Render.Signature
  ( sigDecl,
    standaloneKindSig,
    ruleDecls,
    specialisedName,
  )
where

import Data.Choice (Choice, pattern Do, pattern Don't)
import Data.List.NonEmpty (NonEmpty (..))
import Data.List.NonEmpty qualified as NE
import Data.Maybe (maybeToList)
import GHC.Data.BooleanFormula hiding (isTrue)
import GHC.Hs
import GHC.Types.Basic
  ( Activation (..),
    InlinePragma (..),
    InlineSpec (..),
    RuleMatchInfo (..),
  )
import GHC.Types.Fixity (Fixity (..), FixityDirection (..))
import GHC.Types.Name.Reader (RdrName)
import GHC.Types.SourceText
import GHC.Types.SrcLoc (GenLocated (..), unLoc)
import Prelude hiding (break)

import Tilia.Doc.Combinators
import Tilia.Render.Context
import Tilia.Render.Expression (hsExpr)
import Tilia.Render.Literal (writtenString)
import Tilia.Render.Name
import Tilia.Render.Pragma
import Tilia.Render.Type
import Tilia.Span (endOf, startOf)
import Tilia.Span.Ghc (outerBracketSpans, spanOf, spansOf)

-- | A signature declaration.
sigDecl ::
  -- | The context.
  Ctx ->
  -- | The signature.
  Sig GhcPs ->
  Doc
sigDecl ctx = \case
  TypeSig _ names hswc -> typeSig ctx (Do #indentTail) names (hswc_body hswc)
  PatSynSig ann names sigType -> patSynSig ctx ann names sigType
  ClassOpSig ann isDefault names sigType
    | isDefault ->
        keywordAt (spanOf =<< asDefault ann) "default"
          >+> space
            <> typeSig ctx (Do #indentTail) names sigType
    | otherwise -> typeSig ctx (Do #indentTail) names sigType
  FixSig ((_, written), _) sig -> fixitySig ctx written sig
  InlineSig _ n prag -> inlineSig ctx n prag
  SpecSig _ n types prag ->
    specialiseSig ctx Nothing (noLocA (HsVar NoExtField n)) types prag
  SpecSigE _ binders e prag -> specialiseSigE ctx binders e prag
  SpecInstSig (_, src) sigType ->
    pragma
      (spelledAsWritten "SPECIALIZE" "SPECIALISE" src <> " instance")
      (hsSigType ctx sigType)
  MinimalSig _ formula ->
    layoutFrom ctx (spanOf formula) . pragma "MINIMAL" $
      at ctx formula (booleanFormula ctx)
  CompleteMatchSig _ names ty -> completeSig ctx names ty
  SCCFunSig _ n literal -> sccSig ctx n literal

-- | @f, g :: t@.
typeSig ::
  -- | The context.
  Ctx ->
  -- | Indent the names after the first?
  Choice "indentTail" ->
  -- | The names the signature is about.
  [LocatedN RdrName] ->
  -- | The type they are given.
  LHsSigType GhcPs ->
  Doc
typeSig _ _ [] _ = error "Tilia: a signature names something"
typeSig ctx indentTail (n : ns) sigType =
  ascribedNames ctx indentTail names (spanOf sigType) $
    typeAscription ctx (spanOf (NE.last names)) sigType
  where
    names = n :| ns

-- | @pattern P :: t@.
patSynSig ::
  -- | The context.
  Ctx ->
  -- | Where its keywords were written.
  AnnSig ->
  -- | The pattern synonyms it is about.
  [LocatedN RdrName] ->
  -- | The type they are given.
  LHsSigType GhcPs ->
  Doc
patSynSig ctx ann names sigType
  | length names > 1 =
      keyword
        >+> layoutAcross
          ctx
          names
          (variant (space <> body) (break <> body))
  | otherwise = keyword >+> space <> body
  where
    keyword = keywordAt (spanOf =<< asPattern ann) "pattern"
    body = typeSig ctx (Don't #indentTail) names sigType

-- | @infixl 5 <+>@, with the precedence only where one is written.
fixitySig :: Ctx -> Maybe EpaLocation -> FixitySig GhcPs -> Doc
fixitySig ctx written (FixitySig namespace names (Fixity prec direction)) =
  txt keyword
    <> space
    <> foldMap (const (outputable prec <> space)) written
    <> namespaceSpec namespace
    <> align (commaSepUnderFirst (ctxCommaStyle ctx) 0 (fmap (name ctx) names))
  where
    keyword = case direction of
      InfixL -> "infixl"
      InfixR -> "infixr"
      InfixN -> "infix"

-- | An @INLINE@ or @NOINLINE@ pragma.
inlineSig ::
  -- | The context.
  Ctx ->
  -- | The name it is about.
  LocatedN RdrName ->
  -- | The pragma.
  InlinePragma ->
  Doc
inlineSig ctx n InlinePragma{..} =
  pragmaBrackets $
    ( inlineSpec inl_inline
        <> space
        <> conLike
        <> space
        <> includeUnless (inl_act == NeverActive) (activation inl_act)
    )
      >+> space
        <> name ctx n
  where
    conLike = case inl_rule of
      ConLike -> txt "CONLIKE"
      FunLike -> mempty

-- | A @SPECIALIZE@ pragma, spelled as written.
specialiseSig ::
  Ctx ->
  Maybe (RuleBndrs GhcPs) ->
  LHsExpr GhcPs ->
  [LHsSigType GhcPs] ->
  InlinePragma ->
  Doc
specialiseSig ctx binders target types InlinePragma{..} =
  pragmaBrackets $
    ( txt (spelledAsWritten "SPECIALIZE" "SPECIALISE" inl_src)
        <> space
        <> inlineSpec inl_inline
        <> space
        <> phase
    )
      >+> space
        <> foldMap (\bs -> ruleBinders ctx bs <> space) binders
        <> hsExpr ctx target
        <> includeUnless
          (null types)
          ( joinedByArrow
              ctx
              break
              (spanOf target)
              (spansOf types)
              (reserved ctx "::")
              <> commaSepUnderFirst
                (ctxCommaStyle ctx)
                0
                (fmap (hsSigType ctx) types)
          )
  where
    -- A @NOINLINE@ written without a phase reads as never active, so that
    -- phase is left off rather than printed as @[~]@.
    phase = case (inl_inline, inl_act) of
      (NoInline _, NeverActive) -> mempty
      _ -> activation inl_act

-- | A @SPECIALIZE@ pragma written as an expression.
specialiseSigE ::
  Ctx ->
  RuleBndrs GhcPs ->
  LHsExpr GhcPs ->
  InlinePragma ->
  Doc
specialiseSigE ctx binders e =
  specialiseSig ctx (Just binders) target (maybeToList sigTy)
  where
    (target, sigTy) = specBody e

-- | A @SPECIALIZE@ expression without the type ascription it may carry.
specBody :: LHsExpr GhcPs -> (LHsExpr GhcPs, Maybe (LHsSigType GhcPs))
specBody = \case
  L _ (ExprWithTySig _ e HsWC{hswc_body}) -> (e, Just hswc_body)
  e -> (e, Nothing)

-- | The function a @SPECIALIZE@ expression applies, if it applies one.
--
-- The parser takes any expression at all here and leaves it to the renamer
-- to insist on a head variable, so a module on its way to being rejected
-- reaches us with expressions like @let x = 2 in f x@ in this position.
specHead :: LHsExpr GhcPs -> Maybe (LocatedN RdrName)
specHead (L _ e) = case e of
  HsVar _ n -> Just n
  HsApp _ f _ -> specHead f
  HsAppType _ f _ -> specHead f
  _ -> Nothing

-- | The name a @SPECIALIZE@ pragma is about, for grouping declarations.
specialisedName :: Sig GhcPs -> Maybe RdrName
specialisedName = \case
  SpecSig _ (L _ n) _ _ -> Just n
  SpecSigE _ _ e _ -> unLoc <$> specHead (fst (specBody e))
  _ -> Nothing

-- | The formula a @MINIMAL@ pragma is written with.
booleanFormula :: Ctx -> BooleanFormula GhcPs -> Doc
booleanFormula ctx = \case
  Var n -> name ctx n
  And xs ->
    align
      ( commaSepUnderFirst
          (ctxCommaStyle ctx)
          0
          (fmap (at_ ctx (booleanFormula ctx)) xs)
      )
  Or xs ->
    align
      ( sepBy
          (break <> leadingBar)
          (fmap (at_ ctx (booleanFormula ctx)) (concatMap alternatives xs))
      )
  Parens l -> at ctx l (parens (Nothing, Nothing) . booleanFormula ctx)
  where
    alternatives = \case
      L _ (Or ys) -> concatMap alternatives ys
      x -> [x]

-- | A @COMPLETE@ pragma.
completeSig ::
  -- | The context.
  Ctx ->
  -- | The constructors and pattern synonyms it lists.
  [LIdP GhcPs] ->
  -- | The type constructor after its @::@, if written.
  Maybe (LocatedN RdrName) ->
  Doc
completeSig ctx names ty =
  layoutAcross ctx names . pragma "COMPLETE" $ case ty of
    Nothing -> listed
    Just t ->
      listed
        >+> variant
          (ascription t)
          (layoutFrom ctx (spanOf (last names) <> spanOf t) (ascription t))
  where
    listed = commaSepUnderFirst (ctxCommaStyle ctx) 0 (fmap (name ctx) names)
    ascription t =
      joinedByArrow
        ctx
        break
        (spansOf names)
        (spanOf t)
        (reserved ctx "::")
        <> name ctx t

-- | An @SCC@ pragma.
sccSig :: Ctx -> LocatedN RdrName -> Maybe (XRec GhcPs StringLiteral) -> Doc
sccSig ctx n literal =
  pragma "SCC" $
    name ctx n
      <> foldMap (\l -> break <> writtenString (unLoc l)) literal

-- | @type T :: k@.
standaloneKindSig :: Ctx -> StandaloneKindSig GhcPs -> Doc
standaloneKindSig ctx (StandaloneKindSig (typeToken, _) n sigTy) =
  keyword
    <> indent 1 (ptr keyword) (space <> name ctx n)
    <> indent 1 (ptr keyword) (typeAscription ctx (spanOf n) sigTy)
  where
    keyword = refAt (spanOf typeToken) (txt "type")

-- | A @RULES@ block.
--
-- The closing @#-\}@ is given an anchor of its own, so that a comment
-- written after the last rule and before it stays inside the pragma. There
-- is nothing else down there for such a comment to attach to, and outside
-- the braces it would read as a remark on whatever follows the block.
ruleDecls :: Ctx -> RuleDecls GhcPs -> Doc
ruleDecls ctx (HsRules ((_, close), _) rules) =
  pragmaBrackets $
    txt "RULES"
      <> break
      <> sepBy
        break
        (fmap (align . at_ ctx (ruleDecl ctx)) rules)
      <> foldMap (emptyAnchor . startOf) (spanOf close)

-- | One rule of a @RULES@ block.
ruleDecl ::
  -- | The context.
  Ctx ->
  -- | The rule.
  RuleDecl GhcPs ->
  Doc
ruleDecl ctx (HsRule (_, written) ruleName phase binders lhs rhs) =
  at ctx ruleName (\n -> writtenString (StringLiteral written n Nothing))
    >+> space
      <> activation phase
      <> space
      <> ruleBinders ctx binders
      <> break
      <> ( hsExpr ctx lhs
             >+> trailing (txt "=")
               <> layoutFrom
                 ctx
                 (fmap endOf (spanOf lhs) <> spanOf rhs)
                 (break <> hsExpr ctx rhs)
         )

-- | The @forall@s a rule or a @SPECIALIZE@ pragma binds.
ruleBinders :: Ctx -> RuleBndrs GhcPs -> Doc
ruleBinders ctx (RuleBndrs HsRuleBndrsAnn{..} tyvars binders) =
  foldMap
    (\xs -> forallBndrs ctx Invisible (tyVarBndr ctx) xs <> space)
    tyvars
    <> case rb_tmanns of
      Nothing -> mempty
      Just _ -> forallBndrs ctx Invisible (ruleBinder ctx) binders

-- | One variable a rule's @forall@ binds.
ruleBinder :: Ctx -> RuleBndr GhcPs -> Doc
ruleBinder ctx = \case
  RuleBndr _ n -> name ctx n
  RuleBndrSig ann n HsPS{..} ->
    parens
      (outerBracketSpans (atv_opens ann) (atv_closes ann))
      (name ctx n >+> typeAscription ctx (spanOf n) (asSigType hsps_body))