packages feed

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

{-# LANGUAGE OverloadedStrings #-}

-- | What the syntax walk needs to know that the syntax tree does not say.
module Tilia.Render.Context
  ( -- * The context
    RenderConfig (..),
    defaultRenderConfig,
    Ctx (..),
    Knot (..),
    FamilyStyle (..),
    ArrowStyle (..),

    -- * Extensions
    extensionOn,
    negativeLiteralGap,
    reserved,

    -- * Fixities
    operatorFixity,

    -- * What lies between two spans
    separatedByBlank,
    directiveBetween,

    -- * Entering the tree
    at,
    at_,
    atSpan,
    keywordAt,
    layoutFrom,
    layoutAcross,
    writtenOnOneLine,
    attachOperator,
    joinedByArrow,
    lineLed,

    -- * Haddocks
    writtenHaddock,
  )
where

import Data.Char (isSpace)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Hs hiding (Fixity, UnicodeSyntax)
import GHC.LanguageExtensions.Type (Extension (NegativeLiterals, UnicodeSyntax))
import GHC.Types.Name.Reader (RdrName (..))
import GHC.Types.SrcLoc (GenLocated (..))
import GHC.Types.SrcLoc qualified as GHC

import Tilia.Comments
  ( Comment (..),
    CommentStyle (..),
  )
import Tilia.Doc.Combinators
import Tilia.Fixity
  ( Fixity,
    Namespace (..),
    Resolution (..),
    Scope,
    lookupFixity,
    opName,
    qualifierOf,
  )
import Tilia.Settings (ArrowStyle (..), Indentation, Settings, defaultSettings)
import Tilia.Source
  ( Source,
    SourceType,
    blankAt,
    directivePresentOnLine,
    lineAt,
    offsetOf,
    quoteEndingFrom,
    sourceLines,
  )
import Tilia.Span
import Tilia.Span.Ghc

----------------------------------------------------------------------------
-- The context

-- | What the printer needs to know about the module beyond its text.
data RenderConfig = RenderConfig
  { -- | Extensions in force, from the module's own pragmas and from the
    -- package it belongs to.
    rcExtensions :: Set Extension,
    -- | What the module can see, if it could be worked out.
    rcScope :: Maybe Scope,
    -- | The lines of every conditional's directives, which the names of an
    -- import list are not sorted across.
    rcDirectiveLines :: [Int],
    -- | The lines of the directives that imports are not sorted across:
    -- those of every conditional but one that only continues the import
    -- above it, such as a @hiding@ clause written behind a condition.
    rcImportBarriers :: [Int],
    -- | The lines the first and the last import begin on in every
    -- configuration that has the given line, or in every configuration at
    -- all, where the module has conditionals, so that the configurations
    -- that print a comment agree on where the imports open and on whether
    -- it is among them.
    rcImportBounds :: Maybe Int -> Maybe (Int, Int),
    -- | The modules the project's own packages declare, each with the names
    -- of those that declare it.
    rcOwnModules :: Map Text (Set Text),
    -- | The names the module defines macros by, in whichever configuration.
    rcMacros :: Set Text,
    -- | Where the argument lists of the module's uses of its function-like
    -- macros were written, which cpp pastes into the macros as they are.
    rcMacroArguments :: Set Span,
    -- | What the project sets.
    rcSettings :: Settings
  }

-- | A configuration that asserts nothing.
defaultRenderConfig :: RenderConfig
defaultRenderConfig =
  RenderConfig
    { rcExtensions = Set.empty,
      rcScope = Nothing,
      rcDirectiveLines = [],
      rcImportBarriers = [],
      rcImportBounds = const Nothing,
      rcOwnModules = Map.empty,
      rcMacros = Set.empty,
      rcMacroArguments = Set.empty,
      rcSettings = defaultSettings
    }

-- | Everything a printer may need beyond the node it is given.
data Ctx = Ctx
  { -- | How the module is rendered.
    ctxRender :: RenderConfig,
    -- | The type of the source file.
    ctxSourceType :: SourceType,
    -- | The uses of an operator a local binding captures, by where the
    -- operator is written, with their fixities.
    ctxCaptured :: Map Span Fixity,
    -- | The module as its author wrote it.
    ctxSource :: Source,
    -- | The author's own text for each Haddock, by starting position.
    ctxHaddocks :: Map (Int, Int) Comment,
    -- | The knot.
    ctxKnot :: Knot,
    -- | How far each level of nesting is indented.
    ctxIndentation :: Indentation,
    -- | Where a list laid out on several lines puts its commas.
    ctxCommaStyle :: CommaStyle,
    -- | Where a type laid out on several lines puts its arrows.
    ctxArrowStyle :: ArrowStyle
  }

-- | The backward edges of the rendering knot.
data Knot = Knot
  { -- | Expressions, needed by patterns.
    knotExpr :: Ctx -> LHsExpr GhcPs -> Doc,
    -- | Splices, needed by types and patterns, defined with expressions.
    knotSplice :: Ctx -> SpliceDecoration -> HsUntypedSplice GhcPs -> Doc,
    -- | Signature declarations, needed by @let@ and @where@ bodies.
    knotSig :: Ctx -> Sig GhcPs -> Doc,
    -- | A run of declarations, needed by Template Haskell brackets and by
    -- class and instance bodies.
    knotDecls :: Ctx -> FamilyStyle -> [LHsDecl GhcPs] -> Doc
  }

-- | Whether a declaration stands on its own or inside a class or an
-- instance.
data FamilyStyle
  = Associated
  | Free
  deriving (Eq, Show)

----------------------------------------------------------------------------
-- Extensions

-- | Is the extension on?
extensionOn :: Ctx -> Extension -> Bool
extensionOn ctx e = Set.member e (rcExtensions (ctxRender ctx))

-- | With @NegativeLiterals@ on, @- 1@ and @-1@ are different, so the minus
-- in front of a literal has to keep its distance.
negativeLiteralGap :: Ctx -> Doc
negativeLiteralGap ctx = includeWhen (extensionOn ctx NegativeLiterals) space

-- | A reserved symbol in its @UnicodeSyntax@ form, where that extension is
-- in force and the symbol has one.
reserved :: Ctx -> Text -> Text
reserved ctx symbol
  | extensionOn ctx UnicodeSyntax = case symbol of
      "::" -> "∷"
      "=>" -> "⇒"
      "->" -> "→"
      "<-" -> "←"
      "forall" -> "∀"
      "-<" -> "⤙"
      ">-" -> "⤚"
      "-<<" -> "⤛"
      ">>-" -> "⤜"
      "(|" -> "⦇"
      "|)" -> "⦈"
      "*" -> "★"
      _ -> symbol
  | otherwise = symbol
{-# INLINE reserved #-}

----------------------------------------------------------------------------
-- Fixities

-- | The fixity of an operator, if one was established.
operatorFixity :: Ctx -> Namespace -> RdrName -> Maybe Fixity
operatorFixity ctx namespace name = do
  scope <- rcScope (ctxRender ctx)
  case lookupFixity scope namespace (qualifierOf name) (opName name) of
    Resolved fixity _ -> Just fixity
    Unresolved _ -> Nothing

----------------------------------------------------------------------------
-- What lies between two spans

-- | Did the author leave an empty line directly after the first of these,
-- past directives and Haddocks?
separatedByBlank :: Ctx -> Maybe Span -> Maybe Span -> Bool
separatedByBlank ctx (Just a) (Just b) =
  any (writtenBlank ctx) . takeWhile (passedOver ctx) $
    [spanEndLine a + 1 .. spanStartLine b - 1]
separatedByBlank _ _ _ = False

-- | Is this line empty, a preprocessor directive, a Haddock's, or one this
-- configuration does not contain?
passedOver :: Ctx -> Int -> Bool
passedOver ctx n = case lineAt n ls of
  Nothing -> True
  Just t -> T.all isSpace t || directivePresentOnLine n ls || documenting
  where
    ls = sourceLines (ctxSource ctx)
    documenting =
      maybe False ((>= n) . spanEndLine . commentSpan . snd) $
        Map.lookupLE (n, maxBound) (ctxHaddocks ctx)

-- | Is a preprocessor directive written between the two spans?
directiveBetween ::
  -- | The context.
  Ctx ->
  -- | What comes first.
  Maybe Span ->
  -- | What comes next.
  Maybe Span ->
  Bool
directiveBetween ctx (Just a) (Just b) =
  any
    (`directivePresentOnLine` sourceLines (ctxSource ctx))
    [spanEndLine a + 1 .. spanStartLine b - 1]
directiveBetween _ _ _ = False

-- | Did the author leave this line empty?
--
-- Asked of the module as written, so that a line the preprocessor support
-- emptied to make one configuration does not read as one the author left
-- blank.
writtenBlank :: Ctx -> Int -> Bool
writtenBlank ctx n = blankAt n (sourceLines (ctxSource ctx))

----------------------------------------------------------------------------
-- Entering the tree

-- | Enter a located node.
--
-- This is the counterpart of every @L@ in the syntax tree: it records where
-- the output came from, so that comments can be attached to it later, and
-- it settles the node's layout from the region it occupied. A node written
-- as the argument list of a use of a function-like macro is printed as it
-- was written, since cpp pastes that into the macro's body.
at :: HasLoc l => Ctx -> GenLocated l a -> (a -> Doc) -> Doc
at ctx l f = atSpan ctx s $ case s of
  Just x
    | not (Set.null pasted),
      Set.member x pasted,
      Just written <- writtenAt ctx x ->
        txt written
  _ -> f (GHC.unLoc l)
  where
    s = spanOf l
    pasted = rcMacroArguments (ctxRender ctx)

-- | 'at' with the arguments the other way round, for use in sections.
at_ :: HasLoc l => Ctx -> (a -> Doc) -> GenLocated l a -> Doc
at_ ctx f l = at ctx l f

-- | Lay a region out as 'layoutFrom' does, and claim it: a comment written
-- anywhere inside the region attaches to this document.
atSpan :: Ctx -> Maybe Span -> Doc -> Doc
atSpan _ Nothing d = d
atSpan ctx (Just s) d = located s (layoutFrom ctx (Just s) d)

-- | A keyword, claiming the span it was written on.
keywordAt ::
  -- | Where it was written.
  Maybe Span ->
  -- | The keyword.
  Text ->
  Doc
keywordAt s = maybe id located s . txt

-- | Lay a region out broken where it was written over several lines, and
-- otherwise flat where it fits within the column limit, claiming nothing.
--
-- The lines of a quasi-quotation count as one, since they are reproduced
-- rather than laid out.
layoutFrom :: Ctx -> Maybe Span -> Doc -> Doc
layoutFrom ctx s
  | maybe True (writtenOnOneLine ctx) s = frangible
  | otherwise = broken

-- | 'layoutFrom' over the region several located things cover.
layoutAcross :: HasLoc l => Ctx -> [GenLocated l a] -> Doc -> Doc
layoutAcross ctx xs = layoutFrom ctx (spansOf xs)

-- | 'attach' an operator and its operand, placed on their line as told,
-- leaving the operator's region at the end of the line when it was written
-- there, so that the comments written around it stay on that line, and
-- giving the indentation of the operand's line a region, so that those
-- above the operand come before it.
attachOperator ::
  -- | How the operator and its operand attach to what they follow.
  Placement ->
  -- | How their line is placed.
  (Doc -> Doc) ->
  -- | What the operator follows.
  Maybe Span ->
  -- | The operator.
  Maybe Span ->
  -- | Its operand.
  Maybe Span ->
  -- | The operator, printed.
  Doc ->
  -- | Its operand, printed.
  Doc ->
  Doc
attachOperator placement placing before here after op operand =
  case here of
    Just s
      | placement == Normal,
        sameLine before here,
        not (sameLine here after) ->
          located s mempty
            <> attach
              Normal
              ( placing
                  ( foldMap indentation after
                      <> leadingOperator (unclaimed op)
                      <> space
                      <> operand
                  )
              )
    _ -> attach placement (placing (leadingOperator op <> space <> operand))

-- | The @::@, @=>@ or @->@ that joins two parts of a type, at the end of a
-- line or at the start of the next one, as the project asks.
joinedByArrow ::
  -- | The context.
  Ctx ->
  -- | Where the line may break.
  Doc ->
  -- | What the arrow follows.
  Maybe Span ->
  -- | What it leads to.
  Maybe Span ->
  -- | The arrow.
  Text ->
  Doc
joinedByArrow ctx separator before after arrow = case ctxArrowStyle ctx of
  TrailingArrows -> trailing (txt arrow) <> separator
  LeadingArrows ->
    separator
      <> lineLed before after
      <> leading (txt arrow)

-- | A region over the indentation of the line a part begins, where that
-- line is below the part before it, so that the comments written above it
-- come before what leads it.
lineLed ::
  -- | The part before.
  Maybe Span ->
  -- | The part.
  Maybe Span ->
  Doc
lineLed before after = case (before, after) of
  (Just b, Just a) | spanEndLine b < spanStartLine a -> indentation a
  _ -> mempty

-- | A region over the indentation of the line a span begins on.
indentation :: Span -> Doc
indentation s = located (mkSpan (spanStartLine s, 1) (startPoint s)) mempty

-- | Was the region written on one line, the lines of a quasi-quotation
-- counting as one?
writtenOnOneLine :: Ctx -> Span -> Bool
writtenOnOneLine ctx s = from (spanStartLine s)
  where
    from n =
      n >= spanEndLine s
        || maybe False from (quoteEndingFrom n (ctxSource ctx))

-- | What was written at a span within one line.
writtenAt :: Ctx -> Span -> Maybe Text
writtenAt ctx s = do
  l <- lineAt (spanStartLine s) (sourceLines (ctxSource ctx))
  let from = offsetOf l (spanStartColumn s)
  pure (T.take (offsetOf l (spanEndColumn s) - from) (T.drop from l))

----------------------------------------------------------------------------
-- Haddocks

-- | The Haddock the author wrote at this position, if we kept it.
writtenHaddock :: Ctx -> Maybe Span -> Maybe Comment
writtenHaddock ctx ms = do
  s <- ms
  c <- Map.lookup (startPoint s) (ctxHaddocks ctx)
  case commentStyle c of
    DocComment -> Just c
    _ -> Nothing