packages feed

tilia-0.2.0.0: src/Tilia/Imports.hs

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}

-- | Putting a module's imports in order.
module Tilia.Imports
  ( normalizeImports,
    travellingComments,
  )
where

import Control.Monad (guard)
import Data.Char (isAlphaNum, isSpace)
import Data.Choice (Choice, isTrue)
import Data.Function (on, (&))
import Data.IntMap.Strict (IntMap)
import Data.IntMap.Strict qualified as IntMap
import Data.List (groupBy, sortOn, unfoldr)
import Data.List.NonEmpty (NonEmpty)
import Data.List.NonEmpty qualified as NE
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (isNothing, listToMaybe, mapMaybe)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Data.FastString (unpackFS)
import GHC.Hs
import GHC.Types.Name.Occurrence (occNameString)
import GHC.Types.Name.Reader (RdrName, rdrNameOcc)
import GHC.Types.PkgQual (RawPkgQual (..))
import GHC.Types.SourceText (StringLiteral (..))
import GHC.Types.SrcLoc

import Tilia.Comments
  ( Comment (..),
    CommentStyle (..),
    commentTrailing,
    commentsWithin,
  )
import Tilia.MagicComments (magicCommentOf)
import Tilia.Source (Lines, lineAt)
import Tilia.Span (Span (..), endPoint, isSingleLine, startPoint)
import Tilia.Span.Ghc (bracketsSpan, spanOf)

-- | Sort and fold together a module's imports, the project's own modules
-- after the rest.
normalizeImports ::
  -- | Whether @ImplicitPrelude@ is on.
  Choice "implicitPrelude" ->
  -- | The modules the project's own packages declare, each with the names
  -- of those that declare it.
  Map Text (Set Text) ->
  -- | The lines the imports are not sorted across.
  [Int] ->
  -- | The lines of every conditional's directives, which the names of a
  -- list are not sorted across.
  [Int] ->
  -- | The module's comments.
  [Comment] ->
  -- | Original imports.
  [LImportDecl GhcPs] ->
  -- | Normalized imports, each with the spans of the imports it is folded
  -- out of, in runs that an empty line keeps apart: a run begins wherever
  -- the imports pass between the project's own modules and those of other
  -- packages.
  [[(LImportDecl GhcPs, [Span])]]
normalizeImports
  implicitPrelude
  ownModules
  barriers
  directives
  written
  imports =
    fmap (fmap snd) . groupBy ((==) `on` fst) $
      [ (ours i, x)
      | x@(i, _) <- concatMap stretch (cutAtBarriers barriers tidied)
      ]
    where
      tidied = fmap (fmap (tidyImportList directives)) imports
      identity = importIdentity implicitPrelude ownModules
      ours = iiOwn . identity
      stretch is = foldRuns folded [(key i, i) | i <- is]
      folded run =
        ( foldl1 (foldImports directives) run,
          mapMaybe spanOf (NE.toList run)
        )
      key i
        | Set.member (lineOf i) continued =
            (bare (identity i), Nothing, lineOf i)
        | otherwise = (identity i, hiddenNames i, alone i)
      continued =
        Set.fromList
          [ l
          | d <- directives,
            Just (l, True) <- [IntMap.lookupLT d begins],
            d `notElem` barriers
          ]
      begins =
        IntMap.fromList
          ([(b, False) | b <- barriers] <> [(lineOf i, True) | i <- imports])
      alone i
        | any strands (spanOf i) = lineOf i
        | otherwise = 0
        where
          strands s =
            any
              (unanchored (itemStarts i))
              (filter loose (commentsWithin s written))
          loose = not . commentTrailing
      unanchored starts c = not (any (> endPoint (commentSpan c)) starts)

-- | The comments that go wherever an import does, by the line it begins
-- on: those written right under it, on lines of their own one under
-- another at its column, with an empty line or nothing under them.
travellingComments ::
  -- | The module as written.
  Lines ->
  -- | Its comments, in order.
  [Comment] ->
  -- | The module.
  HsModule GhcPs ->
  IntMap (NonEmpty Comment)
travellingComments ls cs m =
  IntMap.fromList
    [ (spanStartLine s, block)
    | s <- mapMaybe spanOf (hsmodImports m),
      Just block <- [NE.nonEmpty (unfoldr (next s) (spanEndLine s + 1))],
      setApart (spanEndLine (commentSpan (NE.last block)) + 1)
    ]
  where
    byLine =
      IntMap.fromList
        [(spanStartLine (commentSpan c), c) | c <- takeWhile aboveDecls cs]
    aboveDecls c =
      all
        ((spanStartLine (commentSpan c) <) . spanStartLine)
        (spanOf =<< listToMaybe (hsmodDecls m))
    next s n = do
      c <- IntMap.lookup n byLine
      guard $
        not (commentTrailing c)
          && commentStyle c /= DocComment
          && isNothing (magicCommentOf c)
          && spanStartColumn (commentSpan c) == spanStartColumn s
      pure (c, spanEndLine (commentSpan c) + 1)
    setApart n = maybe True (T.all isSpace) (lineAt n ls)

