packages feed

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

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}

-- | Names, the decorations the author put around them, the heads of
-- definitions, and function arrows.
module Tilia.Render.Name
  ( outputable,
    showGhc,
    sourceText,
    name,
    nameClosing,
    hashesApart,
    moduleHeadName,
    wrappedName,
    namespaceSpec,
    joinedByFunctionArrow,
    multiplicity,
    defHead,
    headArguments,
    typeHead,
  )
where

import Data.Choice (Choice, fromBool, isTrue)
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Hs hiding (UnicodeSyntax)
import GHC.LanguageExtensions.Type (Extension (..))
import GHC.Types.Fixity (LexicalFixity (..))
import GHC.Types.Name.Occurrence (OccName, occNameString)
import GHC.Types.Name.Reader
import GHC.Types.SourceText
import GHC.Types.SrcLoc (getLoc)
import GHC.Utils.Outputable (Outputable, ppr, showSDocUnsafe)
import Prelude hiding (break)

import Tilia.Doc (BracketSide (..), edgeTexts)
import Tilia.Doc.Combinators
import Tilia.Render.Context
import Tilia.Source (SourceType (..))
import Tilia.Span
import Tilia.Span.Ghc

-- | Anything GHC knows how to show.
--
-- For the leaves that have no structure worth walking—numeric literals,
-- occurrence names, calling conventions. Never for anything that might need
-- a line break inside it, since the result is emitted as one fragment.
outputable :: Outputable a => a -> Doc
outputable = txt . showGhc

-- | The text GHC would show for something.
showGhc :: Outputable a => a -> Text
showGhc = T.pack . showSDocUnsafe . ppr

-- | The text the author wrote, when GHC kept it.
sourceText :: SourceText -> Doc
sourceText = \case
  NoSourceText -> mempty
  SourceText s -> outputable s

-- | A name, with whatever the author wrapped it in.
name ::
  -- | The context.
  Ctx ->
  -- | The name.
  LocatedN RdrName ->
  Doc
name ctx = nameClosing ctx 0

