packages feed

tilia-0.2.0.0: src/Tilia/Pragma.hs

{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}

-- | Pragma-related helpers.
module Tilia.Pragma
  ( Pragma (..),
    pragmaOf,
    movesPositions,
    Defaults (..),
    defaultsOf,
    editionExtensions,
    effectiveExtensions,
    safeImportsOn,
    lookupExtension,
    lookupEdition,
    nameSwitch,
    flagSwitches,
    pragmaFlags,
    languageNames,
    switchedBy,
    commute,
    headerPragmas,
  )
where

import Control.Monad (guard, (<=<))
import Data.Char (isAlphaNum, isDigit, isLower, isSpace, isUpper)
import Data.List (unsnoc)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe, mapMaybe, maybeToList)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Data.FastString (fsLit)
import GHC.Driver.Session qualified as GHC
import GHC.LanguageExtensions.Type (Extension (..))
import GHC.Parser.Header (toArgs)
import GHC.Types.SrcLoc (mkRealSrcLoc, unLoc)

import Tilia.Cpp.Macros (Macros)
import Tilia.Utils (opensLineComment, tshow)

-- | A compiler pragma, which is written as a block comment but is not one.
--
-- GHC reads pragmas only from the file header, so where a pragma sits
-- decides whether it does anything at all. That is why recognising one is
-- not enough on its own: see 'Tilia.Parser.pmHeaderEnd' for the boundary
-- that says which pragmas are real.
data Pragma = Pragma
  { -- | The name, upper-cased as GHC expects it, e.g. @LANGUAGE@.
    pragmaName :: Text,
    -- | Everything between the name and the closing @#-}@, on one line
    -- with one space between its words, as 'spacedOnce' puts it, and
    -- without the comments GHC skips in a @LANGUAGE@ pragma.
    pragmaBody :: Text,
    -- | Whether it holds such a comment.
    pragmaCommented :: Bool
  }
  deriving (Eq, Show)