-- | The names an import hides, where it hides any, so that only imports
-- hiding the same names are folded together.
hiddenNames ::
  LImportDecl GhcPs ->
  Maybe [(NameIdentity, Maybe (Bool, [NameIdentity]))]
hiddenNames (L _ decl) = case ideclImportList decl of
  Just (EverythingBut, L _ items) -> Just (fmap (hidden . unLoc) items)
  _ -> Nothing
  where
    hidden item = (nameIdentity item, subordinates item)
    subordinates = \case
      IEThingAll{} -> Just (True, [])
      IEThingWith _ _ _ subs _ -> Just (False, names subs)
      _ -> Nothing
    names = fmap (wrappedNameIdentity . unLoc)

-- | Where every name an import lists begins, each as a line and a column.
--
-- The names inside a thing's own brackets count too, so @T (A, B)@ gives
-- three positions: the start of @T@, of @A@ and of @B@. An import with no
-- list has none at all.
itemStarts :: LImportDecl GhcPs -> [(Int, Int)]
itemStarts (L _ decl) = case ideclImportList decl of
  Nothing -> []
  Just (_, L _ items) -> concatMap starts items
  where
    starts item =
      foldMap ((: []) . startPoint) (spanOf item)
        <> inside (unLoc item)
    inside = \case
      IEThingWith _ _ _ members _ ->
        concatMap (foldMap ((: []) . startPoint) . spanOf) members
      _ -> []

-- | Cut imports, or the names of a list, into the stretches the barriers
-- leave between them.
cutAtBarriers ::
  -- | Lines not to be sorted across, in ascending order.
  [Int] ->
  -- | What to cut, as it was written.
  [GenLocated SrcSpanAnnA a] ->
  -- | One stretch per run between barriers, in the same order.
  [[GenLocated SrcSpanAnnA a]]
cutAtBarriers [] xs = [xs]
cutAtBarriers barriers xs =
  groupBy ((==) `on` fst) [(between i, i) | i <- xs] & fmap (fmap snd)
  where
    between i = length (takeWhile (< lineOf i) barriers)

-- | The line an item begins on, or 0 for one without a place in the input.
lineOf :: GenLocated SrcSpanAnnA a -> Int
lineOf = maybe 0 spanStartLine . spanOf

-- | Sort by the keys, then replace each run of equal keys by one value
-- folded out of it.
foldRuns ::
  Ord k =>
  -- | How to fold the values that share a key, in the order given.
  (NonEmpty a -> b) ->
  -- | The values, each under the key it sorts and folds by.
  [(k, a)] ->
  -- | One value per distinct key, in key order.
  [b]
