Commit 73c08ab1 authored by Simon Peyton Jones's avatar Simon Peyton Jones

Re-work the naming story for the GHCi prompt (Trac #8649)

The basic idea here is simple, and described in Note [The interactive package]
in HscTypes, which starts thus:

    Note [The interactive package]
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Type and class declarations at the command prompt are treated as if
    they were defined in modules
       interactive:Ghci1
       interactive:Ghci2
       ...etc...
    with each bunch of declarations using a new module, all sharing a
    common package 'interactive' (see Module.interactivePackageId, and
    PrelNames.mkInteractiveModule).

    This scheme deals well with shadowing.  For example:

       ghci> data T = A
       ghci> data T = B
       ghci> :i A
       data Ghci1.T = A  -- Defined at <interactive>:2:10

    Here we must display info about constructor A, but its type T has been
    shadowed by the second declaration.  But it has a respectable
    qualified name (Ghci1.T), and its source location says where it was
    defined.

    So the main invariant continues to hold, that in any session an original
    name M.T only refers to oe unique thing.  (In a previous iteration both
    the T's above were called :Interactive.T, albeit with different uniques,
    which gave rise to all sorts of trouble.)

This scheme deals nicely with the original problem.  It allows us to
eliminate a couple of grotseque hacks
  - Note [Outputable Orig RdrName] in HscTypes
  - Note [interactive name cache] in IfaceEnv
(both these comments have gone, because the hacks they describe are no
longer necessary). I was also able to simplify Outputable.QueryQualifyName,
so that it takes a Module/OccName as args rather than a Name.

However, matters are never simple, and this change took me an
unreasonably long time to get right.  There are some details in
Note [The interactive package] in HscTypes.
parent 322b48b9
......@@ -41,6 +41,7 @@ module Module
dphParPackageId,
mainPackageId,
thisGhcPackageId,
interactivePackageId, isInteractiveModule,
-- * The Module type
Module,
......@@ -357,20 +358,24 @@ packageIdString = unpackFS . packageIdFS
integerPackageId, primPackageId,
basePackageId, rtsPackageId,
thPackageId, dphSeqPackageId, dphParPackageId,
mainPackageId, thisGhcPackageId :: PackageId
primPackageId = fsToPackageId (fsLit "ghc-prim")
integerPackageId = fsToPackageId (fsLit cIntegerLibrary)
basePackageId = fsToPackageId (fsLit "base")
rtsPackageId = fsToPackageId (fsLit "rts")
thPackageId = fsToPackageId (fsLit "template-haskell")
dphSeqPackageId = fsToPackageId (fsLit "dph-seq")
dphParPackageId = fsToPackageId (fsLit "dph-par")
thisGhcPackageId = fsToPackageId (fsLit ("ghc-" ++ cProjectVersion))
mainPackageId, thisGhcPackageId, interactivePackageId :: PackageId
primPackageId = fsToPackageId (fsLit "ghc-prim")
integerPackageId = fsToPackageId (fsLit cIntegerLibrary)
basePackageId = fsToPackageId (fsLit "base")
rtsPackageId = fsToPackageId (fsLit "rts")
thPackageId = fsToPackageId (fsLit "template-haskell")
dphSeqPackageId = fsToPackageId (fsLit "dph-seq")
dphParPackageId = fsToPackageId (fsLit "dph-par")
thisGhcPackageId = fsToPackageId (fsLit ("ghc-" ++ cProjectVersion))
interactivePackageId = fsToPackageId (fsLit "interactive")
-- | This is the package Id for the current program. It is the default
-- package Id if you don't specify a package name. We don't add this prefix
-- to symbol names, since there can be only one main package per program.
mainPackageId = fsToPackageId (fsLit "main")
isInteractiveModule :: Module -> Bool
isInteractiveModule mod = modulePackageId mod == interactivePackageId
\end{code}
%************************************************************************
......
......@@ -442,17 +442,17 @@ instance OutputableBndr Name where
pprName :: Name -> SDoc
pprName n@(Name {n_sort = sort, n_uniq = u, n_occ = occ})
pprName (Name {n_sort = sort, n_uniq = u, n_occ = occ})
= getPprStyle $ \ sty ->
case sort of
WiredIn mod _ builtin -> pprExternal sty uniq mod occ n True builtin
External mod -> pprExternal sty uniq mod occ n False UserSyntax
WiredIn mod _ builtin -> pprExternal sty uniq mod occ True builtin
External mod -> pprExternal sty uniq mod occ False UserSyntax
System -> pprSystem sty uniq occ
Internal -> pprInternal sty uniq occ
where uniq = mkUniqueGrimily (iBox u)
pprExternal :: PprStyle -> Unique -> Module -> OccName -> Name -> Bool -> BuiltInSyntax -> SDoc
pprExternal sty uniq mod occ name is_wired is_builtin
pprExternal :: PprStyle -> Unique -> Module -> OccName -> Bool -> BuiltInSyntax -> SDoc
pprExternal sty uniq mod occ is_wired is_builtin
| codeStyle sty = ppr mod <> char '_' <> ppr_z_occ_name occ
-- In code style, always qualify
-- ToDo: maybe we could print all wired-in things unqualified
......@@ -462,7 +462,7 @@ pprExternal sty uniq mod occ name is_wired is_builtin
pprNameSpaceBrief (occNameSpace occ),
pprUnique uniq])
| BuiltInSyntax <- is_builtin = ppr_occ_name occ -- Never qualify builtin syntax
| otherwise = pprModulePrefix sty mod name <> ppr_occ_name occ
| otherwise = pprModulePrefix sty mod occ <> ppr_occ_name occ
where
pp_mod = sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressModulePrefixes dflags
......@@ -491,14 +491,14 @@ pprSystem sty uniq occ
-- so print the unique
pprModulePrefix :: PprStyle -> Module -> Name -> SDoc
pprModulePrefix :: PprStyle -> Module -> OccName -> SDoc
-- Print the "M." part of a name, based on whether it's in scope or not
-- See Note [Printing original names] in HscTypes
pprModulePrefix sty mod name = sdocWithDynFlags $ \dflags ->
pprModulePrefix sty mod occ = sdocWithDynFlags $ \dflags ->
if gopt Opt_SuppressModulePrefixes dflags
then empty
else
case qualName sty name of -- See Outputable.QualifyName:
case qualName sty mod occ of -- See Outputable.QualifyName:
NameQual modname -> ppr modname <> dot -- Name is in scope
NameNotInScope1 -> ppr mod <> dot -- Not in scope
NameNotInScope2 -> ppr (modulePackageId mod) <> colon -- Module not in
......
......@@ -265,9 +265,7 @@ instance Outputable RdrName where
ppr (Exact name) = ppr name
ppr (Unqual occ) = ppr occ
ppr (Qual mod occ) = ppr mod <> dot <> ppr occ
ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod name <> ppr occ)
where name = mkExternalName (mkUniqueGrimily 0) mod occ noSrcSpan
-- Note [Outputable Orig RdrName] in HscTypes
ppr (Orig mod occ) = getPprStyle (\sty -> pprModulePrefix sty mod occ <> ppr occ)
instance OutputableBndr RdrName where
pprBndr _ n
......
......@@ -34,7 +34,6 @@ import NameEnv
import Rules
import BasicTypes ( Activation(.. ) )
import CoreMonad ( endPass, CoreToDo(..) )
import PrelNames ( iNTERACTIVE )
import FastString
import ErrUtils
import Outputable
......@@ -232,7 +231,7 @@ deSugarExpr hsc_env tc_expr
; showPass dflags "Desugar"
-- Do desugaring
; (msgs, mb_core_expr) <- initDs hsc_env iNTERACTIVE rdr_env
; (msgs, mb_core_expr) <- initDs hsc_env (icInteractiveModule icntxt) rdr_env
type_env fam_inst_env $
dsLExpr tc_expr
......
......@@ -52,7 +52,6 @@ import FastString
import Config
import Platform
import SysTools
import PrelNames
-- Standard libraries
import Control.Monad
......@@ -525,27 +524,26 @@ getLinkDeps hsc_env hpt pls replace_osuf span mods
-- Find all the packages and linkables that a set of modules depends on
= do {
-- 1. Find the dependent home-pkg-modules/packages from each iface
-- (omitting iINTERACTIVE, which is already linked)
(mods_s, pkgs_s) <- follow_deps (filter ((/=) iNTERACTIVE) mods)
-- (omitting modules from the interactive package, which is already linked)
; (mods_s, pkgs_s) <- follow_deps (filterOut isInteractiveModule mods)
emptyUniqSet emptyUniqSet;
let {
; let {
-- 2. Exclude ones already linked
-- Main reason: avoid findModule calls in get_linkable
mods_needed = mods_s `minusList` linked_mods ;
pkgs_needed = pkgs_s `minusList` pkgs_loaded pls ;
linked_mods = map (moduleName.linkableModule)
(objs_loaded pls ++ bcos_loaded pls)
} ;
(objs_loaded pls ++ bcos_loaded pls) }
-- 3. For each dependent module, find its linkable
-- This will either be in the HPT or (in the case of one-shot
-- compilation) we may need to use maybe_getFileLinkable
let { osuf = objectSuf dflags } ;
lnks_needed <- mapM (get_linkable osuf) mods_needed ;
; let { osuf = objectSuf dflags }
; lnks_needed <- mapM (get_linkable osuf) mods_needed
return (lnks_needed, pkgs_needed) }
; return (lnks_needed, pkgs_needed) }
where
dflags = hsc_dflags hsc_env
this_pkg = thisPackage dflags
......
......@@ -569,7 +569,11 @@ runTR hsc_env thing = do
Just x -> return x
runTR_maybe :: HscEnv -> TR a -> IO (Maybe a)
runTR_maybe hsc_env = fmap snd . initTc hsc_env HsSrcFile False iNTERACTIVE
runTR_maybe hsc_env thing_inside
= do { (_errs, res) <- initTc hsc_env HsSrcFile False
(icInteractiveModule (hsc_IC hsc_env))
thing_inside
; return res }
traceTR :: SDoc -> TR ()
traceTR = liftTcM . traceOptTcRn Opt_D_dump_rtti
......
......@@ -110,12 +110,14 @@ allocateGlobalBinder name_supply mod occ loc
-- Their wired-in-ness is in their NameSort
-- and their Module is correct.
Just name | isWiredInName name -> (name_supply, name)
| mod /= iNTERACTIVE -> (new_name_supply, name')
-- Note [interactive name cache]
Just name | isWiredInName name
-> (name_supply, name)
| otherwise
-> (new_name_supply, name')
where
uniq = nameUnique name
name' = mkExternalName uniq mod occ loc
-- name' is like name, but with the right SrcSpan
new_cache = extendNameCache (nsNames name_supply) mod occ name'
new_name_supply = name_supply {nsNames = new_cache}
......@@ -128,16 +130,6 @@ allocateGlobalBinder name_supply mod occ loc
new_cache = extendNameCache (nsNames name_supply) mod occ name
new_name_supply = name_supply {nsUniqs = us', nsNames = new_cache}
{- Note [interactive name cache]
In GHCi we always create Names with the same Module, ":Interactive".
However, we want to be able to shadow older declarations with newer
ones, and we don't want the Name cache giving us back the same Unique
for the new Name as for the old, hence this special case.
See also Note [Outputable Orig RdrName] in HscTypes.
-}
newImplicitBinder :: Name -- Base name
-> (OccName -> OccName) -- Occurrence name modifier
-> TcRnIf m n Name -- Implicit name
......
......@@ -404,7 +404,7 @@ strDisplayName_llvm lbl = do
dflags <- getDynFlags
let sdoc = pprCLabel platform lbl
depth = Outp.PartWay 1
style = Outp.mkUserStyle (const Outp.NameNotInScope2, const True) depth
style = Outp.mkUserStyle (\ _ _ -> Outp.NameNotInScope2, Outp.alwaysQualifyModules) depth
str = Outp.renderWithStyle dflags sdoc style
return (fsLit (dropInfoSuffix str))
......@@ -422,7 +422,7 @@ strProcedureName_llvm lbl = do
dflags <- getDynFlags
let sdoc = pprCLabel platform lbl
depth = Outp.PartWay 1
style = Outp.mkUserStyle (const Outp.NameUnqual, const False) depth
style = Outp.mkUserStyle Outp.neverQualify depth
str = Outp.renderWithStyle dflags sdoc style
return (fsLit str)
......
......@@ -5,10 +5,10 @@ module DynamicLoading (
forceLoadModuleInterfaces,
forceLoadNameModuleInterface,
forceLoadTyCon,
-- * Finding names
lookupRdrNameInModuleForPlugins,
-- * Loading values
getValueSafely,
getHValueSafely,
......@@ -20,18 +20,16 @@ module DynamicLoading (
import Linker ( linkModule, getHValue )
import SrcLoc ( noSrcSpan )
import Finder ( findImportedModule, cannotFindModule )
import DriverPhases ( HscSource(HsSrcFile) )
import TcRnMonad ( initTc, initIfaceTcRn )
import TcRnMonad ( initTcInteractive, initIfaceTcRn )
import LoadIface ( loadPluginInterface )
import RdrName ( RdrName, Provenance(..), ImportSpec(..), ImpDeclSpec(..)
, ImpItemSpec(..), mkGlobalRdrEnv, lookupGRE_RdrName, gre_name )
import RnNames ( gresFromAvails )
import PrelNames ( iNTERACTIVE )
import DynFlags
import HscTypes ( HscEnv(..), FindResult(..), ModIface(..), lookupTypeHscEnv )
import HscTypes
import BasicTypes ( HValue )
import TypeRep ( TyThing(..), pprTyThingCategory )
import TypeRep ( pprTyThingCategory )
import Type ( Type, eqType )
import TyCon ( TyCon )
import Name ( Name, nameModule_maybe )
......@@ -52,7 +50,10 @@ import GHC.Exts ( unsafeCoerce# )
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
forceLoadModuleInterfaces :: HscEnv -> SDoc -> [Module] -> IO ()
forceLoadModuleInterfaces hsc_env doc modules
= (initTc hsc_env HsSrcFile False iNTERACTIVE $ initIfaceTcRn $ mapM_ (loadPluginInterface doc) modules) >> return ()
= (initTcInteractive hsc_env $
initIfaceTcRn $
mapM_ (loadPluginInterface doc) modules)
>> return ()
-- | Force the interface for the module containing the name to be loaded. The 'SDoc' parameter is used
-- for debugging (@-ddump-if-trace@) only: it is shown as the reason why the module is being loaded.
......@@ -151,7 +152,9 @@ lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
case found_module of
Found _ mod -> do
-- Find the exports of the module
(_, mb_iface) <- initTc hsc_env HsSrcFile False iNTERACTIVE $ initIfaceTcRn $ loadPluginInterface (ptext (sLit "contains a name used in an invocation of lookupRdrNameInModule")) mod
(_, mb_iface) <- initTcInteractive hsc_env $
initIfaceTcRn $
loadPluginInterface doc mod
case mb_iface of
Just iface -> do
-- Try and find the required name in the exports
......@@ -166,8 +169,9 @@ lookupRdrNameInModuleForPlugins hsc_env mod_name rdr_name = do
Nothing -> throwCmdLineErrorS dflags $ hsep [ptext (sLit "Could not determine the exports of the module"), ppr mod_name]
err -> throwCmdLineErrorS dflags $ cannotFindModule dflags mod_name err
where dflags = hsc_dflags hsc_env
where
dflags = hsc_dflags hsc_env
doc = ptext (sLit "contains a name used in an invocation of lookupRdrNameInModule")
wrongTyThingError :: Name -> TyThing -> SDoc
wrongTyThingError name got_thing = hsep [ptext (sLit "The name"), ppr name, ptext (sLit "is not that of a value but rather a"), pprTyThingCategory got_thing]
......
......@@ -283,9 +283,10 @@ hscTcRcLookupName hsc_env0 name = runInteractiveHsc hsc_env0 $ do
-- is used to indicate that.
hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [ClsInst], [FamInst]))
hscTcRnGetInfo hsc_env0 name = runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
ioMsgMaybe' $ tcRnGetInfo hsc_env name
hscTcRnGetInfo hsc_env0 name
= runInteractiveHsc hsc_env0 $
do { hsc_env <- getHscEnv
; ioMsgMaybe' $ tcRnGetInfo hsc_env name }
#ifdef GHCI
hscIsGHCiMonad :: HscEnv -> String -> IO Name
......@@ -1327,7 +1328,7 @@ you run it you get a list of HValues that should be the same length as the list
of names; add them to the ClosureEnv.
A naked expression returns a singleton Name [it]. The stmt is lifted into the
IO monad as explained in Note [Interactively-bound Ids in GHCi] in TcRnDriver
IO monad as explained in Note [Interactively-bound Ids in GHCi] in HscTypes
-}
#ifdef GHCI
......@@ -1349,16 +1350,18 @@ hscStmtWithLocation :: HscEnv
-> IO (Maybe ([Id], IO [HValue], FixityEnv))
hscStmtWithLocation hsc_env0 stmt source linenumber =
runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
maybe_stmt <- hscParseStmtWithLocation source linenumber stmt
case maybe_stmt of
Nothing -> return Nothing
Just parsed_stmt -> do
-- Rename and typecheck it
-- Here we lift the stmt into the IO monad, see Note
-- [Interactively-bound Ids in GHCi] in TcRnDriver
(ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt hsc_env parsed_stmt
hsc_env <- getHscEnv
let interactive_hsc_env = setInteractivePackage hsc_env
-- Bindings created here belong to the interactive package
-- See Note [The interactive package] in HscTypes
-- (NB: maybe not necessary, since Stmts bind only Ids)
(ids, tc_expr, fix_env) <- ioMsgMaybe $ tcRnStmt interactive_hsc_env parsed_stmt
-- Desugar it
ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env tc_expr
......@@ -1366,6 +1369,9 @@ hscStmtWithLocation hsc_env0 stmt source linenumber =
handleWarnings
-- Then code-gen, and link it
-- It's important NOT to have package 'interactive' as thisPackageId
-- for linking, else we try to link 'main' and can't find it.
-- Whereas the linker already knows to ignore 'interactive'
let src_span = srcLocSpan interactiveSrcLoc
hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr
let hval_io = unsafeCoerce# hval :: IO [HValue]
......@@ -1386,12 +1392,15 @@ hscDeclsWithLocation :: HscEnv
-> IO ([TyThing], InteractiveContext)
hscDeclsWithLocation hsc_env0 str source linenumber =
runInteractiveHsc hsc_env0 $ do
hsc_env <- getHscEnv
L _ (HsModule{ hsmodDecls = decls }) <-
hscParseThingWithLocation source linenumber parseModule str
{- Rename and typecheck it -}
tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env decls
hsc_env <- getHscEnv
let interactive_hsc_env = setInteractivePackage hsc_env
-- Bindings created here belong to the interactive package
-- See Note [The interactive package] in HscTypes
tc_gblenv <- ioMsgMaybe $ tcRnDeclsi interactive_hsc_env decls
{- Grab the new instances -}
-- We grab the whole environment because of the overlapping that may have
......@@ -1432,7 +1441,6 @@ hscDeclsWithLocation hsc_env0 str source linenumber =
prepd_binds data_tycons mod_breaks
let src_span = srcLocSpan interactiveSrcLoc
hsc_env <- getHscEnv
liftIO $ linkDecls hsc_env src_span cbc
let tcs = filterOut isImplicitTyCon (mg_tcs simpl_mg)
......@@ -1611,7 +1619,7 @@ hscCompileCoreExpr' hsc_env srcspan ds_expr
; lintInteractiveExpr "hscCompileExpr" hsc_env prepd_expr
{- Convert to BCOs -}
; bcos <- coreExprToBCOs dflags iNTERACTIVE prepd_expr
; bcos <- coreExprToBCOs dflags (icInteractiveModule (hsc_IC hsc_env)) prepd_expr
{- link it -}
; hval <- linkExpr hsc_env srcspan bcos
......
......@@ -31,7 +31,7 @@ module HscTypes (
-- * State relating to modules in this package
HomePackageTable, HomeModInfo(..), emptyHomePackageTable,
hptInstances, hptRules, hptVectInfo,
hptInstances, hptRules, hptVectInfo, pprHPT,
hptObjs,
-- * State relating to known packages
......@@ -50,8 +50,8 @@ module HscTypes (
InteractiveContext(..), emptyInteractiveContext,
icPrintUnqual, icInScopeTTs, icExtendGblRdrEnv,
extendInteractiveContext, substInteractiveContext,
setInteractivePrintName,
InteractiveImport(..),
setInteractivePrintName, icInteractiveModule,
InteractiveImport(..), setInteractivePackage,
mkPrintUnqualified, pprModulePrefix,
-- * Interfaces
......@@ -144,7 +144,7 @@ import Class
import TyCon
import CoAxiom
import DataCon
import PrelNames ( gHC_PRIM, ioTyConName, printName )
import PrelNames ( gHC_PRIM, ioTyConName, printName, mkInteractiveModule )
import Packages hiding ( Version(..) )
import DynFlags
import DriverPhases ( Phase, HscSource(..), isHsBoot, hscSourceString )
......@@ -155,7 +155,7 @@ import Maybes
import Outputable
import BreakArray
import SrcLoc
import Unique
-- import Unique
import UniqFM
import UniqSupply
import FastString
......@@ -168,7 +168,7 @@ import ErrUtils
import Platform
import Util
import Control.Monad ( mplus, guard, liftM, when, ap )
import Control.Monad ( guard, liftM, when, ap )
import Data.Array ( Array, array )
import Data.IORef
import Data.Time
......@@ -218,12 +218,13 @@ runHsc hsc_env (Hsc hsc) = do
printOrThrowWarnings (hsc_dflags hsc_env) w
return a
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
-- A variant of runHsc that switches in the DynFlags from the
-- InteractiveContext before running the Hsc computation.
--
runInteractiveHsc :: HscEnv -> Hsc a -> IO a
runInteractiveHsc hsc_env =
runHsc (hsc_env { hsc_dflags = ic_dflags (hsc_IC hsc_env) })
runInteractiveHsc hsc_env
= runHsc (hsc_env { hsc_dflags = interactive_dflags })
where
interactive_dflags = ic_dflags (hsc_IC hsc_env)
-- -----------------------------------------------------------------------------
-- Source Errors
......@@ -451,6 +452,21 @@ emptyHomePackageTable = emptyUFM
emptyPackageIfaceTable :: PackageIfaceTable
emptyPackageIfaceTable = emptyModuleEnv
pprHPT :: HomePackageTable -> SDoc
-- A bit aribitrary for now
pprHPT hpt
= vcat [ hang (ppr (mi_module (hm_iface hm)))
2 (ppr (md_types (hm_details hm)))
| hm <- eltsUFM hpt ]
lookupHptByModule :: HomePackageTable -> Module -> Maybe HomeModInfo
-- The HPT is indexed by ModuleName, not Module,
-- we must check for a hit on the right Module
lookupHptByModule hpt mod
= case lookupUFM hpt (moduleName mod) of
Just hm | mi_module (hm_iface hm) == mod -> Just hm
_otherwise -> Nothing
-- | Information about modules in the package being compiled
data HomeModInfo
= HomeModInfo {
......@@ -487,15 +503,10 @@ lookupIfaceByModule
-> PackageIfaceTable
-> Module
-> Maybe ModIface
lookupIfaceByModule dflags hpt pit mod
| modulePackageId mod == thisPackage dflags
-- The module comes from the home package, so look first
-- in the HPT. If it's not from the home package it's wrong to look
-- in the HPT, because the HPT is indexed by *ModuleName* not Module
= fmap hm_iface (lookupUFM hpt (moduleName mod))
`mplus` lookupModuleEnv pit mod
| otherwise = lookupModuleEnv pit mod -- Look in PIT only
lookupIfaceByModule _dflags hpt pit mod
= case lookupHptByModule hpt mod of
Just hm -> Just (hm_iface hm)
Nothing -> lookupModuleEnv pit mod
-- If the module does come from the home package, why do we look in the PIT as well?
-- (a) In OneShot mode, even home-package modules accumulate in the PIT
......@@ -1080,6 +1091,110 @@ appendStubC (ForeignStubs h c) c_code = ForeignStubs h (c $$ c_code)
%* *
%************************************************************************
Note [The interactive package]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Type and class declarations at the command prompt are treated as if
they were defined in modules
interactive:Ghci1
interactive:Ghci2
...etc...
with each bunch of declarations using a new module, all sharing a
common package 'interactive' (see Module.interactivePackageId, and
PrelNames.mkInteractiveModule).
This scheme deals well with shadowing. For example:
ghci> data T = A
ghci> data T = B
ghci> :i A
data Ghci1.T = A -- Defined at <interactive>:2:10
Here we must display info about constructor A, but its type T has been
shadowed by the second declaration. But it has a respectable
qualified name (Ghci1.T), and its source location says where it was
defined.
So the main invariant continues to hold, that in any session an original
name M.T only refers to oe unique thing. (In a previous iteration both
the T's above were called :Interactive.T, albeit with different uniques,
which gave rise to all sorts of trouble.)
The details are a bit tricky though:
* The field ic_mod_index counts which Ghci module we've got up to.
It is incremented when extending ic_tythings
* ic_tythings contains only things from the 'interactive' package.
* Module from the 'interactive' package (Ghci1, Ghci2 etc) never go
in the Home Package Table (HPT). When you say :load, that's when
extend the HPT.
* The 'thisPackage' field of DynFlags is *not* set to 'interactive'.
It stays as 'main' (or whatever -package-name says), and is the
package to which :load'ed modules are added to.
* So how do we arrange that declarations at the command prompt get
to be in the 'interactive' package? By setting 'thisPackage' just
before the typecheck/rename step for command-line processing;
see the calls to HscTypes.setInteractivePackage in
HscMain.hscDeclsWithLocation and hscStmtWithLocation.
* The main trickiness is that the type environment (tcg_type_env and
fixity envt (tcg_fix_env) now contains entities from all the
GhciN modules together, rather than just a single module as is usually
the case. So you can't use "nameIsLocalOrFrom" to decide whether
to look in the TcGblEnv vs the HPT/PTE. This is a change, but not
a problem provided you know.
Note [Interactively-bound Ids in GHCi]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The Ids bound by previous Stmts in GHCi are currently
a) GlobalIds
b) with an Internal Name (not External)
c) and a tidied type
(a) They must be GlobalIds (not LocalIds) otherwise when we come to
compile an expression using these ids later, the byte code
generator will consider the occurrences to be free rather than
global.
(b) They start with an Internal Name because a Stmt is a local
construct, so the renamer naturally builds an Internal name for
each of its binders. It would be possible subsequently to give
them an External Name (in a GhciN module) but then we'd have
to substitute it out. So for now they stay Internal.
(c) Their types are tidied. This is important, because :info may ask
to look at them, and :info expects the things it looks up to have
tidy types
However note that TyCons, Classes, and even Ids bound by other top-level
declarations in GHCi (eg foreign import, record selectors) currently get
External Names, with Ghci9 (or 8, or 7, etc) as the module name.
Note [ic_tythings]
~~~~~~~~~~~~~~~~~~
The ic_tythings field contains
* The TyThings declared by the user at the command prompt
(eg Ids, TyCons, Classes)
* The user-visible Ids that arise from such things, which
*don't* come from 'implicitTyThings', notably:
- record selectors
- class ops
The implicitTyThings are readily obtained from the TyThings
but record selectors etc are not
It does *not* contain
* DFunIds (they can be gotten from ic_instances)
* CoAxioms (ditto)
See also Note [Interactively-bound Ids in GHCi]
\begin{code}
-- | Interactive context, recording information about the state of the
-- context in which statements are executed in a GHC session.
......@@ -1089,28 +1204,33 @@ data InteractiveContext
-- ^ The 'DynFlags' used to evaluate interative expressions
-- and statements.
ic_monad :: Name,
-- ^ The monad that GHCi is executing in
ic_mod_index :: Int,
-- ^ Each GHCi stmt or declaration brings some new things into
-- scope. We give them names like interactive:Ghci9.T,
-- where the ic_index is the '9'. The ic_mod_index is
-- incremented whenever we add something to ic_tythings
-- See Note [The interactive package]
ic_imports :: [InteractiveImport],
-- ^ The GHCi context is extended with these imports
ic_imports :: [InteractiveImport],
-- ^ The GHCi top-level scope (ic_rn_gbl_env) is extended with
-- these imports
--
-- This field is only stored here so that the client
-- can retrieve it with GHC.getContext. GHC itself doesn't
-- use it, but does reset it to empty sometimes (such
-- as before a GHC.load). The context is set with GHC.setContext.
ic_tythings :: [TyThing],
-- ^ TyThings defined by the user, in reverse order of
-- definition (ie most recent at the front)
-- See Note [ic_tythings]
ic_rn_gbl_env :: GlobalRdrEnv,
-- ^ The cached 'GlobalRdrEnv', built by
-- 'InteractiveEval.setContext' and updated regularly
-- It contains everything in scope at the command line,
-- including everything in ic_tythings
ic_tythings :: [TyThing],
-- ^ TyThings defined by the user, in reverse order of
-- definition (ie most recent at the front)
-- See Note [ic_tythings]
ic_instances :: ([ClsInst], [FamInst]),
-- ^ All instances and family instances created during
-- this session. These are grabbed en masse after each
......@@ -1122,10 +1242,6 @@ data InteractiveContext
ic_fix_env :: FixityEnv,
-- ^ Fixities declared in let statements
ic_int_print :: Name,
-- ^ The function that is used for printing results
-- of expressions in ghci and -e mode.
ic_default :: Maybe [Type],
-- ^ The current default types, set by a 'default' declaration
......@@ -1134,49 +1250,50 @@ data InteractiveContext
-- ^ The stack of breakpoint contexts