<commit_before>-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------

{-# OPTIONS -w #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
-- for details

module InteractiveEval (
#ifdef GHCI
        RunResult(..), Status(..), Resume(..), History(..),
	runStmt, SingleStep(..),
        resume,
        abandon, abandonAll,
        getResumeContext,
        getHistorySpan,
        getModBreaks,
        getHistoryModule,
        back, forward,
	setContext, getContext,	
        nameSetToGlobalRdrEnv,
	getNamesInScope,
	getRdrNamesInScope,
	moduleIsInterpreted,
	getInfo,
	exprType,
	typeKind,
	parseName,
	showModule,
        isModuleInterpreted,
	compileExpr, dynCompileExpr,
	lookupName,
        Term(..), obtainTerm, obtainTerm1, obtainTermB, reconstructType,
        skolemiseSubst, skolemiseTy
#endif
        ) where

#ifdef GHCI

#include "HsVersions.h"

import HscMain          hiding (compileExpr)
import HscTypes
import TcRnDriver
import Type             hiding (typeKind)
import TcType           hiding (typeKind)
import InstEnv
import Var              hiding (setIdType)
import Id
import IdInfo
import Name             hiding ( varName )
import NameSet
import RdrName
import VarSet
import VarEnv
import ByteCodeInstr
import Linker
import DynFlags
import Unique
import UniqSupply
import Module
import Panic
import UniqFM
import Maybes
import ErrUtils
import Util
import SrcLoc
import BreakArray
import RtClosureInspect
import Packages
import BasicTypes
import Outputable

import Data.Dynamic
import Data.List (find)
import Control.Monad
import Foreign
import Foreign.C
import GHC.Exts
import Data.Array
import Control.Exception as Exception
import Control.Concurrent
import Data.List (sortBy)
import Data.IORef
import Foreign.StablePtr

-- -----------------------------------------------------------------------------
-- running a statement interactively

data RunResult
  = RunOk [Name] 		-- ^ names bound by this evaluation
  | RunFailed	 		-- ^ statement failed compilation
  | RunException Exception	-- ^ statement raised an exception
  | RunBreak ThreadId [Name] (Maybe BreakInfo)

data Status
   = Break Bool HValue BreakInfo ThreadId
          -- ^ the computation hit a breakpoint (Bool <=> was an exception)
   | Complete (Either Exception [HValue])
          -- ^ the computation completed with either an exception or a value

data Resume
   = Resume {
       resumeStmt      :: String,       -- the original statement
       resumeThreadId  :: ThreadId,     -- thread running the computation
       resumeBreakMVar :: MVar (),   
       resumeStatMVar  :: MVar Status,
       resumeBindings  :: ([Id], TyVarSet),
       resumeFinalIds  :: [Id],         -- [Id] to bind on completion
       resumeApStack   :: HValue,       -- The object from which we can get
                                        -- value of the free variables.
       resumeBreakInfo :: Maybe BreakInfo,    
                                        -- the breakpoint we stopped at
                                        -- (Nothing <=> exception)
       resumeSpan      :: SrcSpan,      -- just a cache, otherwise it's a pain
                                        -- to fetch the ModDetails & ModBreaks
                                        -- to get this.
       resumeHistory   :: [History],
       resumeHistoryIx :: Int           -- 0 <==> at the top of the history
   }

getResumeContext :: Session -> IO [Resume]
getResumeContext s = withSession s (return . ic_resume . hsc_IC)

data SingleStep
   = RunToCompletion
   | SingleStep
   | RunAndLogSteps

isStep RunToCompletion = False
isStep _ = True

data History
   = History {
        historyApStack   :: HValue,
        historyBreakInfo :: BreakInfo,
        historyEnclosingDecl :: Id
         -- ^^ A cache of the enclosing top level declaration, for convenience
   }

mkHistory :: HscEnv -> HValue -> BreakInfo -> History
mkHistory hsc_env hval bi = let
    h    = History hval bi decl
    decl = findEnclosingDecl hsc_env (getHistoryModule h)
                                     (getHistorySpan hsc_env h)
    in h

getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo

getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env hist =
   let inf = historyBreakInfo hist
       num = breakInfo_number inf
   in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
       Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
       _ -> panic "getHistorySpan"

getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
  | Just linkable <- hm_linkable hmi, 
    [BCOs _ modBreaks] <- linkableUnlinked linkable
  = modBreaks
  | otherwise
  = emptyModBreaks -- probably object code

{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
findEnclosingDecl hsc_env mod span =
   case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
         Nothing -> panic "findEnclosingDecl"
         Just hmi -> let
             globals   = typeEnvIds (md_types (hm_details hmi))
             Just decl = 
                 find (\id -> let n = idName id in 
                               nameSrcSpan n < span && isExternalName n)
                      (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
                                       globals)
           in decl

-- | Run a statement in the current interactive context.  Statement
-- may bind multple values.
runStmt :: Session -> String -> SingleStep -> IO RunResult
runStmt (Session ref) expr step
   = do 
	hsc_env <- readIORef ref

        breakMVar  <- newEmptyMVar  -- wait on this when we hit a breakpoint
        statusMVar <- newEmptyMVar  -- wait on this when a computation is running 

	-- Turn off -fwarn-unused-bindings when running a statement, to hide
	-- warnings about the implicit bindings we introduce.
	let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
	    hsc_env' = hsc_env{ hsc_dflags = dflags' }

        maybe_stuff <- hscStmt hsc_env' expr

        case maybe_stuff of
	   Nothing -> return RunFailed
	   Just (ids, hval) -> do

              status <- 
                withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
                      let thing_to_run = unsafeCoerce# hval :: IO [HValue]
                      sandboxIO dflags' statusMVar thing_to_run
              
              let ic = hsc_IC hsc_env
                  bindings = (ic_tmp_ids ic, ic_tyvars ic)

              case step of
                RunAndLogSteps -> 
                        traceRunStatus expr ref bindings ids   
                                       breakMVar statusMVar status emptyHistory
                _other ->
                        handleRunStatus expr ref bindings ids
                                        breakMVar statusMVar status emptyHistory


emptyHistory = nilBL 50 -- keep a log of length 50

handleRunStatus expr ref bindings final_ids breakMVar statusMVar status 
                history =
   case status of  
      -- did we hit a breakpoint or did we complete?
      (Break is_exception apStack info tid) -> do
        hsc_env <- readIORef ref
        let mb_info | is_exception = Nothing
                    | otherwise    = Just info
        (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env 
                                                          apStack mb_info
        let
            resume = Resume expr tid breakMVar statusMVar 
                              bindings final_ids apStack mb_info span 
                              (toListBL history) 0
            hsc_env2 = pushResume hsc_env1 resume
        --
        writeIORef ref hsc_env2
        return (RunBreak tid names mb_info)
      (Complete either_hvals) ->
	case either_hvals of
	    Left e -> return (RunException e)
	    Right hvals -> do
                hsc_env <- readIORef ref
                let final_ic = extendInteractiveContext (hsc_IC hsc_env)
                                        final_ids emptyVarSet
                        -- the bound Ids never have any free TyVars
                    final_names = map idName final_ids
                Linker.extendLinkEnv (zip final_names hvals)
                hsc_env' <- rttiEnvironment hsc_env{hsc_IC=final_ic}
                writeIORef ref hsc_env' 
                return (RunOk final_names)


traceRunStatus expr ref bindings final_ids
               breakMVar statusMVar status history = do
  hsc_env <- readIORef ref
  case status of
     -- when tracing, if we hit a breakpoint that is not explicitly
     -- enabled, then we just log the event in the history and continue.
     (Break is_exception apStack info tid) | not is_exception -> do
        b <- isBreakEnabled hsc_env info
        if b
           then handle_normally
           else do
             let history' = mkHistory hsc_env apStack info `consBL` history
                -- probably better make history strict here, otherwise
                -- our BoundedList will be pointless.
             evaluate history'
             status <- withBreakAction True (hsc_dflags hsc_env)
                                 breakMVar statusMVar $ do
                       withInterruptsSentTo
                         (do putMVar breakMVar ()  -- awaken the stopped thread
                             return tid)
                         (takeMVar statusMVar)     -- and wait for the result
             traceRunStatus expr ref bindings final_ids 
                            breakMVar statusMVar status history'
     _other ->
        handle_normally
  where
        handle_normally = handleRunStatus expr ref bindings final_ids 
                                          breakMVar statusMVar status history


isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
isBreakEnabled hsc_env inf =
   case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
       Just hmi -> do
         w <- getBreak (modBreaks_flags (getModBreaks hmi))
                       (breakInfo_number inf)
         case w of Just n -> return (n /= 0); _other -> return False
       _ ->
         return False


foreign import ccall "&rts_stop_next_breakpoint" stepFlag      :: Ptr CInt
foreign import ccall "&rts_stop_on_exception"    exceptionFlag :: Ptr CInt

setStepFlag   = poke stepFlag 1
resetStepFlag = poke stepFlag 0

-- this points to the IO action that is executed when a breakpoint is hit
foreign import ccall "&rts_breakpoint_io_action" 
   breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ())) 