foldRuns fold' =
  fmap (fold' . fmap snd) . NE.groupBy ((==) `on` fst) . sortOn fst

-- | What has to agree before two imports may be folded together.
--
-- The derived ordering is the whole of the policy: the fields are compared
-- in the order they are declared, which is the order imports are printed
-- in. The three leading fields are about reading rather than about
-- identity. The project's own modules go after the rest, in a group of
-- their own. A @Prelude@ that only refines what the module already has goes
-- at the end of the rest, since looking for it among the @D@s would be
-- looking for the least interesting line in the block. The package goes
-- before the module name so that the imports from one package stay in one
-- run; sorting by module first would interleave them and hide who provides
-- what.
data ImportIdentity = ImportIdentity
  { -- | One of the project's own modules, from the package it names where
    -- it names one.
    iiOwn :: Bool,
    -- | A @Prelude@ that only refines what the module already has.
    iiRefinesPrelude :: Bool,
    -- | The package it names, where it names one.
    iiPackage :: (Int, Text),
    -- | The module it brings in.
    iiModule :: Text,
    -- | Written @{-\# SOURCE \#-}@?
    iiBoot :: Bool,
    -- | Written @safe@?
    iiSafe :: Bool,
    -- | Written @qualified@?
    iiQualified :: Bool,
    -- | The name it was given with @as@, where it was given one.
    iiAlias :: Maybe Text,
    -- | Whether its list hides rather than names, where it has a list.
    iiHides :: Maybe Bool,
    -- | Whether it is a @quote@ rather than a @splice@ import, where it is
    -- levelled at all.
    iiLevel :: Maybe Bool
  }
  deriving (Eq, Ord, Show)

-- | The identity of one import.
importIdentity ::
  -- | Whether @ImplicitPrelude@ is on.
  Choice "implicitPrelude" ->
  -- | The modules the project's own packages declare, each with the names
  -- of those that declare it.
  Map Text (Set Text) ->
  -- | The import.
  LImportDecl GhcPs ->
  ImportIdentity
importIdentity implicitPrelude ownModules (L _ decl) =
  ImportIdentity
    { iiOwn = case qualifier of
        (0, _) -> Map.member module' ownModules
        (1, named') -> any (Set.member named') (Map.lookup module' ownModules)
        _ -> True,
      iiRefinesPrelude =
        isTrue implicitPrelude && module' == T.pack "Prelude",
      iiPackage = qualifier,
      iiModule = module',
      iiBoot = ideclSource decl == IsBoot,
      iiSafe = ideclSafe decl,
      iiQualified = isImportDeclQualified (ideclQualified decl),
      iiAlias = named <$> ideclAs decl,
      iiHides = hides . fst <$> ideclImportList decl,
      iiLevel = lifted (ideclLevelSpec decl)
    }
  where
    module' = named (ideclName decl)
    qualifier = package (ideclPkgQual decl)
    named = T.pack . moduleNameString . unLoc
    package = \case
      NoRawPkgQual -> (0, T.empty)
      RawPkgQual (sl_fs -> fs)
        | name == T.pack "this" -> (2, T.empty)
        | otherwise -> (1, name)
        where
          name = T.pack (unpackFS fs)
    hides = \case
      Exactly -> False
      EverythingBut -> True
    lifted = \case
      NotLevelled -> Nothing
      LevelStylePre l -> Just (quoted l)
      LevelStylePost l -> Just (quoted l)
    quoted = \case
      ImportDeclSplice -> False
      ImportDeclQuote -> True

-- | The identity an import that a conditional continues sorts by, which is
-- the same in every configuration: its fields as far as the module name,
-- and the rest as an import that writes nothing after it.
bare :: ImportIdentity -> ImportIdentity
bare ii =
  ii
    { iiBoot = False,
      iiSafe = False,
      iiQualified = False,
      iiAlias = Nothing,
      iiHides = Nothing,
      iiLevel = Nothing
    }

-- | Keep the first import and give it everything the second named.
foldImports ::
  -- | The lines the names of a list are not sorted across.
  [Int] ->
  -- | The import kept, whose spelling and span the result takes.
  LImportDecl GhcPs ->
  -- | The import folded in, which gives up its list.
  LImportDecl GhcPs ->
  -- | The first, listing what both named.
  LImportDecl GhcPs
foldImports directives (L ann kept) (L _ folded) =
  L
    ann
    kept{ideclImportList = both (ideclImportList kept) (ideclImportList folded)}
  where
    both (Just (interpretation, L l xs)) (Just (_, L l' ys)) =
      Just
        ( interpretation,
          L
            (bracketsAcross l l')
            (tidyImportItems directives interpretation (xs <> ys))
        )
    both _ _ = Nothing

-- | Take the second list's brackets where only they were written across
-- lines, so that a list folded out of several breaks if any of them did.
bracketsAcross :: EpAnn (AnnList a) -> EpAnn (AnnList a) -> EpAnn (AnnList a)
bracketsAcross kept folded
  | onOneLine kept && not (onOneLine folded) =
      kept{anns = (anns kept){al_brackets = al_brackets (anns folded)}}
  | otherwise = kept
  where
    onOneLine = all isSingleLine . bracketsSpan . al_brackets . anns

-- | An import with its list sorted and the entries naming one thing folded
-- together. An import with no list is left as it is.
tidyImportList ::
  -- | The lines the names of a list are not sorted across.
  [Int] ->
  -- | The import.
  ImportDecl GhcPs ->
  ImportDecl GhcPs
tidyImportList directives decl =
  decl
    { ideclImportList = tidied <$> ideclImportList decl
    }
  where
    tidied (interpretation, items) =
      ( interpretation,
        tidyImportItems directives interpretation <$> items
      )

-- | Sort an import list and fold together the entries naming one thing,
-- each stretch between directives on its own.
--
-- @import M (T (A), T (B))@ names one type twice and comes out as @import M
-- (T (A, B))@.
tidyImportItems ::
  -- | The lines the names of a list are not sorted across.
  [Int] ->
  -- | Whether the list names what is imported or what is hidden.
  ImportListInterpretation ->
  -- | The entries.
  [LIE GhcPs] ->
  [LIE GhcPs]
tidyImportItems directives interpretation items
  | any (unnameable . unLoc) items = items
  | otherwise = concatMap tidied (cutAtBarriers directives items)
  where
    tidied stretch =
      foldRuns
        (foldl1 wider)
        [ ((nameIdentity (unLoc i), apart (unLoc i)), fmap sortSubnames i)
        | i <- stretch
        ]
    -- A bare name in a hiding list also hides any data constructor of that
    -- name, which the name with its own parentheses does not.
    apart item = case (interpretation, item) of
      (EverythingBut, IEThingAll{}) -> True
      (EverythingBut, IEThingWith{}) -> True
      _ -> False
    unnameable = \case
      IEVar{} -> False
      IEThingAbs{} -> False
      IEThingAll{} -> False
      IEThingWith{} -> False
      _ -> True

-- | Of two entries naming one thing, the one that brings in more of it.
wider ::
  -- | The entry kept, where the result is.
  LIE GhcPs ->
  -- | The entry folded in.
  LIE GhcPs ->
  LIE GhcPs
wider (L ann kept) (L _ folded) = L ann $ case (kept, folded) of
  (IEThingAll x n _, _) -> IEThingAll x n Nothing
  (_, IEThingAll x n _) -> IEThingAll x n Nothing
  (IEThingWith x n wildcard subs _, IEThingWith x' _ _ subs' _) ->
    IEThingWith
      (parensAcross x x')
      n
      wildcard
      (dedupeSubnames (subs <> subs'))
      Nothing
  (IEThingWith x n wildcard subs _, _) ->
    IEThingWith x n wildcard subs Nothing
  (_, IEThingWith x n wildcard subs _) ->
    IEThingWith x n wildcard subs Nothing
  (IEVar _ n _, _) -> IEVar Nothing n Nothing
  _ -> kept
  where
    parensAcross
      (warning, (open, dots, comma, close))
      (_, (open', _, _, close'))
        | onOneLine open close && not (onOneLine open' close') =
            (warning, (open', dots, comma, close'))
        | otherwise = (warning, (open, dots, comma, close))
    onOneLine open close = all isSingleLine (spanOf open <> spanOf close)

-- | An entry with the names in its own brackets sorted and deduplicated.
sortSubnames :: IE GhcPs -> IE GhcPs
sortSubnames = \case
  IEThingWith x n wildcard subs doc ->
    IEThingWith x n wildcard (dedupeSubnames subs) doc
  other -> other

-- | Deduplicate names in sub-lists.
dedupeSubnames :: [LIEWrappedName GhcPs] -> [LIEWrappedName GhcPs]
dedupeSubnames subs =
  foldRuns NE.head [(wrappedNameIdentity (unLoc s), s) | s <- subs]

-- | Where a name sorts, and what makes two of them name one thing.
--
-- The derived ordering is the whole of the policy: the fields are compared
-- in the order they are declared. Names are grouped first by what kind of
-- thing is named, so that the @pattern@s and the @type@s of an import list
-- stay together. Then the ones spelled with letters come before the ones
-- spelled with punctuation, which gathers the operators at the end where
-- they are easy to find; ordering by character code would scatter them,
-- some before the letters and some after.
data NameIdentity = NameIdentity
  { -- | Which kind of thing is named: a plain name, then a @default@, a
    -- @pattern@, a @type@ and a @data@.
    niKind :: Int,
    -- | Is it spelled with punctuation rather than letters?
    niPunctuation :: Bool,
    -- | The name as it was written.
    niName :: String
  }
  deriving (Eq, Ord, Show)

-- | The identity of the name an entry is about.
nameIdentity :: IE GhcPs -> NameIdentity
nameIdentity = \case
  IEVar _ x _ -> wrappedNameIdentity (unLoc x)
  IEThingAbs _ x _ -> wrappedNameIdentity (unLoc x)
  IEThingAll _ x _ -> wrappedNameIdentity (unLoc x)
  IEThingWith _ x _ _ _ -> wrappedNameIdentity (unLoc x)
  _ ->
    NameIdentity
      { niKind = maxBound,
        niPunctuation = True,
        niName = ""
      }

-- | The identity of one name, as an import list writes it.
wrappedNameIdentity :: IEWrappedName GhcPs -> NameIdentity
wrappedNameIdentity = \case
  IEName _ x -> spelled 0 x
  IEDefault _ x -> spelled 1 x
  IEPattern _ x -> spelled 2 x
  IEType _ x -> spelled 3 x
  IEData _ x -> spelled 4 x
  where
    spelled :: Int -> LocatedN RdrName -> NameIdentity
    spelled kind (unLoc -> name) =
      NameIdentity
        { niKind = kind,
          niPunctuation = punctuation text,
          niName = text
        }
      where
        text = occNameString (rdrNameOcc name)
    punctuation = \case
      (c : _) -> not (isAlphaNum c)
      [] -> False