tilia-0.2.0.1: src/Tilia/Fixity/Interface.hs
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | Reading a module's operators out of interface files.
module Tilia.Fixity.Interface
( Interface (..),
readInterface,
showIface,
parseInterface,
shownHiFile,
fromHiFile,
)
where
import Control.DeepSeq (NFData)
import Data.Bifunctor (first)
import Data.ByteString qualified as BS
import Data.Char (isUpper)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (listToMaybe, mapMaybe)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Text (Text)
import Data.Text qualified as T
import GHC.Generics (Generic)
import Tilia.Fixity
import Tilia.Fixity.HiFile
( HiExport (..),
HiFile (..),
HiName (..),
decodeHiFile,
)
import Tilia.Process (readProgramOutput)
import Tilia.Utils (blocksOf, quietly)
-- | What an interface says about the operators a module offers.
data Interface = Interface
{ -- | The fixities the module declares itself for the names it exports,
-- by the namespace each governs.
interfaceDeclares :: Fixities,
-- | The names it reexports, each with the source module and the
-- namespace it is exported in.
interfaceReexports :: [(Text, Namespace, OpName)],
-- | The members it exports with each name, which is what @T(..)@ in an
-- import list stands for.
interfaceMembers :: Map OpName (Set (Namespace, OpName)),
-- | What it certainly brings into scope, where an interface file says.
interfaceExports :: Maybe Certain
}
deriving (Eq, Show, Generic)
instance NFData Interface
-- | Read a module's interface file.
--
-- The file is decoded directly where it can be, and read off 'showIface'
-- otherwise.
readInterface ::
-- | The module the file is supposed to hold.
Text ->
-- | The file.
FilePath ->
IO (Maybe Interface)
readInterface modName path =
quietly Nothing $
decodeHiFile <$> BS.readFile path >>= \case
Right hi -> pure (either (const Nothing) Just (fromHiFile modName hi))
Left _ -> (parseInterface modName =<<) <$> showIface path
-- | What a decoded interface file says, if it is this module's.
fromHiFile :: Text -> HiFile -> Either Text Interface
fromHiFile modName HiFile{..}
| hiModule /= modName = Left ("the interface of " <> hiModule)
| otherwise =
Right
Interface
{ interfaceDeclares =
foldl'
(flip Map.delete)
fixities
[ (namespace, op)
| not (Map.null fixities),
(_, namespace, op) <- reexports
],
interfaceReexports = reexports,
interfaceMembers = members,
interfaceExports =
Just
Certain
{ certainNames = exportedHere,
certainMembers = members
}
}
where
exported = mapMaybe known (concatMap exportedNames hiExports)
exportedHere =
Set.fromList [(namespace, op) | (_, namespace, op) <- exported]
fixities =
Map.fromList
[ ((namespace, op), fixity)
| (namespace, op, fixity) <- hiFixities,
Set.member (namespace, op) exportedHere
]
reexports =
[ (m, namespace, op)
| HiName m namespace op <- concatMap exportedNames hiExports,
m /= hiModule
]
members =
Map.fromListWith
Set.union
[ (op, Set.fromList [(namespace, kid) | (_, namespace, kid) <- kids])
| AvailTC p ns <- hiExports,
Just parent@(_, _, op) <- [known p],
let kids = filter (/= parent) (mapMaybe known ns)
]
exportedNames = \case
Avail n -> [n]
AvailTC _ ns -> ns
known = \case
HiName m namespace op -> Just (Just m, namespace, op)
BuiltInSyntax namespace op -> Just (Nothing, namespace, op)
Unneeded -> Nothing
-- | What @ghc --show-iface@ prints for an interface file, with each name
-- annotated with its namespace.
showIface :: FilePath -> IO (Maybe Text)
showIface path = readProgramOutput "ghc" ["--show-iface", path, "-dppr-debug"]
-- | Read what 'showIface' printed, if it is this module's interface.
parseInterface :: Text -> Text -> Maybe Interface
parseInterface modName out =
either (const Nothing) Just . fromHiFile modName =<< shownHiFile out
-- | What 'showIface' printed, as decoding the file would give it.
shownHiFile :: Text -> Maybe HiFile
shownHiFile out = do
self <-
listToMaybe
[ m
| l <- T.lines out,
Just rest <- [T.stripPrefix "interface " l],
m : _ <- [T.words rest]
]
exports <- traverse exportEntries (sectionsNamed "exports:")
pure
HiFile
{ hiModule = self,
hiExports = concat exports,
hiFixities =
mapMaybe
fixityEntry
(concatMap (T.splitOn ",") (sectionsNamed "fixities"))
}
where
sectionsNamed name =
[body | (heading, body) <- sections out, heading == name]
-- | Split the output into sections.
sections :: Text -> [(Text, Text)]
sections out =
[ (heading, T.unwords (opening : body))
| (l, body) <- blocksOf (T.lines out),
let (heading, opening) = T.breakOn " " l
]
-- | One entry of a @fixities@ line: @infixl 9 !{v}@ and the like.
fixityEntry :: Text -> Maybe (Namespace, OpName, Fixity)
fixityEntry entry = case T.words entry of
direction : precedence : written@(_ : _) -> do
d <- case direction of
"infixl" -> Just LeftAssoc
"infixr" -> Just RightAssoc
"infix" -> Just NoAssoc
_ -> Nothing
p <- readPrecedence precedence
let (op, rest) = T.break (== '{') (T.unwords written)
namespace <- namespaceOf =<< T.stripSuffix "}" =<< T.stripPrefix "{" rest
pure (namespace, OpName op, Fixity d p)
_ -> Nothing
-- | The entries of an exports section, unless one cannot be read.
--
-- An entry with members in braces is a type or class, exported itself
-- unless a bar before the braces, as in @T|{...}@, says it is not.
exportEntries :: Text -> Maybe [HiExport]
exportEntries text = case T.uncons (separated text) of
Nothing -> Just []
Just _ -> do
(parent, rest) <- shownName (separated text)
(entry, after) <- case T.uncons rest of
Just ('{', inside) ->
first (AvailTC parent . (parent :)) <$> members inside
Just ('|', bar)
| Just inside <- T.stripPrefix "{" bar ->
first (AvailTC parent) <$> members inside
_ -> Just (Avail parent, rest)
(entry :) <$> exportEntries after
where
members t = case T.uncons (separated t) of
Just ('}', after) -> Just ([], after)
_ -> do
(kid, rest) <- shownName (separated t)
first (kid :) <$> members rest
separated = T.dropWhile (== ' ')
-- | One name as 'showIface' prints it, and the text after it.
--
-- GHC 9.6 and older print a record field as its label with its selector in
-- braces and flags after them. A name printed bare, with no namespace, is
-- built-in syntax, such as @[]@ or @(,)@, whose members follow in braces
-- the way a field's selector does.
shownName :: Text -> Maybe (HiName, Text)
shownName t = case T.uncons rest of
Just ('{', inside)
| (note, after) <- T.break (\c -> c == '{' || c == '}') inside,
Just remaining <- T.stripPrefix "}" after -> do
namespace <- namespaceOf note
(m, op) <- moduleOf written
pure (HiName m namespace (OpName op), remaining)
| T.take 1 written `elem` ["(", "["] -> Just (Unneeded, rest)
| otherwise -> do
(selector, after) <- shownName inside
flagged <- T.stripPrefix "}" after
case selector of
HiName m _ _ ->
pure
( HiName m InTerms (OpName written),
T.dropWhile (\c -> c /= ' ' && c /= '}') flagged
)
_ -> Nothing
_
| T.null written -> Nothing
| otherwise -> Just (Unneeded, rest)
where
(written, rest) = T.break (\c -> c == ' ' || c == '{' || c == '}') t
-- | The namespace an annotation such as @(w) tc 3c@ gives a name.
namespaceOf :: Text -> Maybe Namespace
namespaceOf note = case filter (not . T.isPrefixOf "(") (T.words note) of
space : _
| space == "v" || space == "d" || "fld" `T.isPrefixOf` space -> Just InTerms
| space == "tc" -> Just InTypes
_ -> Nothing
-- | Split a name into the module that declared it and the name itself.
moduleOf :: Text -> Maybe (Text, Text)
moduleOf = go []
where
go seen t = case component t of
Just (c, rest) -> go (c : seen) rest
Nothing
| null seen -> Nothing
| otherwise -> Just (T.intercalate "." (reverse seen), t)
component t = do
(c, _) <- T.uncons t
if isUpper c
then case T.break (== '.') t of
(before, rest)
| Just after <- T.stripPrefix "." rest,
not (T.null before) ->
Just (before, after)
_ -> Nothing
else Nothing