-- | 'name', with the closing bracket of a @()@, a @(# #)@ or a @[]@ that a
-- comment breaks this many steps in from its opening one.
nameClosing ::
  -- | The context.
  Ctx ->
  -- | The steps.
  Int ->
  -- | The name.
  LocatedN RdrName ->
  Doc
nameClosing ctx closing l =
  at ctx l $ \x -> adorn ctx closing (spanOf l) x (getLoc l) (bareName x)

-- | The name itself, with nothing around it.
bareName :: RdrName -> Doc
bareName = \case
  Unqual occName -> occurrence occName
  Qual mname occName -> qualifiedName mname occName
  Orig _ occName -> occurrence occName
  Exact n -> outputable n

-- | Put back whatever brackets, backticks or ticks the author used.
adorn ::
  -- | The context.
  Ctx ->
  -- | How many steps in from the opening bracket of a @()@, a @(# #)@ or a
  -- @[]@ its closing one goes where a comment breaks it.
  Int ->
  -- | Where the name was written.
  Maybe Span ->
  -- | The name.
  RdrName ->
  -- | What was written around it.
  EpAnn NameAnn ->
  -- | The name, printed.
  Doc ->
  Doc
adorn ctx closing here x = go
  where
    go EpAnn{anns} = case anns of
      NameAnnQuote{nann_quote, nann_quoted} ->
        (keywordAt (spanOf nann_quote) "'" <>) . go nann_quoted
      NameAnnOnly{nann_adornment = NameParensHash o c} ->
        const (hollow o "(#" c "#)" (\d -> space <> d <> space))
      NameAnnOnly{nann_adornment = NameParens o c} ->
        const (hollow o "(" c ")" id)
      NameAnnOnly{nann_adornment = NameSquare o c} ->
        const (hollow o "[" c "]" id)
      NameAnnCommas{nann_adornment = NameParens o c, nann_commas} ->
        const (inParens (spanOf o) (spanOf c) (tokens "," nann_commas))
      NameAnnCommas{nann_adornment = NameParensHash o c, nann_commas} ->
        const (inBrackets o "(#" c "#)" (tokens "," nann_commas))
      NameAnnBars{nann_parensh = (o, c), nann_bars} ->
        const
          ( inBrackets o "(#" c "#)" $
              space
                <> sepBy space [keywordAt (spanOf t) "|" | t <- nann_bars]
                <> space
          )
      NameAnnRArrow{nann_mopen = Just o, nann_arrow, nann_mclose} ->
        inParens (spanOf o) (spanOf nann_mclose)
          . atSpan ctx (spanOf nann_arrow)
      NameAnn{nann_adornment, nann_name} -> case nann_adornment of
        NameParens o c ->
          inParens (spanOf o) (spanOf c) . spaceOutHash . itsOwn nann_name
        NameBackquotes{} -> backticks . itsOwn nann_name
        _ -> itsOwn nann_name
      _ -> id
    itsOwn = atSpan ctx . spanOf
    hollow o open c close spaced
      | fmap endPoint (spanOf o) == fmap startPoint (spanOf c) =
          opening <> spaced mempty <> closing'
      | otherwise =
          align . indent closing opening $
            spaced (insideBrackets here mempty) <> closing'
      where
        opening = openingAt (spanOf o) open
        closing' = closingAt (spanOf c) close
    inParens o c d = openingAt o "(" >+> d <> closingAt c ")"
    inBrackets o open c close d =
      openingAt (spanOf o) open >+> d <> closingAt (spanOf c) close
    tokens t = foldMap (\tok -> keywordAt (spanOf tok) t)
    spaceOutHash d
      | unboxedParens ctx,
        Unqual (occNameString -> '#' : _) <- x =
          space <> d <> space
      | otherwise = d

-- | What a pair of parentheses holds, held off them where it begins with a
-- @#@ or ends with the operator @#@ and 'unboxedParens' holds.
hashesApart ::
  -- | The context.
  Ctx ->
  -- | What the parentheses hold.
  Doc ->
  Doc
hashesApart ctx d
  | unboxedParens ctx =
      gap OpeningBracket (T.isPrefixOf "#") <> d <> gap ClosingBracket (== "#")
  | otherwise = d
  where
    gap side hashed = includeWhen (any hashed (edgeTexts side d)) space

-- | Do @(#@ and @#)@ lex as brackets, so that a @#@ next to a parenthesis
-- has to keep its distance, as with @UnboxedTuples@ or @UnboxedSums@ on?
unboxedParens :: Ctx -> Bool
unboxedParens ctx =
  extensionOn ctx UnboxedTuples || extensionOn ctx UnboxedSums

-- | A name written with its module.
qualifiedName :: ModuleName -> OccName -> Doc
qualifiedName mname occName =
  txt (T.pack (moduleNameString mname)) <> txt "." <> occurrence occName

-- | A name as it is spelled, without a module.
occurrence :: OccName -> Doc
occurrence = txt . T.pack . occNameString

-- | The name in a module header, with the keyword that introduces it.
moduleHeadName ::
  -- | The context.
  Ctx ->
  -- | Where the keyword was written.
  Maybe Span ->
  -- | The name.
  LocatedA ModuleName ->
  Doc
moduleHeadName ctx keywordSpan mname =
  keywordAt keywordSpan keyword <> space <> at ctx mname outputable
  where
    keyword = case ctxSourceType ctx of
      ModuleSource -> "module"
      SignatureSource -> "signature"

-- | A name as it appears in an import or export list.
wrappedName :: Ctx -> IEWrappedName GhcPs -> Doc
wrappedName ctx = \case
  IEName _ x -> name ctx x
  IEDefault _ x -> keyed "default" x
  IEPattern _ x -> keyed "pattern" x
  IEType _ x -> keyed "type" x
  IEData _ x -> keyed "data" x
  where
    keyed kw x = txt kw <> space <> name ctx x

-- | The @type@ or @data@ that disambiguates which namespace is meant.
namespaceSpec :: NamespaceSpecifier -> Doc
namespaceSpec = \case
  NoNamespaceSpecifier -> mempty
  TypeNamespaceSpecifier _ -> txt "type" <> space
  DataNamespaceSpecifier _ -> txt "data" <> space

-- | 'joinedByArrow' with the arrow of a function type and the multiplicity
-- written on it, which @UnicodeSyntax@ lets a linear arrow spell as one
-- symbol.
joinedByFunctionArrow ::
  -- | The context.
  Ctx ->
  -- | How to print a multiplicity.
  (mult -> Doc) ->
  -- | Where the line may break.
  Doc ->
  -- | The argument.
  Maybe Span ->
  -- | What the arrow leads to.
  Maybe Span ->
  -- | The multiplicity.
  HsMultAnnOf mult GhcPs ->
  Doc
joinedByFunctionArrow ctx render separator before after = \case
  HsLinearAnn _ | extensionOn ctx UnicodeSyntax -> joined "⊸"
  HsUnannotated _ -> joined arrow
  multAnn -> case ctxArrowStyle ctx of
    TrailingArrows ->
      space <> multiplicity render multAnn <> joined arrow
    LeadingArrows ->
      separator
        <> lineLed before after
        <> multiplicity render multAnn
        <> space
        <> leading (txt arrow)
  where
    joined = joinedByArrow ctx separator before after
    arrow = reserved ctx "->"

-- | A multiplicity annotation on an arrow or a field.
multiplicity ::
  -- | How to print the multiplicity written after a @%@.
  (mult -> Doc) ->
  -- | The annotation.
  HsMultAnnOf mult GhcPs ->
  Doc
multiplicity render = \case
  HsUnannotated _ -> mempty
  HsLinearAnn (EpPct1 tok _) -> keywordAt (spanOf tok) "%1"
  HsLinearAnn EpLolly{} -> txt "%1"
  HsExplicitMult (tok, _) mult -> keywordAt (spanOf tok) "%" <> render mult

-- | The left-hand side of a definition: a name and the things it is applied
-- to.
--
-- Written infix, the first two arguments straddle the name and any further
-- ones force the whole of that into parentheses, which is the only way the
-- source could have been written. Written prefix, the arguments simply
-- follow. The 'headArguments' are a 'ref' for what follows the head.
defHead ::
  -- | How many steps in from the opening parenthesis the closing one goes,
  -- where there is one.
  Int ->
  -- | Where the parentheses were written, where there are any.
  (Maybe Span, Maybe Span) ->
  -- | Written infix?
  Choice "writtenInfix" ->
  -- | The name.
  Doc ->
  -- | The arguments.
  [Doc] ->
  Doc
defHead closing parensAt writtenInfix nameDoc args = case args of
  a0 : a1 : rest
    | isTrue writtenInfix ->
        let infixHead =
              a0
                >+> break
                  <> align (leadingOperator nameDoc <> space <> a1)
         in if
              | null rest -> a0 >+> break <> arguments
              | otherwise ->
                  bracketWith closing parensAt "(" ")" infixHead
                    >+> break
                      <> arguments
  [] -> nameDoc
  _ -> nameDoc >+> break <> arguments
  where
    arguments = ref (headArguments writtenInfix nameDoc args)

-- | The part of a definition's head that what follows the head is placed
-- relative to, before it is lined up: the arguments, or, written infix,
-- the name and the argument after it, where no more follow.
headArguments ::
  -- | Written infix?
  Choice "writtenInfix" ->
  -- | The name.
  Doc ->
  -- | The arguments.
  [Doc] ->
  Doc
headArguments writtenInfix nameDoc = \case
  [_, a1]
    | isTrue writtenInfix -> align (leadingOperator nameDoc <> space <> a1)
  _ : _ : rest | isTrue writtenInfix -> spread rest
  args -> spread args

-- | Arguments, each aligned under itself, one per line when broken.
spread :: [Doc] -> Doc
spread = align . sepBy break . fmap align

-- | The head of a type-level declaration: a type constructor and what it is
-- applied to, laid out from where they were written.
typeHead ::
  -- | The context.
  Ctx ->
  -- | How many steps in from the opening parenthesis the closing one goes,
  -- where there is one.
  Int ->
  -- | Where the parentheses were written, where there are any.
  (Maybe Span, Maybe Span) ->
  -- | Was it written infix?
  LexicalFixity ->
  -- | The type constructor.
  LocatedN RdrName ->
  -- | Where each argument was.
  (arg -> Maybe Span) ->
  -- | How to print one.
  (arg -> Doc) ->
  -- | The arguments.
  [arg] ->
  Doc
typeHead ctx closing parensAt fixity tyCon argSpan arg args =
  layoutFrom ctx (spanOf tyCon <> foldMap argSpan args) $
    defHead
      closing
      parensAt
      (fromBool (fixity == Infix))
      (name ctx tyCon)
      (fmap arg args)