Skip to content

Commit b03ba78

Browse files
committed
Only import inner scope for module we are stopped at.
At the start of a session we import: - exported symbols from Prelude - instances from loaded Debug View modules - instances from debugeee home units modules (we were importing their inner scope before). The latter two are so DebugView orphans are in scope. During an eval, if stopped at a breakpoint, we also import the inner scope of the breakpoint module. Imports made by the user at the REPL are as before: preserved across stops, only for exported symbols.
1 parent 617cc18 commit b03ba78

10 files changed

Lines changed: 155 additions & 66 deletions

File tree

haskell-debugger/GHC/Debugger/Monad.hs

Lines changed: 48 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@ import System.Process.Internals (mkProcessHandle)
4141
import Text.Read (readMaybe)
4242

4343
import GHC
44-
import GHC.Data.FastString
4544
import GHC.Data.StringBuffer
4645
import GHC.Driver.Config.Diagnostic
4746
import GHC.Driver.Config.Logger
@@ -61,9 +60,7 @@ import GHC.Runtime.Interpreter as GHCi
6160
import GHC.Runtime.Loader as GHC
6261
import GHC.Runtime.Context as GHCi
6362
import GHC.Types.Error
64-
import GHC.Types.PkgQual
6563
import GHC.Types.SourceError
66-
import GHC.Types.SourceText
6764
import GHC.Types.Unique.Supply as GHC
6865
import GHC.Unit.Module.Graph
6966
import GHC.Unit.State
@@ -399,8 +396,6 @@ runDebuggerAction l rootDir extraGhcArgs conf loadHomeUnit (Debugger action) = f
399396
GHC.initUniqSupply (GHC.initialUnique df) (GHC.uniqueIncrement df)
400397

401398
loadHomeUnit
402-
-- See Note [Must explicitly expose module graph units]
403-
setExposedInUnit interactiveGhcDebuggerUnitId . graphUnits . hsc_mod_graph =<< getSession
404399

405400
-- Ensure all the home units are built with same Ways and return them.
406401
buildWays <- do
@@ -413,35 +408,42 @@ runDebuggerAction l rootDir extraGhcArgs conf loadHomeUnit (Debugger action) = f
413408
-- in-memory sources.
414409
(hdv_uid, loadedBuiltinModNames) <- findOrLoadHaskellDebuggerView l buildWays
415410

411+
-- See Note [Must explicitly expose module graph units]
412+
setExposedInUnit interactiveGhcDebuggerUnitId . graphUnits . hsc_mod_graph =<< getSession
416413

417414
-- Set interactive context to import all loaded modules
418-
let preludeImp = GHC.IIDecl . GHC.simpleImportDecl $ GHC.mkModuleName "Prelude"
415+
let preludeImp = GHC.simpleImportDecl $ GHC.mkModuleName "Prelude"
416+
417+
hsc_env_new <- getSession
418+
419419
-- dbgView should always be available, either because we manually loaded it
420420
-- or because it's in the transitive closure.
421-
hug <- hsc_HUG <$> getSession
422421
let dbgViewImps
423-
-- If hs-dbg-view is a home-unit, refer to it directly
424-
-- See Note [Do not package-qualify imports for home units]
425-
| memberHugUnitId hdv_uid hug
426-
= map (GHC.IIModule . mkModule (RealUnit (Definite hdv_uid))) loadedBuiltinModNames
427-
-- It's available in an exposed unit in the transitive closure. Resolve it
428-
| otherwise
429-
= map (\mn ->
430-
GHC.IIDecl (GHC.simpleImportDecl mn)
431-
{ ideclPkgQual = RawPkgQual
432-
StringLiteral
433-
{ sl_st = NoSourceText
434-
, sl_fs = mkFastString (unitIdString hdv_uid)
435-
, sl_tc = Nothing
436-
}
437-
}) loadedBuiltinModNames
422+
= map (packageImportDecl hvd_pkgName) loadedBuiltinModNames
423+
where
424+
hvd_pkgName = fromMaybe (error $ "No package name for: " ++ unitIdString hdv_uid) $
425+
lookupUnitPackageQualifier hsc_env_new hdv_uid
438426

439427
mss <- getAllLoadedModules
440428

