PageRenderTime 73ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/compiler/main/InteractiveEval.hs

https://bitbucket.org/carter/ghc
Haskell | 1042 lines | 743 code | 132 blank | 167 comment | 18 complexity | 60d5ad244884dcd7ba2954376bb3c6cc MD5 | raw file
  1. -- -----------------------------------------------------------------------------
  2. --
  3. -- (c) The University of Glasgow, 2005-2007
  4. --
  5. -- Running statements interactively
  6. --
  7. -- -----------------------------------------------------------------------------
  8. module InteractiveEval (
  9. #ifdef GHCI
  10. RunResult(..), Status(..), Resume(..), History(..),
  11. runStmt, runStmtWithLocation, runDecls, runDeclsWithLocation,
  12. parseImportDecl, SingleStep(..),
  13. resume,
  14. abandon, abandonAll,
  15. getResumeContext,
  16. getHistorySpan,
  17. getModBreaks,
  18. getHistoryModule,
  19. back, forward,
  20. setContext, getContext,
  21. availsToGlobalRdrEnv,
  22. getNamesInScope,
  23. getRdrNamesInScope,
  24. moduleIsInterpreted,
  25. getInfo,
  26. exprType,
  27. typeKind,
  28. parseName,
  29. showModule,
  30. isModuleInterpreted,
  31. compileExpr, dynCompileExpr,
  32. Term(..), obtainTermFromId, obtainTermFromVal, reconstructType
  33. #endif
  34. ) where
  35. #ifdef GHCI
  36. #include "HsVersions.h"
  37. import GhcMonad
  38. import HscMain
  39. import HsSyn
  40. import HscTypes
  41. import InstEnv
  42. import TyCon
  43. import Type hiding( typeKind )
  44. import TcType hiding( typeKind )
  45. import Var
  46. import Id
  47. import Name hiding ( varName )
  48. import NameSet
  49. import Avail
  50. import RdrName
  51. import VarSet
  52. import VarEnv
  53. import ByteCodeInstr
  54. import Linker
  55. import DynFlags
  56. import Unique
  57. import UniqSupply
  58. import Module
  59. import Panic
  60. import UniqFM
  61. import Maybes
  62. import ErrUtils
  63. import SrcLoc
  64. import BreakArray
  65. import RtClosureInspect
  66. import Outputable
  67. import FastString
  68. import MonadUtils
  69. import System.Directory
  70. import Data.Dynamic
  71. import Data.Either
  72. import Data.List (find)
  73. import Control.Monad
  74. import Foreign.Safe
  75. import Foreign.C
  76. import GHC.Exts
  77. import Data.Array
  78. import Exception
  79. import Control.Concurrent
  80. import System.IO.Unsafe
  81. -- -----------------------------------------------------------------------------
  82. -- running a statement interactively
  83. data RunResult
  84. = RunOk [Name] -- ^ names bound by this evaluation
  85. | RunException SomeException -- ^ statement raised an exception
  86. | RunBreak ThreadId [Name] (Maybe BreakInfo)
  87. data Status
  88. = Break Bool HValue BreakInfo ThreadId
  89. -- ^ the computation hit a breakpoint (Bool <=> was an exception)
  90. | Complete (Either SomeException [HValue])
  91. -- ^ the computation completed with either an exception or a value
  92. data Resume
  93. = Resume {
  94. resumeStmt :: String, -- the original statement
  95. resumeThreadId :: ThreadId, -- thread running the computation
  96. resumeBreakMVar :: MVar (),
  97. resumeStatMVar :: MVar Status,
  98. resumeBindings :: ([TyThing], GlobalRdrEnv),
  99. resumeFinalIds :: [Id], -- [Id] to bind on completion
  100. resumeApStack :: HValue, -- The object from which we can get
  101. -- value of the free variables.
  102. resumeBreakInfo :: Maybe BreakInfo,
  103. -- the breakpoint we stopped at
  104. -- (Nothing <=> exception)
  105. resumeSpan :: SrcSpan, -- just a cache, otherwise it's a pain
  106. -- to fetch the ModDetails & ModBreaks
  107. -- to get this.
  108. resumeHistory :: [History],
  109. resumeHistoryIx :: Int -- 0 <==> at the top of the history
  110. }
  111. getResumeContext :: GhcMonad m => m [Resume]
  112. getResumeContext = withSession (return . ic_resume . hsc_IC)
  113. data SingleStep
  114. = RunToCompletion
  115. | SingleStep
  116. | RunAndLogSteps
  117. isStep :: SingleStep -> Bool
  118. isStep RunToCompletion = False
  119. isStep _ = True
  120. data History
  121. = History {
  122. historyApStack :: HValue,
  123. historyBreakInfo :: BreakInfo,
  124. historyEnclosingDecls :: [String] -- declarations enclosing the breakpoint
  125. }
  126. mkHistory :: HscEnv -> HValue -> BreakInfo -> History
  127. mkHistory hsc_env hval bi = let
  128. decls = findEnclosingDecls hsc_env bi
  129. in History hval bi decls
  130. getHistoryModule :: History -> Module
  131. getHistoryModule = breakInfo_module . historyBreakInfo
  132. getHistorySpan :: HscEnv -> History -> SrcSpan
  133. getHistorySpan hsc_env hist =
  134. let inf = historyBreakInfo hist
  135. num = breakInfo_number inf
  136. in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
  137. Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
  138. _ -> panic "getHistorySpan"
  139. getModBreaks :: HomeModInfo -> ModBreaks
  140. getModBreaks hmi
  141. | Just linkable <- hm_linkable hmi,
  142. [BCOs _ modBreaks] <- linkableUnlinked linkable
  143. = modBreaks
  144. | otherwise
  145. = emptyModBreaks -- probably object code
  146. {- | Finds the enclosing top level function name -}
  147. -- ToDo: a better way to do this would be to keep hold of the decl_path computed
  148. -- by the coverage pass, which gives the list of lexically-enclosing bindings
  149. -- for each tick.
  150. findEnclosingDecls :: HscEnv -> BreakInfo -> [String]
  151. findEnclosingDecls hsc_env inf =
  152. let hmi = expectJust "findEnclosingDecls" $
  153. lookupUFM (hsc_HPT hsc_env) (moduleName $ breakInfo_module inf)
  154. mb = getModBreaks hmi
  155. in modBreaks_decls mb ! breakInfo_number inf
  156. -- | Update fixity environment in the current interactive context.
  157. updateFixityEnv :: GhcMonad m => FixityEnv -> m ()
  158. updateFixityEnv fix_env = do
  159. hsc_env <- getSession
  160. let ic = hsc_IC hsc_env
  161. setSession $ hsc_env { hsc_IC = ic { ic_fix_env = fix_env } }
  162. -- | Run a statement in the current interactive context. Statement
  163. -- may bind multple values.
  164. runStmt :: GhcMonad m => String -> SingleStep -> m RunResult
  165. runStmt = runStmtWithLocation "<interactive>" 1
  166. -- | Run a statement in the current interactive context. Passing debug information
  167. -- Statement may bind multple values.
  168. runStmtWithLocation :: GhcMonad m => String -> Int ->
  169. String -> SingleStep -> m RunResult
  170. runStmtWithLocation source linenumber expr step =
  171. do
  172. hsc_env <- getSession
  173. breakMVar <- liftIO $ newEmptyMVar -- wait on this when we hit a breakpoint
  174. statusMVar <- liftIO $ newEmptyMVar -- wait on this when a computation is running
  175. -- Turn off -fwarn-unused-bindings when running a statement, to hide
  176. -- warnings about the implicit bindings we introduce.
  177. let ic = hsc_IC hsc_env -- use the interactive dflags
  178. idflags' = ic_dflags ic `wopt_unset` Opt_WarnUnusedBinds
  179. hsc_env' = hsc_env{ hsc_IC = ic{ ic_dflags = idflags' } }
  180. -- compile to value (IO [HValue]), don't run
  181. r <- liftIO $ hscStmtWithLocation hsc_env' expr source linenumber
  182. case r of
  183. -- empty statement / comment
  184. Nothing -> return (RunOk [])
  185. Just (tyThings, hval, fix_env) -> do
  186. updateFixityEnv fix_env
  187. status <-
  188. withVirtualCWD $
  189. withBreakAction (isStep step) idflags' breakMVar statusMVar $ do
  190. liftIO $ sandboxIO idflags' statusMVar hval
  191. let ic = hsc_IC hsc_env
  192. bindings = (ic_tythings ic, ic_rn_gbl_env ic)
  193. case step of
  194. RunAndLogSteps ->
  195. traceRunStatus expr bindings tyThings
  196. breakMVar statusMVar status emptyHistory
  197. _other ->
  198. handleRunStatus expr bindings tyThings
  199. breakMVar statusMVar status emptyHistory
  200. runDecls :: GhcMonad m => String -> m [Name]
  201. runDecls = runDeclsWithLocation "<interactive>" 1
  202. runDeclsWithLocation :: GhcMonad m => String -> Int -> String -> m [Name]
  203. runDeclsWithLocation source linenumber expr =
  204. do
  205. hsc_env <- getSession
  206. (tyThings, ic) <- liftIO $ hscDeclsWithLocation hsc_env expr source linenumber
  207. setSession $ hsc_env { hsc_IC = ic }
  208. hsc_env <- getSession
  209. hsc_env' <- liftIO $ rttiEnvironment hsc_env
  210. modifySession (\_ -> hsc_env')
  211. return (map getName tyThings)
  212. withVirtualCWD :: GhcMonad m => m a -> m a
  213. withVirtualCWD m = do
  214. hsc_env <- getSession
  215. let ic = hsc_IC hsc_env
  216. let set_cwd = do
  217. dir <- liftIO $ getCurrentDirectory
  218. case ic_cwd ic of
  219. Just dir -> liftIO $ setCurrentDirectory dir
  220. Nothing -> return ()
  221. return dir
  222. reset_cwd orig_dir = do
  223. virt_dir <- liftIO $ getCurrentDirectory
  224. hsc_env <- getSession
  225. let old_IC = hsc_IC hsc_env
  226. setSession hsc_env{ hsc_IC = old_IC{ ic_cwd = Just virt_dir } }
  227. liftIO $ setCurrentDirectory orig_dir
  228. gbracket set_cwd reset_cwd $ \_ -> m
  229. parseImportDecl :: GhcMonad m => String -> m (ImportDecl RdrName)
  230. parseImportDecl expr = withSession $ \hsc_env -> liftIO $ hscImport hsc_env expr
  231. emptyHistory :: BoundedList History
  232. emptyHistory = nilBL 50 -- keep a log of length 50
  233. handleRunStatus :: GhcMonad m =>
  234. String-> ([TyThing],GlobalRdrEnv) -> [Id]
  235. -> MVar () -> MVar Status -> Status -> BoundedList History
  236. -> m RunResult
  237. handleRunStatus expr bindings final_ids breakMVar statusMVar status
  238. history =
  239. case status of
  240. -- did we hit a breakpoint or did we complete?
  241. (Break is_exception apStack info tid) -> do
  242. hsc_env <- getSession
  243. let mb_info | is_exception = Nothing
  244. | otherwise = Just info
  245. (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env apStack
  246. mb_info
  247. let
  248. resume = Resume { resumeStmt = expr, resumeThreadId = tid
  249. , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
  250. , resumeBindings = bindings, resumeFinalIds = final_ids
  251. , resumeApStack = apStack, resumeBreakInfo = mb_info
  252. , resumeSpan = span, resumeHistory = toListBL history
  253. , resumeHistoryIx = 0 }
  254. hsc_env2 = pushResume hsc_env1 resume
  255. --
  256. modifySession (\_ -> hsc_env2)
  257. return (RunBreak tid names mb_info)
  258. (Complete either_hvals) ->
  259. case either_hvals of
  260. Left e -> return (RunException e)
  261. Right hvals -> do
  262. hsc_env <- getSession
  263. let final_ic = extendInteractiveContext (hsc_IC hsc_env)
  264. (map AnId final_ids)
  265. final_names = map getName final_ids
  266. liftIO $ Linker.extendLinkEnv (zip final_names hvals)
  267. hsc_env' <- liftIO $ rttiEnvironment hsc_env{hsc_IC=final_ic}
  268. modifySession (\_ -> hsc_env')
  269. return (RunOk final_names)
  270. traceRunStatus :: GhcMonad m =>
  271. String -> ([TyThing], GlobalRdrEnv) -> [Id]
  272. -> MVar () -> MVar Status -> Status -> BoundedList History
  273. -> m RunResult
  274. traceRunStatus expr bindings final_ids
  275. breakMVar statusMVar status history = do
  276. hsc_env <- getSession
  277. case status of
  278. -- when tracing, if we hit a breakpoint that is not explicitly
  279. -- enabled, then we just log the event in the history and continue.
  280. (Break is_exception apStack info tid) | not is_exception -> do
  281. b <- liftIO $ isBreakEnabled hsc_env info
  282. if b
  283. then handle_normally
  284. else do
  285. let history' = mkHistory hsc_env apStack info `consBL` history
  286. -- probably better make history strict here, otherwise
  287. -- our BoundedList will be pointless.
  288. _ <- liftIO $ evaluate history'
  289. status <-
  290. withBreakAction True (hsc_dflags hsc_env)
  291. breakMVar statusMVar $ do
  292. liftIO $ withInterruptsSentTo tid $ do
  293. putMVar breakMVar () -- awaken the stopped thread
  294. takeMVar statusMVar -- and wait for the result
  295. traceRunStatus expr bindings final_ids
  296. breakMVar statusMVar status history'
  297. _other ->
  298. handle_normally
  299. where
  300. handle_normally = handleRunStatus expr bindings final_ids
  301. breakMVar statusMVar status history
  302. isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
  303. isBreakEnabled hsc_env inf =
  304. case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
  305. Just hmi -> do
  306. w <- getBreak (hsc_dflags hsc_env)
  307. (modBreaks_flags (getModBreaks hmi))
  308. (breakInfo_number inf)
  309. case w of Just n -> return (n /= 0); _other -> return False
  310. _ ->
  311. return False
  312. foreign import ccall "&rts_stop_next_breakpoint" stepFlag :: Ptr CInt
  313. foreign import ccall "&rts_stop_on_exception" exceptionFlag :: Ptr CInt
  314. setStepFlag :: IO ()
  315. setStepFlag = poke stepFlag 1
  316. resetStepFlag :: IO ()
  317. resetStepFlag = poke stepFlag 0
  318. -- this points to the IO action that is executed when a breakpoint is hit
  319. foreign import ccall "&rts_breakpoint_io_action"
  320. breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ()))
  321. -- When running a computation, we redirect ^C exceptions to the running
  322. -- thread. ToDo: we might want a way to continue even if the target
  323. -- thread doesn't die when it receives the exception... "this thread
  324. -- is not responding".
  325. --
  326. -- Careful here: there may be ^C exceptions flying around, so we start the new
  327. -- thread blocked (forkIO inherits mask from the parent, #1048), and unblock
  328. -- only while we execute the user's code. We can't afford to lose the final
  329. -- putMVar, otherwise deadlock ensues. (#1583, #1922, #1946)
  330. sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
  331. sandboxIO dflags statusMVar thing =
  332. mask $ \restore -> -- fork starts blocked
  333. let runIt = liftM Complete $ try (restore $ rethrow dflags thing)
  334. in if dopt Opt_GhciSandbox dflags
  335. then do tid <- forkIO $ do res <- runIt
  336. putMVar statusMVar res -- empty: can't block
  337. withInterruptsSentTo tid $ takeMVar statusMVar
  338. else -- GLUT on OS X needs to run on the main thread. If you
  339. -- try to use it from another thread then you just get a
  340. -- white rectangle rendered. For this, or anything else
  341. -- with such restrictions, you can turn the GHCi sandbox off
  342. -- and things will be run in the main thread.
  343. runIt
  344. -- We want to turn ^C into a break when -fbreak-on-exception is on,
  345. -- but it's an async exception and we only break for sync exceptions.
  346. -- Idea: if we catch and re-throw it, then the re-throw will trigger
  347. -- a break. Great - but we don't want to re-throw all exceptions, because
  348. -- then we'll get a double break for ordinary sync exceptions (you'd have
  349. -- to :continue twice, which looks strange). So if the exception is
  350. -- not "Interrupted", we unset the exception flag before throwing.
  351. --
  352. rethrow :: DynFlags -> IO a -> IO a
  353. rethrow dflags io = Exception.catch io $ \se -> do
  354. -- If -fbreak-on-error, we break unconditionally,
  355. -- but with care of not breaking twice
  356. if dopt Opt_BreakOnError dflags &&
  357. not (dopt Opt_BreakOnException dflags)
  358. then poke exceptionFlag 1
  359. else case fromException se of
  360. -- If it is a "UserInterrupt" exception, we allow
  361. -- a possible break by way of -fbreak-on-exception
  362. Just UserInterrupt -> return ()
  363. -- In any other case, we don't want to break
  364. _ -> poke exceptionFlag 0
  365. Exception.throwIO se
  366. withInterruptsSentTo :: ThreadId -> IO r -> IO r
  367. withInterruptsSentTo thread get_result = do
  368. bracket (pushInterruptTargetThread thread)
  369. (\_ -> popInterruptTargetThread)
  370. (\_ -> get_result)
  371. -- This function sets up the interpreter for catching breakpoints, and
  372. -- resets everything when the computation has stopped running. This
  373. -- is a not-very-good way to ensure that only the interactive
  374. -- evaluation should generate breakpoints.
  375. withBreakAction :: (ExceptionMonad m, MonadIO m) =>
  376. Bool -> DynFlags -> MVar () -> MVar Status -> m a -> m a
  377. withBreakAction step dflags breakMVar statusMVar act
  378. = gbracket (liftIO setBreakAction) (liftIO . resetBreakAction) (\_ -> act)
  379. where
  380. setBreakAction = do
  381. stablePtr <- newStablePtr onBreak
  382. poke breakPointIOAction stablePtr
  383. when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
  384. when step $ setStepFlag
  385. return stablePtr
  386. -- Breaking on exceptions is not enabled by default, since it
  387. -- might be a bit surprising. The exception flag is turned off
  388. -- as soon as it is hit, or in resetBreakAction below.
  389. onBreak is_exception info apStack = do
  390. tid <- myThreadId
  391. putMVar statusMVar (Break is_exception apStack info tid)
  392. takeMVar breakMVar
  393. resetBreakAction stablePtr = do
  394. poke breakPointIOAction noBreakStablePtr
  395. poke exceptionFlag 0
  396. resetStepFlag
  397. freeStablePtr stablePtr
  398. noBreakStablePtr :: StablePtr (Bool -> BreakInfo -> HValue -> IO ())
  399. noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction
  400. noBreakAction :: Bool -> BreakInfo -> HValue -> IO ()
  401. noBreakAction False _ _ = putStrLn "*** Ignoring breakpoint"
  402. noBreakAction True _ _ = return () -- exception: just continue
  403. resume :: GhcMonad m => (SrcSpan->Bool) -> SingleStep -> m RunResult
  404. resume canLogSpan step
  405. = do
  406. hsc_env <- getSession
  407. let ic = hsc_IC hsc_env
  408. resume = ic_resume ic
  409. case resume of
  410. [] -> ghcError (ProgramError "not stopped at a breakpoint")
  411. (r:rs) -> do
  412. -- unbind the temporary locals by restoring the TypeEnv from
  413. -- before the breakpoint, and drop this Resume from the
  414. -- InteractiveContext.
  415. let (resume_tmp_te,resume_rdr_env) = resumeBindings r
  416. ic' = ic { ic_tythings = resume_tmp_te,
  417. ic_rn_gbl_env = resume_rdr_env,
  418. ic_resume = rs }
  419. modifySession (\_ -> hsc_env{ hsc_IC = ic' })
  420. -- remove any bindings created since the breakpoint from the
  421. -- linker's environment
  422. let new_names = map getName (filter (`notElem` resume_tmp_te)
  423. (ic_tythings ic))
  424. liftIO $ Linker.deleteFromLinkEnv new_names
  425. when (isStep step) $ liftIO setStepFlag
  426. case r of
  427. Resume { resumeStmt = expr, resumeThreadId = tid
  428. , resumeBreakMVar = breakMVar, resumeStatMVar = statusMVar
  429. , resumeBindings = bindings, resumeFinalIds = final_ids
  430. , resumeApStack = apStack, resumeBreakInfo = info, resumeSpan = span
  431. , resumeHistory = hist } -> do
  432. withVirtualCWD $ do
  433. withBreakAction (isStep step) (hsc_dflags hsc_env)
  434. breakMVar statusMVar $ do
  435. status <- liftIO $ withInterruptsSentTo tid $ do
  436. putMVar breakMVar ()
  437. -- this awakens the stopped thread...
  438. takeMVar statusMVar
  439. -- and wait for the result
  440. let prevHistoryLst = fromListBL 50 hist
  441. hist' = case info of
  442. Nothing -> prevHistoryLst
  443. Just i
  444. | not $canLogSpan span -> prevHistoryLst
  445. | otherwise -> mkHistory hsc_env apStack i `consBL`
  446. fromListBL 50 hist
  447. case step of
  448. RunAndLogSteps ->
  449. traceRunStatus expr bindings final_ids
  450. breakMVar statusMVar status hist'
  451. _other ->
  452. handleRunStatus expr bindings final_ids
  453. breakMVar statusMVar status hist'
  454. back :: GhcMonad m => m ([Name], Int, SrcSpan)
  455. back = moveHist (+1)
  456. forward :: GhcMonad m => m ([Name], Int, SrcSpan)
  457. forward = moveHist (subtract 1)
  458. moveHist :: GhcMonad m => (Int -> Int) -> m ([Name], Int, SrcSpan)
  459. moveHist fn = do
  460. hsc_env <- getSession
  461. case ic_resume (hsc_IC hsc_env) of
  462. [] -> ghcError (ProgramError "not stopped at a breakpoint")
  463. (r:rs) -> do
  464. let ix = resumeHistoryIx r
  465. history = resumeHistory r
  466. new_ix = fn ix
  467. --
  468. when (new_ix > length history) $
  469. ghcError (ProgramError "no more logged breakpoints")
  470. when (new_ix < 0) $
  471. ghcError (ProgramError "already at the beginning of the history")
  472. let
  473. update_ic apStack mb_info = do
  474. (hsc_env1, names, span) <- liftIO $ bindLocalsAtBreakpoint hsc_env
  475. apStack mb_info
  476. let ic = hsc_IC hsc_env1
  477. r' = r { resumeHistoryIx = new_ix }
  478. ic' = ic { ic_resume = r':rs }
  479. modifySession (\_ -> hsc_env1{ hsc_IC = ic' })
  480. return (names, new_ix, span)
  481. -- careful: we want apStack to be the AP_STACK itself, not a thunk
  482. -- around it, hence the cases are carefully constructed below to
  483. -- make this the case. ToDo: this is v. fragile, do something better.
  484. if new_ix == 0
  485. then case r of
  486. Resume { resumeApStack = apStack,
  487. resumeBreakInfo = mb_info } ->
  488. update_ic apStack mb_info
  489. else case history !! (new_ix - 1) of
  490. History apStack info _ ->
  491. update_ic apStack (Just info)
  492. -- -----------------------------------------------------------------------------
  493. -- After stopping at a breakpoint, add free variables to the environment
  494. result_fs :: FastString
  495. result_fs = fsLit "_result"
  496. bindLocalsAtBreakpoint
  497. :: HscEnv
  498. -> HValue
  499. -> Maybe BreakInfo
  500. -> IO (HscEnv, [Name], SrcSpan)
  501. -- Nothing case: we stopped when an exception was raised, not at a
  502. -- breakpoint. We have no location information or local variables to
  503. -- bind, all we can do is bind a local variable to the exception
  504. -- value.
  505. bindLocalsAtBreakpoint hsc_env apStack Nothing = do
  506. let exn_fs = fsLit "_exception"
  507. exn_name = mkInternalName (getUnique exn_fs) (mkVarOccFS exn_fs) span
  508. e_fs = fsLit "e"
  509. e_name = mkInternalName (getUnique e_fs) (mkTyVarOccFS e_fs) span
  510. e_tyvar = mkRuntimeUnkTyVar e_name liftedTypeKind
  511. exn_id = AnId $ Id.mkVanillaGlobal exn_name (mkTyVarTy e_tyvar)
  512. ictxt0 = hsc_IC hsc_env
  513. ictxt1 = extendInteractiveContext ictxt0 [exn_id]
  514. span = mkGeneralSrcSpan (fsLit "<exception thrown>")
  515. --
  516. Linker.extendLinkEnv [(exn_name, unsafeCoerce# apStack)]
  517. return (hsc_env{ hsc_IC = ictxt1 }, [exn_name], span)
  518. -- Just case: we stopped at a breakpoint, we have information about the location
  519. -- of the breakpoint and the free variables of the expression.
  520. bindLocalsAtBreakpoint hsc_env apStack (Just info) = do
  521. let
  522. mod_name = moduleName (breakInfo_module info)
  523. hmi = expectJust "bindLocalsAtBreakpoint" $
  524. lookupUFM (hsc_HPT hsc_env) mod_name
  525. breaks = getModBreaks hmi
  526. index = breakInfo_number info
  527. vars = breakInfo_vars info
  528. result_ty = breakInfo_resty info
  529. occs = modBreaks_vars breaks ! index
  530. span = modBreaks_locs breaks ! index
  531. -- Filter out any unboxed ids;
  532. -- we can't bind these at the prompt
  533. pointers = filter (\(id,_) -> isPointer id) vars
  534. isPointer id | UnaryRep ty <- repType (idType id)
  535. , PtrRep <- typePrimRep ty = True
  536. | otherwise = False
  537. (ids, offsets) = unzip pointers
  538. free_tvs = foldr (unionVarSet . tyVarsOfType . idType)
  539. (tyVarsOfType result_ty) ids
  540. -- It might be that getIdValFromApStack fails, because the AP_STACK
  541. -- has been accidentally evaluated, or something else has gone wrong.
  542. -- So that we don't fall over in a heap when this happens, just don't
  543. -- bind any free variables instead, and we emit a warning.
  544. mb_hValues <- mapM (getIdValFromApStack apStack) (map fromIntegral offsets)
  545. let filtered_ids = [ id | (id, Just _hv) <- zip ids mb_hValues ]
  546. when (any isNothing mb_hValues) $
  547. debugTraceMsg (hsc_dflags hsc_env) 1 $
  548. text "Warning: _result has been evaluated, some bindings have been lost"
  549. us <- mkSplitUniqSupply 'I'
  550. let (us1, us2) = splitUniqSupply us
  551. tv_subst = newTyVars us1 free_tvs
  552. new_ids = zipWith3 (mkNewId tv_subst) occs filtered_ids (uniqsFromSupply us2)
  553. names = map idName new_ids
  554. -- make an Id for _result. We use the Unique of the FastString "_result";
  555. -- we don't care about uniqueness here, because there will only be one
  556. -- _result in scope at any time.
  557. let result_name = mkInternalName (getUnique result_fs)
  558. (mkVarOccFS result_fs) span
  559. result_id = Id.mkVanillaGlobal result_name (substTy tv_subst result_ty)
  560. -- for each Id we're about to bind in the local envt:
  561. -- - tidy the type variables
  562. -- - globalise the Id (Ids are supposed to be Global, apparently).
  563. --
  564. let result_ok = isPointer result_id
  565. all_ids | result_ok = result_id : new_ids
  566. | otherwise = new_ids
  567. id_tys = map idType all_ids
  568. (_,tidy_tys) = tidyOpenTypes emptyTidyEnv id_tys
  569. final_ids = zipWith setIdType all_ids tidy_tys
  570. ictxt0 = hsc_IC hsc_env
  571. ictxt1 = extendInteractiveContext ictxt0 (map AnId final_ids)
  572. Linker.extendLinkEnv [ (name,hval) | (name, Just hval) <- zip names mb_hValues ]
  573. when result_ok $ Linker.extendLinkEnv [(result_name, unsafeCoerce# apStack)]
  574. hsc_env1 <- rttiEnvironment hsc_env{ hsc_IC = ictxt1 }
  575. return (hsc_env1, if result_ok then result_name:names else names, span)
  576. where
  577. -- We need a fresh Unique for each Id we bind, because the linker
  578. -- state is single-threaded and otherwise we'd spam old bindings
  579. -- whenever we stop at a breakpoint. The InteractveContext is properly
  580. -- saved/restored, but not the linker state. See #1743, test break026.
  581. mkNewId :: TvSubst -> OccName -> Id -> Unique -> Id
  582. mkNewId tv_subst occ id uniq
  583. = Id.mkVanillaGlobalWithInfo name ty (idInfo id)
  584. where
  585. loc = nameSrcSpan (idName id)
  586. name = mkInternalName uniq occ loc
  587. ty = substTy tv_subst (idType id)
  588. newTyVars :: UniqSupply -> TcTyVarSet -> TvSubst
  589. -- Similarly, clone the type variables mentioned in the types
  590. -- we have here, *and* make them all RuntimeUnk tyars
  591. newTyVars us tvs
  592. = mkTopTvSubst [ (tv, mkTyVarTy (mkRuntimeUnkTyVar name (tyVarKind tv)))
  593. | (tv, uniq) <- varSetElems tvs `zip` uniqsFromSupply us
  594. , let name = setNameUnique (tyVarName tv) uniq ]
  595. rttiEnvironment :: HscEnv -> IO HscEnv
  596. rttiEnvironment hsc_env@HscEnv{hsc_IC=ic} = do
  597. let tmp_ids = [id | AnId id <- ic_tythings ic]
  598. incompletelyTypedIds =
  599. [id | id <- tmp_ids
  600. , not $ noSkolems id
  601. , (occNameFS.nameOccName.idName) id /= result_fs]
  602. hsc_env' <- foldM improveTypes hsc_env (map idName incompletelyTypedIds)
  603. return hsc_env'
  604. where
  605. noSkolems = isEmptyVarSet . tyVarsOfType . idType
  606. improveTypes hsc_env@HscEnv{hsc_IC=ic} name = do
  607. let tmp_ids = [id | AnId id <- ic_tythings ic]
  608. Just id = find (\i -> idName i == name) tmp_ids
  609. if noSkolems id
  610. then return hsc_env
  611. else do
  612. mb_new_ty <- reconstructType hsc_env 10 id
  613. let old_ty = idType id
  614. case mb_new_ty of
  615. Nothing -> return hsc_env
  616. Just new_ty -> do
  617. case improveRTTIType hsc_env old_ty new_ty of
  618. Nothing -> return $
  619. WARN(True, text (":print failed to calculate the "
  620. ++ "improvement for a type")) hsc_env
  621. Just subst -> do
  622. let dflags = hsc_dflags hsc_env
  623. when (dopt Opt_D_dump_rtti dflags) $
  624. printInfoForUser dflags alwaysQualify $
  625. fsep [text "RTTI Improvement for", ppr id, equals, ppr subst]
  626. let ic' = extendInteractiveContext
  627. (substInteractiveContext ic subst) []
  628. return hsc_env{hsc_IC=ic'}
  629. getIdValFromApStack :: HValue -> Int -> IO (Maybe HValue)
  630. getIdValFromApStack apStack (I# stackDepth) = do
  631. case getApStackVal# apStack (stackDepth +# 1#) of
  632. -- The +1 is magic! I don't know where it comes
  633. -- from, but this makes things line up. --SDM
  634. (# ok, result #) ->
  635. case ok of
  636. 0# -> return Nothing -- AP_STACK not found
  637. _ -> return (Just (unsafeCoerce# result))
  638. pushResume :: HscEnv -> Resume -> HscEnv
  639. pushResume hsc_env resume = hsc_env { hsc_IC = ictxt1 }
  640. where
  641. ictxt0 = hsc_IC hsc_env
  642. ictxt1 = ictxt0 { ic_resume = resume : ic_resume ictxt0 }
  643. -- -----------------------------------------------------------------------------
  644. -- Abandoning a resume context
  645. abandon :: GhcMonad m => m Bool
  646. abandon = do
  647. hsc_env <- getSession
  648. let ic = hsc_IC hsc_env
  649. resume = ic_resume ic
  650. case resume of
  651. [] -> return False
  652. r:rs -> do
  653. modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = rs } }
  654. liftIO $ abandon_ r
  655. return True
  656. abandonAll :: GhcMonad m => m Bool
  657. abandonAll = do
  658. hsc_env <- getSession
  659. let ic = hsc_IC hsc_env
  660. resume = ic_resume ic
  661. case resume of
  662. [] -> return False
  663. rs -> do
  664. modifySession $ \_ -> hsc_env{ hsc_IC = ic { ic_resume = [] } }
  665. liftIO $ mapM_ abandon_ rs
  666. return True
  667. -- when abandoning a computation we have to
  668. -- (a) kill the thread with an async exception, so that the
  669. -- computation itself is stopped, and
  670. -- (b) fill in the MVar. This step is necessary because any
  671. -- thunks that were under evaluation will now be updated
  672. -- with the partial computation, which still ends in takeMVar,
  673. -- so any attempt to evaluate one of these thunks will block
  674. -- unless we fill in the MVar.
  675. -- (c) wait for the thread to terminate by taking its status MVar. This
  676. -- step is necessary to prevent race conditions with
  677. -- -fbreak-on-exception (see #5975).
  678. -- See test break010.
  679. abandon_ :: Resume -> IO ()
  680. abandon_ r = do
  681. killThread (resumeThreadId r)
  682. putMVar (resumeBreakMVar r) ()
  683. _ <- takeMVar (resumeStatMVar r)
  684. return ()
  685. -- -----------------------------------------------------------------------------
  686. -- Bounded list, optimised for repeated cons
  687. data BoundedList a = BL
  688. {-# UNPACK #-} !Int -- length
  689. {-# UNPACK #-} !Int -- bound
  690. [a] -- left
  691. [a] -- right, list is (left ++ reverse right)
  692. nilBL :: Int -> BoundedList a
  693. nilBL bound = BL 0 bound [] []
  694. consBL :: a -> BoundedList a -> BoundedList a
  695. consBL a (BL len bound left right)
  696. | len < bound = BL (len+1) bound (a:left) right
  697. | null right = BL len bound [a] $! tail (reverse left)
  698. | otherwise = BL len bound (a:left) $! tail right
  699. toListBL :: BoundedList a -> [a]
  700. toListBL (BL _ _ left right) = left ++ reverse right
  701. fromListBL :: Int -> [a] -> BoundedList a
  702. fromListBL bound l = BL (length l) bound l []
  703. -- lenBL (BL len _ _ _) = len
  704. -- -----------------------------------------------------------------------------
  705. -- | Set the interactive evaluation context.
  706. --
  707. -- Setting the context doesn't throw away any bindings; the bindings
  708. -- we've built up in the InteractiveContext simply move to the new
  709. -- module. They always shadow anything in scope in the current context.
  710. setContext :: GhcMonad m => [InteractiveImport] -> m ()
  711. setContext imports
  712. = do { hsc_env <- getSession
  713. ; let dflags = hsc_dflags hsc_env
  714. ; all_env_err <- liftIO $ findGlobalRdrEnv hsc_env imports
  715. ; case all_env_err of
  716. Left (mod, err) -> ghcError (formatError dflags mod err)
  717. Right all_env -> do {
  718. ; let old_ic = hsc_IC hsc_env
  719. final_rdr_env = ic_tythings old_ic `icPlusGblRdrEnv` all_env
  720. ; modifySession $ \_ ->
  721. hsc_env{ hsc_IC = old_ic { ic_imports = imports
  722. , ic_rn_gbl_env = final_rdr_env }}}}
  723. where
  724. formatError dflags mod err = ProgramError . showSDoc dflags $
  725. text "Cannot add module" <+> ppr mod <+>
  726. text "to context:" <+> text err
  727. findGlobalRdrEnv :: HscEnv -> [InteractiveImport]
  728. -> IO (Either (ModuleName, String) GlobalRdrEnv)
  729. -- Compute the GlobalRdrEnv for the interactive context
  730. findGlobalRdrEnv hsc_env imports
  731. = do { idecls_env <- hscRnImportDecls hsc_env idecls
  732. -- This call also loads any orphan modules
  733. ; return $ case partitionEithers (map mkEnv imods) of
  734. ([], imods_env) -> Right (foldr plusGlobalRdrEnv idecls_env imods_env)
  735. (err : _, _) -> Left err }
  736. where
  737. idecls :: [LImportDecl RdrName]
  738. idecls = [noLoc d | IIDecl d <- imports]
  739. imods :: [ModuleName]
  740. imods = [m | IIModule m <- imports]
  741. mkEnv mod = case mkTopLevEnv (hsc_HPT hsc_env) mod of
  742. Left err -> Left (mod, err)
  743. Right env -> Right env
  744. availsToGlobalRdrEnv :: ModuleName -> [AvailInfo] -> GlobalRdrEnv
  745. availsToGlobalRdrEnv mod_name avails
  746. = mkGlobalRdrEnv (gresFromAvails imp_prov avails)
  747. where
  748. -- We're building a GlobalRdrEnv as if the user imported
  749. -- all the specified modules into the global interactive module
  750. imp_prov = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
  751. decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
  752. is_qual = False,
  753. is_dloc = srcLocSpan interactiveSrcLoc }
  754. mkTopLevEnv :: HomePackageTable -> ModuleName -> Either String GlobalRdrEnv
  755. mkTopLevEnv hpt modl
  756. = case lookupUFM hpt modl of
  757. Nothing -> Left "not a home module"
  758. Just details ->
  759. case mi_globals (hm_iface details) of
  760. Nothing -> Left "not interpreted"
  761. Just env -> Right env
  762. -- | Get the interactive evaluation context, consisting of a pair of the
  763. -- set of modules from which we take the full top-level scope, and the set
  764. -- of modules from which we take just the exports respectively.
  765. getContext :: GhcMonad m => m [InteractiveImport]
  766. getContext = withSession $ \HscEnv{ hsc_IC=ic } ->
  767. return (ic_imports ic)
  768. -- | Returns @True@ if the specified module is interpreted, and hence has
  769. -- its full top-level scope available.
  770. moduleIsInterpreted :: GhcMonad m => Module -> m Bool
  771. moduleIsInterpreted modl = withSession $ \h ->
  772. if modulePackageId modl /= thisPackage (hsc_dflags h)
  773. then return False
  774. else case lookupUFM (hsc_HPT h) (moduleName modl) of
  775. Just details -> return (isJust (mi_globals (hm_iface details)))
  776. _not_a_home_module -> return False
  777. -- | Looks up an identifier in the current interactive context (for :info)
  778. -- Filter the instances by the ones whose tycons (or clases resp)
  779. -- are in scope (qualified or otherwise). Otherwise we list a whole lot too many!
  780. -- The exact choice of which ones to show, and which to hide, is a judgement call.
  781. -- (see Trac #1581)
  782. getInfo :: GhcMonad m => Name -> m (Maybe (TyThing,Fixity,[ClsInst]))
  783. getInfo name
  784. = withSession $ \hsc_env ->
  785. do mb_stuff <- liftIO $ hscTcRnGetInfo hsc_env name
  786. case mb_stuff of
  787. Nothing -> return Nothing
  788. Just (thing, fixity, ispecs) -> do
  789. let rdr_env = ic_rn_gbl_env (hsc_IC hsc_env)
  790. return (Just (thing, fixity, filter (plausible rdr_env) ispecs))
  791. where
  792. plausible rdr_env ispec -- Dfun involving only names that are in ic_rn_glb_env
  793. = all ok $ nameSetToList $ orphNamesOfType $ idType $ instanceDFunId ispec
  794. where -- A name is ok if it's in the rdr_env,
  795. -- whether qualified or not
  796. ok n | n == name = True -- The one we looked for in the first place!
  797. | isBuiltInSyntax n = True
  798. | isExternalName n = any ((== n) . gre_name)
  799. (lookupGRE_Name rdr_env n)
  800. | otherwise = True
  801. -- | Returns all names in scope in the current interactive context
  802. getNamesInScope :: GhcMonad m => m [Name]
  803. getNamesInScope = withSession $ \hsc_env -> do
  804. return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
  805. getRdrNamesInScope :: GhcMonad m => m [RdrName]
  806. getRdrNamesInScope = withSession $ \hsc_env -> do
  807. let
  808. ic = hsc_IC hsc_env
  809. gbl_rdrenv = ic_rn_gbl_env ic
  810. gbl_names = concatMap greToRdrNames $ globalRdrEnvElts gbl_rdrenv
  811. return gbl_names
  812. -- ToDo: move to RdrName
  813. greToRdrNames :: GlobalRdrElt -> [RdrName]
  814. greToRdrNames GRE{ gre_name = name, gre_prov = prov }
  815. = case prov of
  816. LocalDef -> [unqual]
  817. Imported specs -> concat (map do_spec (map is_decl specs))
  818. where
  819. occ = nameOccName name
  820. unqual = Unqual occ
  821. do_spec decl_spec
  822. | is_qual decl_spec = [qual]
  823. | otherwise = [unqual,qual]
  824. where qual = Qual (is_as decl_spec) occ
  825. -- | Parses a string as an identifier, and returns the list of 'Name's that
  826. -- the identifier can refer to in the current interactive context.
  827. parseName :: GhcMonad m => String -> m [Name]
  828. parseName str = withSession $ \hsc_env -> do
  829. (L _ rdr_name) <- liftIO $ hscParseIdentifier hsc_env str
  830. liftIO $ hscTcRnLookupRdrName hsc_env rdr_name
  831. -- -----------------------------------------------------------------------------
  832. -- Getting the type of an expression
  833. -- | Get the type of an expression
  834. exprType :: GhcMonad m => String -> m Type
  835. exprType expr = withSession $ \hsc_env -> do
  836. ty <- liftIO $ hscTcExpr hsc_env expr
  837. return $ tidyType emptyTidyEnv ty
  838. -- -----------------------------------------------------------------------------
  839. -- Getting the kind of a type
  840. -- | Get the kind of a type
  841. typeKind :: GhcMonad m => Bool -> String -> m (Type, Kind)
  842. typeKind normalise str = withSession $ \hsc_env -> do
  843. liftIO $ hscKcType hsc_env normalise str
  844. -----------------------------------------------------------------------------
  845. -- Compile an expression, run it and deliver the resulting HValue
  846. compileExpr :: GhcMonad m => String -> m HValue
  847. compileExpr expr = withSession $ \hsc_env -> do
  848. Just (ids, hval, fix_env) <- liftIO $ hscStmt hsc_env ("let __cmCompileExpr = "++expr)
  849. updateFixityEnv fix_env
  850. hvals <- liftIO hval
  851. case (ids,hvals) of
  852. ([_],[hv]) -> return hv
  853. _ -> panic "compileExpr"
  854. -- -----------------------------------------------------------------------------
  855. -- Compile an expression, run it and return the result as a dynamic
  856. dynCompileExpr :: GhcMonad m => String -> m Dynamic
  857. dynCompileExpr expr = do
  858. iis <- getContext
  859. let importDecl = ImportDecl {
  860. ideclName = noLoc (mkModuleName "Data.Dynamic"),
  861. ideclPkgQual = Nothing,
  862. ideclSource = False,
  863. ideclSafe = False,
  864. ideclQualified = True,
  865. ideclImplicit = False,
  866. ideclAs = Nothing,
  867. ideclHiding = Nothing
  868. }
  869. setContext (IIDecl importDecl : iis)
  870. let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
  871. Just (ids, hvals, fix_env) <- withSession $ \hsc_env ->
  872. liftIO $ hscStmt hsc_env stmt
  873. setContext iis
  874. updateFixityEnv fix_env
  875. vals <- liftIO (unsafeCoerce# hvals :: IO [Dynamic])
  876. case (ids,vals) of
  877. (_:[], v:[]) -> return v
  878. _ -> panic "dynCompileExpr"
  879. -----------------------------------------------------------------------------
  880. -- show a module and it's source/object filenames
  881. showModule :: GhcMonad m => ModSummary -> m String
  882. showModule mod_summary =
  883. withSession $ \hsc_env -> do
  884. interpreted <- isModuleInterpreted mod_summary
  885. let dflags = hsc_dflags hsc_env
  886. return (showModMsg dflags (hscTarget dflags) interpreted mod_summary)
  887. isModuleInterpreted :: GhcMonad m => ModSummary -> m Bool
  888. isModuleInterpreted mod_summary = withSession $ \hsc_env ->
  889. case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
  890. Nothing -> panic "missing linkable"
  891. Just mod_info -> return (not obj_linkable)
  892. where
  893. obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
  894. ----------------------------------------------------------------------------
  895. -- RTTI primitives
  896. obtainTermFromVal :: HscEnv -> Int -> Bool -> Type -> a -> IO Term
  897. obtainTermFromVal hsc_env bound force ty x =
  898. cvObtainTerm hsc_env bound force ty (unsafeCoerce# x)
  899. obtainTermFromId :: HscEnv -> Int -> Bool -> Id -> IO Term
  900. obtainTermFromId hsc_env bound force id = do
  901. hv <- Linker.getHValue hsc_env (varName id)
  902. cvObtainTerm hsc_env bound force (idType id) hv
  903. -- Uses RTTI to reconstruct the type of an Id, making it less polymorphic
  904. reconstructType :: HscEnv -> Int -> Id -> IO (Maybe Type)
  905. reconstructType hsc_env bound id = do
  906. hv <- Linker.getHValue hsc_env (varName id)
  907. cvReconstructType hsc_env bound (idType id) hv
  908. mkRuntimeUnkTyVar :: Name -> Kind -> TyVar
  909. mkRuntimeUnkTyVar name kind = mkTcTyVar name kind RuntimeUnk
  910. #endif /* GHCI */