-- | The pragma written between a @{-#@ and a @#-}@, if it names one.
pragmaOf :: Text -> Maybe Pragma
pragmaOf inner
  | T.null name = Nothing
  | otherwise =
      Just
        Pragma
          { pragmaName = T.toUpper name,
            pragmaBody = spacedOnce body,
            pragmaCommented = uncommented /= inner
          }
  where
    uncommented = withoutSkippedComments inner
    (name, body) = T.break isSpace (T.stripStart uncommented)

-- | A pragma's body on one line, with one space wherever white space
-- separates two of its words, but inside a string literal, which GHC reads
-- as one flag of an options pragma.
spacedOnce :: Text -> Text
spacedOnce = T.unwords . wordsOf . T.strip
  where
    wordsOf t
      | T.null t = []
      | otherwise =
          let (w, rest) = wordAt t
           in w : wordsOf (T.stripStart rest)
    wordAt t = case T.break (\c -> isSpace c || c == '"') t of
      (plain, rest)
        | Just ('"', after) <- T.uncons rest ->
            let (literal, after') = literalAt after
                (w, rest') = wordAt after'
             in (plain <> "\"" <> literal <> w, rest')
        | otherwise -> (plain, rest)
    literalAt t = case T.break (\c -> c == '"' || c == '\\') t of
      (plain, rest) -> case T.uncons rest of
        Just ('\\', escaped) ->
          let (more, after) = literalAt (T.drop 1 escaped)
           in (plain <> "\\" <> T.take 1 escaped <> more, after)
        Just (_, after) -> (plain <> "\"", after)
        Nothing -> (plain, rest)

-- | Recognize @{-# LINE #-}@ and @{-# COLUMN #-}@ pragmas in a module with
-- these extensions in force, and the lines GHC's lexer reads past at the
-- start of a line, but for the @#!@ lines a script begins with.
--
-- Those are the line markers cpp writes, such as @# 40 "M.hs"@, which move
-- positions as a @LINE@ pragma does, and @#pragma@ and @#!@ lines, which
-- leave nothing behind for formatting to print. With CPP on, @#line@ and
-- @#pragma@ lines are directives, which formatting keeps.
movesPositions ::
  -- | The extensions in force.
  Set Extension ->
  -- | The module's source.
  Text ->
  Bool
movesPositions extensions =
  or . scanPragmas positional (pastCode extensions) . T.cons '\n' . script
  where
    positional p = pragmaName p `elem` ["LINE", "COLUMN"]
    script t
      | "#!" `T.isPrefixOf` t = script (T.drop 1 (T.dropWhile (/= '\n') t))
      | otherwise = t

-- | What a component puts in force before the pragmas of a module: its
-- @default-language@, its @default-extensions@ and its @cpp-options@.
data Defaults = Defaults
  { -- | What it turns on and off on top of its edition, in order, and on top
    -- of an edition the module names in its place.
    defaultsSwitches :: [GHC.OnOff Extension],
    -- | What its edition and those switches put in force, worked out once.
    defaultsInForce :: Set Extension,
    -- | Whether it names a Safe Haskell mode.
    defaultsSafe :: Bool,
    -- | What its @cpp-options@ settle about the macros.
    defaultsMacros :: Macros
  }
  deriving (Eq, Show)

-- | What a component puts in force.
defaultsOf ::
  -- | Whether it names a Safe Haskell mode.
  Bool ->
  -- | The extensions of its edition.
  Set Extension ->
  -- | What it switches on top of them, in order.
  [GHC.OnOff Extension] ->
  Defaults
defaultsOf safe edition switches =
  Defaults switches (foldl' switch edition switches) safe mempty

-- | The extensions an edition of the language puts in force, the
-- compiler's default one where none is named.
editionExtensions :: Maybe GHC.Language -> Set Extension
editionExtensions = Set.fromList . GHC.languageExtensions

-- | The extensions actually in force in a module.
--
-- As with GHC, the edition the header names last takes the place of the
-- component's, wherever it is named, and what the component and then the
-- header switch is switched on top of it.
effectiveExtensions ::
  -- | What the component the module belongs to puts in force.
  Defaults ->
  -- | The module's source, read here for the @LANGUAGE@, @OPTIONS_GHC@ and
  -- @OPTIONS@ pragmas of its header alone.
  Text ->
  Set Extension
effectiveExtensions defaults source =
  foldl' switch inForce (concat switches)
  where
    (editions, switches) =
      unzip
        [ editionsAndSwitches (pragmaName p) (pragmaBody p)
        | p <- headerPragmas source
        ]
    inForce = case concat editions of
      [] -> defaultsInForce defaults
      named ->
        foldl'
          switch
          (editionExtensions (Just (last named)))
          (defaultsSwitches defaults)

-- | Are safe imports on, as GHC has them wherever a Safe Haskell mode is in
-- force and @-fno-safe-haskell@ is not given?
safeImportsOn ::
  -- | What the component the module belongs to puts in force.
  Defaults ->
  -- | The module's source, read here for its header pragmas alone.
  Text ->
  Bool
safeImportsOn defaults source =
  (defaultsSafe defaults || any (`elem` modes) flags)
    && notElem "-fno-safe-haskell" flags
  where
    flags =
      concat
        [pragmaFlags (pragmaName p) (pragmaBody p) | p <- headerPragmas source]
    modes = ["-XSafe", "-XTrustworthy", "-XUnsafe"]

-- | The edition a pragma of this name and body names last, if any, and
-- whether it, with what it implies, last turns each extension it switches
-- on or off.
switchedBy ::
  -- | The name.
  Text ->
  -- | The body.
  Text ->
  (Maybe GHC.Language, Map Extension Bool)
switchedBy name body =
  ( snd <$> unsnoc editions,
    foldl'
      (switchWith (`Map.insert` True) (`Map.insert` False))
      Map.empty
      switches
  )
  where
    (editions, switches) = editionsAndSwitches name body

-- | Do two pragmas, given by what they switch, put the same in force in
-- either order?
commute ::
  -- | What one of them switches.
  (Maybe GHC.Language, Map Extension Bool) ->
  -- | What the other switches.
  (Maybe GHC.Language, Map Extension Bool) ->
  Bool
commute (editionA, a) (editionB, b) =
  and (liftA2 (==) editionA editionB)
    && and (Map.intersectionWith (==) a b)

-- | The editions a pragma of this name and body names, and what it turns on
-- and off.
editionsAndSwitches :: Text -> Text -> ([GHC.Language], [GHC.OnOff Extension])
editionsAndSwitches name body =
  ( mapMaybe (lookupEdition <=< T.stripPrefix "-X") flags,
    concatMap flagSwitches flags
  )
  where
    flags = pragmaFlags name body

-- | The flags a pragma of this name and body gives GHC: each name of a
-- @LANGUAGE@ pragma after @-X@, and the flags of an options pragma.
pragmaFlags :: Text -> Text -> [Text]
pragmaFlags name body = case name of
  "LANGUAGE" -> ["-X" <> n | n <- languageNames body]
  "OPTIONS_GHC" -> optionFlags body
  "OPTIONS" -> optionFlags body
  _ -> []

-- | The flags of the body of an options pragma, split as GHC splits them.
optionFlags :: Text -> [Text]
optionFlags body =
  either (const (T.words body)) (fmap (T.pack . unLoc)) $
    toArgs (mkRealSrcLoc (fsLit "") 1 1) (T.unpack body)

-- | The extension a name turns on, or off where it puts @No@ in front of one.
nameSwitch :: Text -> Maybe (GHC.OnOff Extension)
nameSwitch name = case T.stripPrefix "No" name >>= lookupExtension of
  Just off -> Just (GHC.Off off)
  Nothing -> GHC.On <$> lookupExtension name

-- | What a flag of an @OPTIONS_GHC@ or @OPTIONS@ pragma turns on and off.
flagSwitches :: Text -> [GHC.OnOff Extension]
flagSwitches flag
  | Just name <- T.stripPrefix "-X" flag = maybeToList (nameSwitch name)
  | flag == "-cpp" = [GHC.On Cpp]
  | flag == "-fglasgow-exts" = GHC.On <$> GHC.glasgowExtsFlags
  | flag == "-fno-glasgow-exts" = GHC.Off <$> GHC.glasgowExtsFlags
  | Just name <- T.stripPrefix "-fno-" flag = GHC.Off <$> oldFlag name
  | Just name <- T.stripPrefix "-f" flag = GHC.On <$> oldFlag name
  | otherwise = []
  where
    oldFlag name = maybeToList (Map.lookup name extensionsByOldFlag)

-- | Turn an extension on or off.
switch :: Set Extension -> GHC.OnOff Extension -> Set Extension
switch = switchWith Set.insert Set.delete

-- | Turn an extension on, and then what it implies, or turn it off alone, as
-- GHC does.
switchWith ::
  -- | How to turn one extension on.
  (Extension -> a -> a) ->
  -- | How to turn one extension off.
  (Extension -> a -> a) ->
  -- | What is on so far.
  a ->
  -- | What to turn on or off.
  GHC.OnOff Extension ->
  a
switchWith on off acc = \case
  GHC.On e ->
    foldl' (switchWith on off) (on e acc) (Map.findWithDefault [] e impliedBy)
  GHC.Off e -> off e acc

-- | What GHC turns on or off besides when it turns an extension on.
impliedBy :: Map Extension [GHC.OnOff Extension]
impliedBy =
  Map.fromListWith
    (flip (<>))
    [(from, [implied]) | (from, implied) <- GHC.impliedXFlags]

-- | The extensions a @LANGUAGE@ pragma names, as written.
languageNames :: Text -> [Text]
languageNames = filter (not . T.null) . fmap T.strip . T.splitOn ","

-- | Parse the name of an edition of the language, such as @GHC2021@.
lookupEdition :: Text -> Maybe GHC.Language
lookupEdition name = Map.lookup name editionsByName

-- | Every edition of the language this compiler knows, by its name.
editionsByName :: Map Text GHC.Language
editionsByName =
  Map.fromList [(tshow e, e) | e <- [minBound .. maxBound]]

-- | Parse an extension name.
lookupExtension :: Text -> Maybe Extension
lookupExtension name = Map.lookup name extensionsByName

-- | Every extension this compiler knows, by the name one writes in a
-- pragma.
extensionsByName :: Map Text Extension
extensionsByName = byFlagName GHC.xFlags

-- | Every extension an old @-f@ flag such as @-fbang-patterns@ turns on, by
-- the flag without its @-f@.
extensionsByOldFlag :: Map Text Extension
extensionsByOldFlag = byFlagName GHC.fLangFlags

-- | Extensions by the names of the flags that turn them on.
byFlagName :: [GHC.FlagSpec Extension] -> Map Text Extension
byFlagName flags =
  Map.fromList [(T.pack (GHC.flagSpecName f), GHC.flagSpecFlag f) | f <- flags]

-- | Carry on past the code of a module with these extensions in force, over
-- its strings, characters and quasi-quotations, up to a line that GHC's
-- lexer reads past and formatting would lose.
pastCode ::
  -- | The extensions in force.
  Set Extension ->
  -- | How to carry on from where a piece of code ends.
  (Text -> [Bool]) ->
  -- | What is left of the module.
  Text ->
  [Bool]
pastCode extensions = past
  where
    past go t = case T.uncons t of
      Just ('\n', after) | readPast after -> [True]
      Just ('"', after) -> go (skipString after)
      Just ('\'', after) -> go (skipCharacter after)
      _
        | Set.member QuasiQuotes extensions,
          Just body <- quasiQuotation t ->
            go (T.drop 2 (snd (T.breakOn "|]" body)))
        | otherwise -> go (skipCode t)

    withoutCpp = Set.notMember Cpp extensions
    readPast l = case T.uncons l of
      Just ('#', rest) ->
        (withoutCpp && any (`T.isPrefixOf` rest) ["line", "pragma"])
          || "!" `T.isPrefixOf` rest
          || T.any isDigit (T.take 1 (fromMaybe rest (T.stripPrefix " " rest)))
      Just (' ', rest) -> "#!" `T.isPrefixOf` rest
      _ -> False

    quasiQuotation t = do
      (quoter, rest) <- T.span inQuoter <$> T.stripPrefix "[" t
      (modules, name) <- unsnoc (T.splitOn "." quoter)
      guard (all (begins isUpper) modules && begins varStart name)
      T.stripPrefix "|" rest
    inQuoter c = inName c || c == '.'
    begins p = maybe False (p . fst) . T.uncons
    varStart c = isLower c || c == '_'

    skipString = inString . T.dropWhile (\c -> c /= '"' && c /= '\\')

    inString t
      | T.null t = t
      | Just after <- T.stripPrefix "\\" t =
          skipString (T.drop 1 (T.dropWhile isSpace after))
      | Just after <- T.stripPrefix "\"" t = after
      | otherwise = skipString (T.drop 1 t)

    skipCharacter t = case T.unpack (T.take 2 t) of
      ['\\', _] -> T.drop 1 (T.dropWhile (/= '\'') (T.drop 2 t))
      [c, '\''] | c /= '\'' -> T.drop 2 t
      _ -> t

    skipCode t =
      let (plain, rest) = T.break opens (T.drop 1 t)
          before = maybe (T.head t) snd (T.unsnoc plain)
       in if "'" `T.isPrefixOf` rest && inName before
            then skipCode rest
            else rest
    opens c =
      c == '{' || c == '-' || c == '"' || c == '\'' || c == '[' || c == '\n'
    inName c = isAlphaNum c || c == '_' || c == '\''

-- | The pragmas of a module's header: those above the first thing that is
-- neither a comment, a directive nor a pragma, which are all GHC reads.
headerPragmas :: Text -> [Pragma]
headerPragmas = scanPragmas id past
  where
    past go t = case T.uncons t of
      Just (c, _)
        | isSpace c -> go (T.stripStart t)
        | c == '#' -> go (T.dropWhile (/= '\n') t)
      _ -> []

-- | What the given function makes of the pragmas of a module, carrying on
-- past what is neither a comment nor a pragma as the other given function
-- does.
scanPragmas ::
  -- | What to make of a pragma.
  (Pragma -> a) ->
  -- | How to carry on past the rest, given how to carry on from there.
  ((Text -> [a]) -> Text -> [a]) ->
  -- | The module's source.
  Text ->
  [a]
scanPragmas pragma past = go
  where
    go t
      | T.null t = []
      | Just body <- T.stripPrefix "{-#" t = case T.breakOn "#-}" body of
          (_, after) | T.null after -> []
          (inner, after) ->
            maybe id ((:) . pragma) (pragmaOf inner) (go (T.drop 3 after))
      | Just after <- T.stripPrefix "{-" t = go (skipBlock (1 :: Int) after)
      | opensLineComment t = go (T.dropWhile (/= '\n') t)
      | otherwise = past go t

-- | What a pragma holds between its @{-#@ and its @#-}@, without the
-- comments GHC skips in it: those of a @LANGUAGE@ pragma.
withoutSkippedComments :: Text -> Text
withoutSkippedComments inner
  | T.any (\c -> c == '-' || c == '{') inner,
    T.toUpper keyword == "LANGUAGE" =
      withoutComments inner
  | otherwise = inner
  where
    keyword = T.takeWhile (not . isSpace) (T.stripStart inner)

-- | A text without its comments, each of which leaves a space behind.
withoutComments :: Text -> Text
withoutComments t
  | T.null t = t
  | Just after <- T.stripPrefix "{-" t =
      " " <> withoutComments (skipBlock (1 :: Int) after)
  | opensLineComment t = withoutComments (T.dropWhile (/= '\n') t)
  | otherwise =
      let (plain, rest) = T.break (\c -> c == '{' || c == '-') (T.drop 1 t)
       in T.take 1 t <> plain <> withoutComments rest

-- | What follows the end of a block comment this deep in comments.
skipBlock :: Int -> Text -> Text
skipBlock 0 t = t
skipBlock n t0 = inBlock (T.dropWhile (\c -> c /= '{' && c /= '-') t0)
  where
    inBlock t
      | T.null t = t
      | Just after <- T.stripPrefix "{-" t = skipBlock (n + 1) after
      | Just after <- T.stripPrefix "-}" t = skipBlock (n - 1) after
      | otherwise = skipBlock n (T.drop 1 t)