PageRenderTime 28ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/ghc-7.0.4/compiler/main/InteractiveEval.hs

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