-- When running a computation, we redirect ^C exceptions to the running
-- thread.  ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
sandboxIO dflags statusMVar thing = 
  withInterruptsSentTo 
        (forkIO (do res <- Exception.try (rethrow dflags thing)
                    putMVar statusMVar (Complete res)))
        (takeMVar statusMVar)

-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break.  Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange).  So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: DynFlags -> IO a -> IO a
rethrow dflags io = Exception.catch io $ \e -> do -- NB. not catchDyn
                case e of
                   -- If -fbreak-on-error, we break unconditionally,
                   --  but with care of not breaking twice 
                   _ | dopt Opt_BreakOnError dflags && 
                       not(dopt Opt_BreakOnException dflags)
                        -> poke exceptionFlag 1

                   -- If it is an "Interrupted" exception, we allow
                   --  a possible break by way of -fbreak-on-exception
                   DynException d | Just Interrupted <- fromDynamic d
                        -> return ()

                   -- In any other case, we don't want to break
                   _    -> poke exceptionFlag 0

                Exception.throwIO e


withInterruptsSentTo :: IO ThreadId -> IO r -> IO r
withInterruptsSentTo io get_result = do
  ts <- takeMVar interruptTargetThread
  child <- io
  putMVar interruptTargetThread (child:ts)
  get_result `finally` modifyMVar_ interruptTargetThread (return.tail)