441-
GHC.setContext
442-
(preludeImp :
443-
dbgViewImps ++
444-
map (GHC.IIModule . GHC.ms_mod) mss)
429+
let
430+
imports
431+
= map GHC.IIDecl $ preludeImp :
432+
[ i { ideclImportList = Just (Exactly, L noAnn []) }
433+
| i <- instancesOnly ]
434+
435+
-- We import (only the instances of) all the home unit
436+
-- modules to bring any orphan DebugView instances in scope.
437+
instancesOnly =
438+
dbgViewImps ++
439+
[ packageImportDecl pkgName (moduleName modl)
440+
| modl <- map GHC.ms_mod mss
441+
, let uid = moduleUnitId modl
442+
, let pkgName = fromMaybe (error $ "No package name for: " ++ unitIdString uid) $ lookupUnitPackageQualifier hsc_env_new uid
443+
]
444+
445+
446+
GHC.setContext imports
445447

446448
-- See Note [External interpreter buffering]
447449
setBufferings <- compileExprRemote """
@@ -465,10 +467,10 @@ runDebuggerAction l rootDir extraGhcArgs conf loadHomeUnit (Debugger action) = f
465467
case conf.externalInterpreterCustomProc of
466468
Left _ -> do
467469
-- We launched the external interpreter ourselves, so forward its output to the logger.
468-
withUnliftGhc $ \ unlift -> do
469-
withAsync (void externalInterpFwdThread) $ \ fwd_thr -> do
470-
liftIO $ link fwd_thr
471-
unlift mainGhcThread
470+
withUnliftGhc $ \ unlift -> annotateCallStackIO $ do
471+
withAsync (annotateCallStackIO $ void externalInterpFwdThread) $ \ fwd_thr -> do
472+
liftIO $ annotateCallStackIO $ link fwd_thr
473+
annotateCallStackIO $ unlift mainGhcThread
472474
Right _ ->
473475
-- Ext interp is running in user terminal, no need to forward output to logger
474476
mainGhcThread
@@ -577,27 +579,30 @@ An alternative, closer to what ghci does, would be to copy the `packageFlags`
577579
from the debuggee units, however doing so doesn't take care of fixing a unitId
578580
for dependencies of dependencies.
579581
580-
Note [Do not package-qualify imports for home units]
582+
Note [Package Qualified Imports]
581583
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
582-
A package-qualified module import will be looked up directly in the exposed
583-
packages, IGNORING the home units modules.
584-
585-
This can lead to two scenarios:
584+
Package qualified imports have a quirky behaviour: the source string qualifier gets converted into a `PkgQual` on the way, which can be one of these two:
585+
- `ThisPkg unitId` interpreted as a home unit
586+
- `OtherPkg unitId` interpreted as an external package
586587
587-
1) a package-import of a loaded unit fails, because that unit, despite being
588-
loaded, is not installed
588+
We get each under these conditions:
589+
- ThisPkg
590+
- qualifier is the literal "this" or the **package name** of the active home unit or any of its home unit dependencies.
591+
- OtherPkg
592+
- qualifier is the **package name** of a non-hidden external unit which exports the module we are importing.
593+
- None of the above apply, and the qualifier itself is interpreted as a `UnitId`.
594+
When choosing between multiple units that satisfy a condition, the first found is committed to.
589595
590-
2) a package-import of a loaded unit succeeds, because a unit with the same
591-
name (but not necessarily the same unit-id!), is installed.
596+
The upshot is that `UnitId`s normally only work as qualifiers for external packages, unless you change the package names of home units as described in Note [ Ambiguous Package Qualified Imports Workaround ].
592597
593-
The second case can result in subtly wrong interactive sessions, where the
598+
At the same time doing a PackageImport with a plain PackageName can succeed while resolving to an installed unit while we meant one of the loaded units, resulting in subtly wrong interactive sessions, where the
594599
package-qualified imported module shadows the loaded module. Perhaps GHC could
595600
warn about this. Cabal-repl and ghci also suffer from this subtle interaction.
596601
597602
In light of this, when the debugger imports the `haskell-debugger-view` modules,
598603
it is imperative that if the `haskell-debugger-view` unit is in the home units
599604
(e.g. if `haskell-debugger-view` is listed in the cabal.project, like it is in
600-
the debugger tree), we do not use a package-qualified import.
605+
the debugger tree), we rely on Note [ Ambiguous Package Qualified Imports Workaround ].
601606
602607
On the other hand, if the `haskell-debugger-view` package is not in the
603608
home-units, we *should* package-qualify it to make sure we reference the right
@@ -623,10 +628,6 @@ cleanupInterp = do
623628
sendMessage i Shutdown
624629
pure InterpPending
625630

626-
-- | WARNING: callback is not to be used from other threads.
627-
withUnliftGhc :: ((Ghc b -> IO b) -> IO a) -> Ghc a
628-
withUnliftGhc k = reifyGhc $ \ s -> k (flip reflectGhc s)
629-
630631
annotateDebuggerStackString :: String -> Debugger a -> Debugger a
631632
annotateDebuggerStackString s (Debugger m) = Debugger $ do
632633
r <- ReaderT $ \val -> do
@@ -857,10 +858,9 @@ doLoad if_cache how_much mg = do
857858

858859

859860
loadInMemoryModules ::
860-
GhcMonad m
861-
=> LogAction IO DebuggerLog
861+
LogAction IO DebuggerLog
862862
-> UnitId
863-
-> [(ModuleName,StringBuffer)] -> m [SuccessFlag]
863+
-> [(ModuleName,StringBuffer)] -> Ghc [SuccessFlag]
864864
loadInMemoryModules l uid ts = do
865865
old_targets <- GHC.getTargets
866866
tgts <- forM ts $ \(modName,modContents) ->

haskell-debugger/GHC/Debugger/Run.hs

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ addImport s = handleError $ do
211211

212212
-- | Evaluate expression. Includes context of breakpoint if stopped at one (the current interactive context).
213213
doEval :: String -> Debugger EvalResult
214-
doEval expr = withCurrentBreakExtensions $ do
214+
doEval expr = withCurrentBreakEnv $ do
215215
excr <- (Right <$> exec expr GHC.execOptions) `catch` \(e::SomeException) -> pure (Left (displayException e))
216216
case excr of
217217
Left err -> pure $ EvalAbortedWith err
@@ -250,20 +250,23 @@ continueToCompletion = do
250250
GHC.ExecBreak{} -> continueToCompletion
251251
GHC.ExecComplete{} -> return execr
252252

253-
-- | @withCurrentBreakExtensions m@ executes @m@ with the language and language
253+
-- | @withCurrentBreakEnv m@ executes @m@ with the imports, language, and language
254254
-- extensions of the current breakpoint source module.
255255
--
256256
-- If we are not stopped at a breakpoint @m@ is executed with no change.
257-
withCurrentBreakExtensions :: Debugger a -> Debugger a
258-
withCurrentBreakExtensions m = do
257+
withCurrentBreakEnv :: Debugger a -> Debugger a
258+
withCurrentBreakEnv m = do
259259
mmodl <- getCurrentBreakModule
260260
case mmodl of
261261
Nothing -> m
262262
Just breakModule -> do
263263
ic_dyn_flags <- getInteractiveDebuggerDynFlags
264264
break_dyn_flags <- ms_hspp_opts <$> GHC.getModSummary breakModule
265+
old_context <- GHC.getContext
265266
setInteractiveDebuggerDynFlags $ adjustFlags ic_dyn_flags break_dyn_flags
267+
GHC.setContext (IIModule breakModule : old_context)
266268
x <- m
269+
GHC.setContext old_context
267270
setInteractiveDebuggerDynFlags ic_dyn_flags
268271
return x
269272
where

haskell-debugger/GHC/Debugger/Session.hs

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,19 @@ module GHC.Debugger.Session (
3333
setExposedInUnit,
3434
graphUnits,
3535
compileModuleWithDepsInHpt,
36+
home_unit_dflags,
37+
packageImportDecl,
38+
withUnliftGhc,
39+
annotateCallStackGhc,
40+
lookupUnitPackageQualifier,
3641
)
3742
where
3843

3944
#if MIN_VERSION_ghc(9,14,2)
4045
import Data.Function ((&))
4146
#endif
47+
import Control.Applicative ((<|>))
48+
import Control.Exception (assert)
4249
import Control.Monad
4350
import Control.Monad.IO.Class
4451
import qualified Crypto.Hash.SHA1 as H
@@ -75,7 +82,7 @@ import qualified GHC.Unit.Home.Graph as HUG
7582
import qualified Data.Set as Set
7683
import Data.Maybe
7784
import GHC.Types.Target (InputFileBuffer)
78-
import GHC (SingleStep, ExecResult, ModSummary (ms_hspp_opts))
85+
import GHC (SingleStep, ExecResult, ModSummary (ms_hspp_opts), ideclPkgQual, ImportDecl, GhcPs)
7986
import Data.Set (Set)
8087
import qualified GHC.Unit as GHC
8188
import GHC.Unit.Module.Graph (mg_mss, ModuleGraphNode (..), mnKey)
@@ -89,7 +96,10 @@ import GHC.Driver.Pipeline (compileOne)
8996
import qualified GHC.Unit.Home.ModInfo as GHC
9097
import GHC.Utils.TmpFs
9198
import Data.Foldable (for_)
92-
import GHC.Plugins (SourceError, try)
99+
import GHC.Plugins (SourceError, try, RawPkgQual (..), HasCallStack, FastString, mkFastString, lookupUnitId)
100+
import GHC.Types.SourceText (StringLiteral(..), SourceText (..))
101+
import GHC.Stack.Annotation
102+
import GHC.Stack (callStack)
93103

94104
-- | Throws if package flags are unsatisfiable
95105
parseHomeUnitArguments :: GhcMonad m
@@ -161,13 +171,24 @@ setupHomeUnitGraph flagsAndTargets = do
161171
-- | Set up the 'HomeUnitGraph' with empty 'HomeUnitEnv's.
162172
-- The first 'DynFlags' are the 'DynFlags' for the interactive session.
163173
createHomeUnitGraph :: GHC.Logger -> [DynFlags] -> IO HomeUnitGraph
164-
createHomeUnitGraph logger unitDflags = do
174+
createHomeUnitGraph logger unitDflags0 = do
175+
-- See Note [ Ambiguous Package Qualified Imports Workaround ]
176+
let unitDflags = fixFlagsForIIDecl unitDflags0
165177
let home_units = Set.fromList $ map homeUnitId_ unitDflags
178+
166179
unitEnvList <- flip traverse unitDflags $ \ dflags -> do
180+
let uid = homeUnitId_ dflags
167181
hue <- setupNewHomeUnitEnv logger dflags Nothing home_units
168-
pure (homeUnitId_ dflags, hue)
182+
assert (homeUnitId_ (homeUnitEnv_dflags hue) == uid) $
183+
pure (uid, hue)
169184

170185
pure $ unitEnv_new (Map.fromList unitEnvList)
186+
where
187+
-- | Makes package names of home units unique and removes hidden modules.
188+
fixFlagsForIIDecl [df] | Just{} <- thisPackageName df = [df {hiddenModules = Set.empty}]
189+
-- TODO #288: pick more user-friendly names.
190+
fixFlagsForIIDecl dfss = map (\ dflags -> dflags { thisPackageName = Just (unitIdString (homeUnitId_ dflags))
191+
, hiddenModules = Set.empty}) dfss
171192

172193
setupNewHomeUnitEnv :: GHC.Logger -> DynFlags -> Maybe [GHC.UnitDatabase UnitId] -> Set UnitId -> IO HomeUnitEnv
173194
setupNewHomeUnitEnv logger dflags cached_dbs other_home_units = do
@@ -225,6 +246,13 @@ graphUnits mod_graph = L.nubOrd .
225246
InstantiationNode uid _ -> Just uid
226247
LinkNode _ _ -> Nothing
227248

249+
-- | WARNING: callback is not to be used from other threads.
250+
withUnliftGhc :: ((Ghc b -> IO b) -> IO a) -> Ghc a
251+
withUnliftGhc k = reifyGhc $ \ s -> k (flip reflectGhc s)
252+
253+
annotateCallStackGhc :: HasCallStack => Ghc a -> Ghc a
254+
annotateCallStackGhc m = let x = callStack in withUnliftGhc $ \k -> annotateStackShowIO x $ k m
255+
228256
-- | Rebuilds the UnitState of the unit, exposing the given packages.
229257
--
230258
-- Takes care of updating hsc_dflags, ue_platform, and ue_namever if this is the ue_currentUnit.
@@ -280,7 +308,7 @@ setupMultiHomeUnitGhcSession
280308
-> HscEnv -- ^ An empty HscEnv that we can use the setup the session.
281309
-> [(DynFlags, [GHC.Target])] -- ^ New components to be loaded. Expected to be non-empty.
282310
-> IO (HscEnv, [TargetDetails])
283-
setupMultiHomeUnitGhcSession exts hsc_env cis = do
311+
setupMultiHomeUnitGhcSession exts hsc_env cis = annotateCallStackIO $ do
284312
let dfs = map fst cis
285313

286314
hscEnv' <- initHomeUnitEnv dfs hsc_env
@@ -353,6 +381,31 @@ fromTargetId _ _ unitId (GHC.TargetFile f _) ctts = do
353381
| otherwise = (f ++ "-boot")
354382
return [TargetDetails (TargetFile f) [f, other] unitId ctts]
355383

384+
{-
385+
Note [ Ambiguous Package Qualified Imports Workaround ]
386+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
387+
388+
Source level package qualified imports `import "foo" A` interpret "foo" as a package name.
389+
390+
When one manually builds a `RawPkgQual` for an `ImportDecl` one can get away with using a unit-id, but only for external (i.e. not home) units.
391+
That it works does not seem entirely intended (see quoted snippet below), the code is in `renamePkgQual`: If a package qualifier is not found among packages it's looked up as an external unit. This is already in the code path for `OtherPkg` though, which is why Home Units are excluded.
392+
```
393+
| otherwise
394+
-> OtherPkg (UnitId pkg_fs)
395+
-- not really correct as pkg_fs is unlikely to be a valid unit-id but
396+
-- we will report the failure later...
397+
```
398+
399+
Home units will only be found if the qualifier matches their dflags' `thisPackageName`. However that's bugged because the lookup doesn't bother considering there can be multiple units in the same package (library, sublibraries and exe units), and just picks the first found, leading to an import error if e.g. the library unit is picked but the module was in the exe one.
400+
Related GHC issue: https://gitlab.haskell.org/ghc/ghc/-/issues/24227
401+
402+
Turns out that the package name of a home unit is pretty meaningless though, so we can update the dflags to replace it with anything that's actually unique so we can dodge the bug.
403+
404+
Another stumbling block is that the `IIDecl` mode of an `InteractiveImport` does not allow importing hidden modules, but again for home units we can alter the DynFlags so all modules are exposed.
405+
406+
See issue #288 for what can we do for users at the repl.
407+
-}
408+
356409
-- ----------------------------------------------------------------------------
357410
-- GHC Utils that should likely be exposed by GHC
358411
-- ----------------------------------------------------------------------------
@@ -363,6 +416,33 @@ mkSimpleTarget df fp = GHC.Target (GHC.TargetFile fp Nothing) True (homeUnitId_
363416
hscSetUnitEnv :: UnitEnv -> HscEnv -> HscEnv
364417
hscSetUnitEnv ue env = env { hsc_unit_env = ue }
365418

419+
home_unit_dflags :: HscEnv -> UnitId -> Maybe DynFlags
420+
home_unit_dflags hsc_env uid
421+
= fmap homeUnitEnv_dflags
422+
. HUG.lookupHugUnitId uid . ue_home_unit_graph
423+
. hsc_unit_env
424+
$ hsc_env
425+
426+
-- | See Note [Package Qualified Imports] for why this is sometimes a @PackageName@ and sometimes a @UnitId@.
427+
newtype PackageQualifier = PackageQualifier FastString
428+
429+
lookupUnitPackageQualifier :: HscEnv -> UnitId -> Maybe PackageQualifier
430+
lookupUnitPackageQualifier env uid = home_unit_name <|> ext_unit_name
431+
where
432+
-- See Note [Package Qualified Imports]
433+
home_unit_name = PackageQualifier . mkFastString <$> (thisPackageName =<< home_unit_dflags env uid)
434+
ext_unit_name = const (PackageQualifier (unitIdFS uid)) <$> lookupUnitId (hsc_units env) uid
435+
436+
packageImportDecl :: PackageQualifier -> ModuleName -> ImportDecl GhcPs
437+
packageImportDecl (PackageQualifier pkgName) mn =
438+
(GHC.simpleImportDecl $ mn)
439+
{ ideclPkgQual = RawPkgQual
440+
StringLiteral
441+
{ sl_st = NoSourceText
442+
, sl_fs = pkgName
443+
, sl_tc = Nothing
444+
}
445+
}
366446
-- ----------------------------------------------------------------------------
367447
-- Session cache directory
368448
-- ----------------------------------------------------------------------------
@@ -417,9 +497,9 @@ getTargetFileSummary hsc_env target
417497
home_unit = ue_unitHomeUnit uid (hsc_unit_env hsc_env)
418498
dflags = homeUnitEnv_dflags (ue_findHomeUnitEnv uid (hsc_unit_env hsc_env))
419499

420-
compileModuleWithDepsInHpt :: GhcMonad m =>
500+
compileModuleWithDepsInHpt ::
421501
GHC.Target ->
422-
m (Maybe SourceError)
502+
Ghc (Maybe SourceError)
423503
compileModuleWithDepsInHpt target@GHC.Target{targetUnitId = uid} = do
424504
hsc_env0 <- getSession
425505
let !old_active = hscActiveUnitId hsc_env0

haskell-debugger/GHC/Debugger/Session/Builtin.hs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ addInMemoryHsDebuggerViewUnit base_uids initialDynFlags = do
107107
, unitId /= rtsUnitId
108108
, unitId /= ghcInternalUnitId
109109
]
110+
, thisPackageName = Just "haskell-debugger-view"
110111
}
111112
& setGeneralFlag' Opt_HideAllPackages
112113
hsc_env <- getSession

0 commit comments

Comments
 (0)