-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running.  This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction step dflags breakMVar statusMVar io
 = bracket setBreakAction resetBreakAction (\_ -> io)
 where
   setBreakAction = do
     stablePtr <- newStablePtr onBreak
     poke breakPointIOAction stablePtr
     when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
     when step $ setStepFlag
     return stablePtr
        -- Breaking on exceptions is not enabled by default, since it
        -- might be a bit surprising.  The exception flag is turned off
        -- as soon as it is hit, or in resetBreakAction below.

   onBreak is_exception info apStack = do
     tid <- myThreadId
     putMVar statusMVar (Break is_exception apStack info tid)
     takeMVar breakMVar

   resetBreakAction stablePtr = do
     poke breakPointIOAction noBreakStablePtr
     poke exceptionFlag 0
     resetStepFlag
     freeStablePtr stablePtr

noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction

noBreakAction False info apStack = putStrLn "*** Ignoring breakpoint"
noBreakAction True  info apStack = return () -- exception: just continue

resume :: Session -> SingleStep -> IO RunResult
resume (Session ref) step
 = do
   hsc_env <- readIORef ref
   let ic = hsc_IC hsc_env
       resume = ic_resume ic

   case resume of
     [] -> throwDyn (ProgramError "not stopped at a breakpoint")
     (r:rs) -> do
        -- unbind the temporary locals by restoring the TypeEnv from
        -- before the breakpoint, and drop this Resume from the
        -- InteractiveContext.
        let (resume_tmp_ids, resume_tyvars) = resumeBindings r
            ic' = ic { ic_tmp_ids  = resume_tmp_ids,
                       ic_tyvars   = resume_tyvars,
                       ic_resume   = rs }
        writeIORef ref hsc_env{ hsc_IC = ic' }
        
        -- remove any bindings created since the breakpoint from the 
        -- linker's environment
        let new_names = map idName (filter (`notElem` resume_tmp_ids)
                                           (ic_tmp_ids ic))
        Linker.deleteFromLinkEnv new_names
        
        when (isStep step) $ setStepFlag
        case r of 
          Resume expr tid breakMVar statusMVar bindings 
              final_ids apStack info _ hist _ -> do
                withBreakAction (isStep step) (hsc_dflags hsc_env) 
                                        breakMVar statusMVar $ do
                status <- withInterruptsSentTo
                             (do putMVar breakMVar ()
                                      -- this awakens the stopped thread...
                                 return tid)
                             (takeMVar statusMVar)
                                      -- and wait for the result 
                let hist' = 
                     case info of 
                       Nothing -> fromListBL 50 hist
                       Just i -> mkHistory hsc_env apStack i `consBL` 
                                                        fromListBL 50 hist
                case step of
                  RunAndLogSteps -> 
                        traceRunStatus expr ref bindings final_ids
                                       breakMVar statusMVar status hist'
                  _other ->
                        handleRunStatus expr ref bindings final_ids
                                        breakMVar statusMVar status hist'

back :: Session -> IO ([Name], Int, SrcSpan)
back  = moveHist (+1)

forward :: Session -> IO ([Name], Int, SrcSpan)
forward  = moveHist (subtract 1)<commit_msg>fix race conditions in sandboxIO (#1583, #1922, #1946) using the new block-inheriting forkIO (#1048)<commit_after>-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2007
--
-- Running statements interactively
--
-- -----------------------------------------------------------------------------

{-# OPTIONS -w #-}
-- The above warning supression flag is a temporary kludge.
-- While working on this module you are encouraged to remove it and fix
-- any warnings in the module. See
--     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
-- for details

module InteractiveEval (
#ifdef GHCI
        RunResult(..), Status(..), Resume(..), History(..),
	runStmt, SingleStep(..),
        resume,
        abandon, abandonAll,
        getResumeContext,
        getHistorySpan,
        getModBreaks,
        getHistoryModule,
        back, forward,
	setContext, getContext,	
        nameSetToGlobalRdrEnv,
	getNamesInScope,
	getRdrNamesInScope,
	moduleIsInterpreted,
	getInfo,
	exprType,
	typeKind,
	parseName,
	showModule,
        isModuleInterpreted,
	compileExpr, dynCompileExpr,
	lookupName,
        Term(..), obtainTerm, obtainTerm1, obtainTermB, reconstructType,
        skolemiseSubst, skolemiseTy
#endif
        ) where

#ifdef GHCI

#include "HsVersions.h"

import HscMain          hiding (compileExpr)
import HscTypes
import TcRnDriver
import Type             hiding (typeKind)
import TcType           hiding (typeKind)
import InstEnv
import Var              hiding (setIdType)
import Id
import IdInfo
import Name             hiding ( varName )
import NameSet
import RdrName
import VarSet
import VarEnv
import ByteCodeInstr
import Linker
import DynFlags
import Unique
import UniqSupply
import Module
import Panic
import UniqFM
import Maybes
import ErrUtils
import Util
import SrcLoc
import BreakArray
import RtClosureInspect
import Packages
import BasicTypes
import Outputable

import Data.Dynamic
import Data.List (find)
import Control.Monad
import Foreign
import Foreign.C
import GHC.Exts
import Data.Array
import Control.Exception as Exception
import Control.Concurrent
import Data.List (sortBy)
import Data.IORef
import Foreign.StablePtr

-- -----------------------------------------------------------------------------
-- running a statement interactively

data RunResult
  = RunOk [Name] 		-- ^ names bound by this evaluation
  | RunFailed	 		-- ^ statement failed compilation
  | RunException Exception	-- ^ statement raised an exception
  | RunBreak ThreadId [Name] (Maybe BreakInfo)

data Status
   = Break Bool HValue BreakInfo ThreadId
          -- ^ the computation hit a breakpoint (Bool <=> was an exception)
   | Complete (Either Exception [HValue])
          -- ^ the computation completed with either an exception or a value

data Resume
   = Resume {
       resumeStmt      :: String,       -- the original statement
       resumeThreadId  :: ThreadId,     -- thread running the computation
       resumeBreakMVar :: MVar (),   
       resumeStatMVar  :: MVar Status,
       resumeBindings  :: ([Id], TyVarSet),
       resumeFinalIds  :: [Id],         -- [Id] to bind on completion
       resumeApStack   :: HValue,       -- The object from which we can get
                                        -- value of the free variables.
       resumeBreakInfo :: Maybe BreakInfo,    
                                        -- the breakpoint we stopped at
                                        -- (Nothing <=> exception)
       resumeSpan      :: SrcSpan,      -- just a cache, otherwise it's a pain
                                        -- to fetch the ModDetails & ModBreaks
                                        -- to get this.
       resumeHistory   :: [History],
       resumeHistoryIx :: Int           -- 0 <==> at the top of the history
   }

getResumeContext :: Session -> IO [Resume]
getResumeContext s = withSession s (return . ic_resume . hsc_IC)

data SingleStep
   = RunToCompletion
   | SingleStep
   | RunAndLogSteps

isStep RunToCompletion = False
isStep _ = True

data History
   = History {
        historyApStack   :: HValue,
        historyBreakInfo :: BreakInfo,
        historyEnclosingDecl :: Id
         -- ^^ A cache of the enclosing top level declaration, for convenience
   }

mkHistory :: HscEnv -> HValue -> BreakInfo -> History
mkHistory hsc_env hval bi = let
    h    = History hval bi decl
    decl = findEnclosingDecl hsc_env (getHistoryModule h)
                                     (getHistorySpan hsc_env h)
    in h

getHistoryModule :: History -> Module
getHistoryModule = breakInfo_module . historyBreakInfo

getHistorySpan :: HscEnv -> History -> SrcSpan
getHistorySpan hsc_env hist =
   let inf = historyBreakInfo hist
       num = breakInfo_number inf
   in case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
       Just hmi -> modBreaks_locs (getModBreaks hmi) ! num
       _ -> panic "getHistorySpan"

getModBreaks :: HomeModInfo -> ModBreaks
getModBreaks hmi
  | Just linkable <- hm_linkable hmi, 
    [BCOs _ modBreaks] <- linkableUnlinked linkable
  = modBreaks
  | otherwise
  = emptyModBreaks -- probably object code

{- | Finds the enclosing top level function name -}
-- ToDo: a better way to do this would be to keep hold of the decl_path computed
-- by the coverage pass, which gives the list of lexically-enclosing bindings
-- for each tick.
findEnclosingDecl :: HscEnv -> Module -> SrcSpan -> Id
findEnclosingDecl hsc_env mod span =
   case lookupUFM (hsc_HPT hsc_env) (moduleName mod) of
         Nothing -> panic "findEnclosingDecl"
         Just hmi -> let
             globals   = typeEnvIds (md_types (hm_details hmi))
             Just decl = 
                 find (\id -> let n = idName id in 
                               nameSrcSpan n < span && isExternalName n)
                      (reverse$ sortBy (compare `on` (nameSrcSpan.idName))
                                       globals)
           in decl

-- | Run a statement in the current interactive context.  Statement
-- may bind multple values.
runStmt :: Session -> String -> SingleStep -> IO RunResult
runStmt (Session ref) expr step
   = do 
	hsc_env <- readIORef ref

        breakMVar  <- newEmptyMVar  -- wait on this when we hit a breakpoint
        statusMVar <- newEmptyMVar  -- wait on this when a computation is running 

	-- Turn off -fwarn-unused-bindings when running a statement, to hide
	-- warnings about the implicit bindings we introduce.
	let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
	    hsc_env' = hsc_env{ hsc_dflags = dflags' }

        maybe_stuff <- hscStmt hsc_env' expr

        case maybe_stuff of
	   Nothing -> return RunFailed
	   Just (ids, hval) -> do

              status <- 
                withBreakAction (isStep step) dflags' breakMVar statusMVar $ do
                      let thing_to_run = unsafeCoerce# hval :: IO [HValue]
                      sandboxIO dflags' statusMVar thing_to_run
              
              let ic = hsc_IC hsc_env
                  bindings = (ic_tmp_ids ic, ic_tyvars ic)

              case step of
                RunAndLogSteps -> 
                        traceRunStatus expr ref bindings ids   
                                       breakMVar statusMVar status emptyHistory
                _other ->
                        handleRunStatus expr ref bindings ids
                                        breakMVar statusMVar status emptyHistory


emptyHistory = nilBL 50 -- keep a log of length 50

handleRunStatus expr ref bindings final_ids breakMVar statusMVar status 
                history =
   case status of  
      -- did we hit a breakpoint or did we complete?
      (Break is_exception apStack info tid) -> do
        hsc_env <- readIORef ref
        let mb_info | is_exception = Nothing
                    | otherwise    = Just info
        (hsc_env1, names, span) <- bindLocalsAtBreakpoint hsc_env 
                                                          apStack mb_info
        let
            resume = Resume expr tid breakMVar statusMVar 
                              bindings final_ids apStack mb_info span 
                              (toListBL history) 0
            hsc_env2 = pushResume hsc_env1 resume
        --
        writeIORef ref hsc_env2
        return (RunBreak tid names mb_info)
      (Complete either_hvals) ->
	case either_hvals of
	    Left e -> return (RunException e)
	    Right hvals -> do
                hsc_env <- readIORef ref
                let final_ic = extendInteractiveContext (hsc_IC hsc_env)
                                        final_ids emptyVarSet
                        -- the bound Ids never have any free TyVars
                    final_names = map idName final_ids
                Linker.extendLinkEnv (zip final_names hvals)
                hsc_env' <- rttiEnvironment hsc_env{hsc_IC=final_ic}
                writeIORef ref hsc_env' 
                return (RunOk final_names)


traceRunStatus expr ref bindings final_ids
               breakMVar statusMVar status history = do
  hsc_env <- readIORef ref
  case status of
     -- when tracing, if we hit a breakpoint that is not explicitly
     -- enabled, then we just log the event in the history and continue.
     (Break is_exception apStack info tid) | not is_exception -> do
        b <- isBreakEnabled hsc_env info
        if b
           then handle_normally
           else do
             let history' = mkHistory hsc_env apStack info `consBL` history
                -- probably better make history strict here, otherwise
                -- our BoundedList will be pointless.
             evaluate history'
             status <- withBreakAction True (hsc_dflags hsc_env)
                                 breakMVar statusMVar $ do
                       withInterruptsSentTo tid $ do
                           putMVar breakMVar ()  -- awaken the stopped thread
                           takeMVar statusMVar   -- and wait for the result
             traceRunStatus expr ref bindings final_ids 
                            breakMVar statusMVar status history'
     _other ->
        handle_normally
  where
        handle_normally = handleRunStatus expr ref bindings final_ids 
                                          breakMVar statusMVar status history


isBreakEnabled :: HscEnv -> BreakInfo -> IO Bool
isBreakEnabled hsc_env inf =
   case lookupUFM (hsc_HPT hsc_env) (moduleName (breakInfo_module inf)) of
       Just hmi -> do
         w <- getBreak (modBreaks_flags (getModBreaks hmi))
                       (breakInfo_number inf)
         case w of Just n -> return (n /= 0); _other -> return False
       _ ->
         return False


foreign import ccall "&rts_stop_next_breakpoint" stepFlag      :: Ptr CInt
foreign import ccall "&rts_stop_on_exception"    exceptionFlag :: Ptr CInt

setStepFlag   = poke stepFlag 1
resetStepFlag = poke stepFlag 0

-- this points to the IO action that is executed when a breakpoint is hit
foreign import ccall "&rts_breakpoint_io_action" 
   breakPointIOAction :: Ptr (StablePtr (Bool -> BreakInfo -> HValue -> IO ())) 

-- When running a computation, we redirect ^C exceptions to the running
-- thread.  ToDo: we might want a way to continue even if the target
-- thread doesn't die when it receives the exception... "this thread
-- is not responding".
-- 
-- Careful here: there may be ^C exceptions flying around, so we start
-- the new thread blocked (forkIO inherits block from the parent,
-- #1048), and unblock only while we execute the user's code.  We
-- can't afford to lose the final putMVar, otherwise deadlock
-- ensues. (#1583, #1922, #1946)
sandboxIO :: DynFlags -> MVar Status -> IO [HValue] -> IO Status
sandboxIO dflags statusMVar thing =
   block $ do  -- fork starts blocked
     id <- forkIO $ do res <- Exception.try (unblock $ rethrow dflags thing)
                       putMVar statusMVar (Complete res) -- empty: can't block
     withInterruptsSentTo id $ takeMVar statusMVar


-- We want to turn ^C into a break when -fbreak-on-exception is on,
-- but it's an async exception and we only break for sync exceptions.
-- Idea: if we catch and re-throw it, then the re-throw will trigger
-- a break.  Great - but we don't want to re-throw all exceptions, because
-- then we'll get a double break for ordinary sync exceptions (you'd have
-- to :continue twice, which looks strange).  So if the exception is
-- not "Interrupted", we unset the exception flag before throwing.
--
rethrow :: DynFlags -> IO a -> IO a
rethrow dflags io = Exception.catch io $ \e -> do -- NB. not catchDyn
                case e of
                   -- If -fbreak-on-error, we break unconditionally,
                   --  but with care of not breaking twice 
                   _ | dopt Opt_BreakOnError dflags && 
                       not(dopt Opt_BreakOnException dflags)
                        -> poke exceptionFlag 1

                   -- If it is an "Interrupted" exception, we allow
                   --  a possible break by way of -fbreak-on-exception
                   DynException d | Just Interrupted <- fromDynamic d
                        -> return ()

                   -- In any other case, we don't want to break
                   _    -> poke exceptionFlag 0

                Exception.throwIO e


withInterruptsSentTo :: ThreadId -> IO r -> IO r
withInterruptsSentTo thread get_result = do
  bracket (modifyMVar_ interruptTargetThread (return . (thread:)))
          (\_ -> modifyMVar_ interruptTargetThread (return.tail))
          (\_ -> get_result)

-- This function sets up the interpreter for catching breakpoints, and
-- resets everything when the computation has stopped running.  This
-- is a not-very-good way to ensure that only the interactive
-- evaluation should generate breakpoints.
withBreakAction step dflags breakMVar statusMVar io
 = bracket setBreakAction resetBreakAction (\_ -> io)
 where
   setBreakAction = do
     stablePtr <- newStablePtr onBreak
     poke breakPointIOAction stablePtr
     when (dopt Opt_BreakOnException dflags) $ poke exceptionFlag 1
     when step $ setStepFlag
     return stablePtr
        -- Breaking on exceptions is not enabled by default, since it
        -- might be a bit surprising.  The exception flag is turned off
        -- as soon as it is hit, or in resetBreakAction below.

   onBreak is_exception info apStack = do
     tid <- myThreadId
     putMVar statusMVar (Break is_exception apStack info tid)
     takeMVar breakMVar

   resetBreakAction stablePtr = do
     poke breakPointIOAction noBreakStablePtr
     poke exceptionFlag 0
     resetStepFlag
     freeStablePtr stablePtr

noBreakStablePtr = unsafePerformIO $ newStablePtr noBreakAction

noBreakAction False info apStack = putStrLn "*** Ignoring breakpoint"
noBreakAction True  info apStack = return () -- exception: just continue

resume :: Session -> SingleStep -> IO RunResult
resume (Session ref) step
 = do
   hsc_env <- readIORef ref
   let ic = hsc_IC hsc_env
       resume = ic_resume ic

   case resume of
     [] -> throwDyn (ProgramError "not stopped at a breakpoint")
     (r:rs) -> do
        -- unbind the temporary locals by restoring the TypeEnv from
        -- before the breakpoint, and drop this Resume from the
        -- InteractiveContext.
        let (resume_tmp_ids, resume_tyvars) = resumeBindings r
            ic' = ic { ic_tmp_ids  = resume_tmp_ids,
                       ic_tyvars   = resume_tyvars,
                       ic_resume   = rs }
        writeIORef ref hsc_env{ hsc_IC = ic' }
        
        -- remove any bindings created since the breakpoint from the 
        -- linker's environment
        let new_names = map idName (filter (`notElem` resume_tmp_ids)
                                           (ic_tmp_ids ic))
        Linker.deleteFromLinkEnv new_names
        
        when (isStep step) $ setStepFlag
        case r of 
          Resume expr tid breakMVar statusMVar bindings 
              final_ids apStack info _ hist _ -> do
                withBreakAction (isStep step) (hsc_dflags hsc_env) 
                                        breakMVar statusMVar $ do
                status <- withInterruptsSentTo tid $ do
                             putMVar breakMVar ()
                                      -- this awakens the stopped thread...
                             takeMVar statusMVar
                                      -- and wait for the result 
                let hist' = 
                     case info of 
                       Nothing -> fromListBL 50 hist
                       Just i -> mkHistory hsc_env apStack i `consBL` 
                                                        fromListBL 50 hist
                case step of
                  RunAndLogSteps -> 
                        traceRunStatus expr ref bindings final_ids
                                       breakMVar statusMVar status hist'
                  _other ->
                        handleRunStatus expr ref bindings final_ids
                                        breakMVar statusMVar status hist'

back :: Session -> IO ([Name], Int, SrcSpan)
back  = moveHist (+1)

forward :: Session -> IO ([Name], Int, SrcSpan)
forward  = moveHist (subtract 1)
{'fraction_non_alphanumeric': 0.07483032997893752, 'fraction_numerical': 0.002808331383103206, 'mean_word_length': 1.843773396556027, 'pattern_counts': {'":': 0, '<': 56, '<?xml version=': 0, '>': 133, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 64, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '905625', 'n_tokens_mistral': 9236, 'n_tokens_neox': 8808, 'n_words': 3254}