{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}

{-# OPTIONS -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly

-----------------------------------------------------------------------------
--
-- GHC Interactive User Interface
--
-- (c) The GHC Team 2005-2006
--
-----------------------------------------------------------------------------

module Clash.GHCi.UI (
        interactiveUI,
        GhciSettings(..),
        defaultGhciSettings,
        ghciCommands,
        ghciWelcomeMsg,
        makeHDL
    ) where

#include "HsVersions.h"

-- GHCi
import qualified Clash.GHCi.UI.Monad as GhciMonad ( args, runStmt, runDecls' )
import Clash.GHCi.UI.Monad hiding ( args, runStmt )
import Clash.GHCi.UI.Tags
import Clash.GHCi.UI.Info
import Debugger

-- The GHC interface
import GHCi
import GHCi.RemoteTypes
import GHCi.BreakArray
import DynFlags
import ErrUtils hiding (traceCmd)
import Finder
import GhcMonad ( modifySession )
import qualified GHC
import GHC ( LoadHowMuch(..), Target(..),  TargetId(..), InteractiveImport(..),
             TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
             GetDocsFailure(..),
             getModuleGraph, handleSourceError )
import HscMain (hscParseDeclsWithLocation, hscParseStmtWithLocation)
import HsImpExp
import HsSyn
import HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
                  setInteractivePrintName, hsc_dflags, msObjFilePath, runInteractiveHsc )
import Module
import Name
import Packages ( trusted, getPackageDetails, getInstalledPackageDetails,
                  listVisibleModuleNames, pprFlag )
import IfaceSyn ( showToHeader )
import PprTyThing
import PrelNames
import RdrName ( getGRE_NameQualifier_maybes, getRdrName )
import SrcLoc
import qualified Lexer

import StringBuffer
import Outputable hiding ( printForUser, printForUserPartWay )

import DynamicLoading ( initializePlugins )

-- Other random utilities
import BasicTypes hiding ( isTopLevel )
import Digraph
import Encoding
import FastString
import Linker
import Maybes ( orElse, expectJust )
import NameSet
import Panic hiding ( showException )
import Util
import qualified GHC.LanguageExtensions as LangExt
import Bag (unitBag)

-- Haskell Libraries
import System.Console.Haskeline as Haskeline

import Control.Applicative hiding (empty)
import Control.DeepSeq (deepseq)
import Control.Monad as Monad
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except

import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Function
import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
                   partition, sort, sortBy )
import qualified Data.Set as S
import Data.Maybe
import Data.Map (Map)
import qualified Data.Map as M
import Data.Time.LocalTime ( getZonedTime )
import Data.Time.Format ( formatTime, defaultTimeLocale )
import Data.Version ( showVersion )
import Prelude hiding ((<>))

import Exception hiding (catch)
import Foreign hiding (void)
import GHC.Stack hiding (SrcLoc(..))

import System.Directory
import System.Environment
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.Info
import System.IO
import System.IO.Error
import System.IO.Unsafe ( unsafePerformIO )
import System.Process
import Text.Printf
import Text.Read ( readMaybe )
import Text.Read.Lex (isSymbolChar)

import Unsafe.Coerce

#if !defined(mingw32_HOST_OS)
import System.Posix hiding ( getEnv )
#else
import qualified System.Win32
#endif

import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
import GHC.IO.Handle ( hFlushAll )
import GHC.TopHandler ( topHandler )

import Clash.GHCi.Leak

-- clash additions
import qualified Clash.Backend
import           Clash.Backend.SystemVerilog (SystemVerilogState)
import           Clash.Backend.VHDL (VHDLState)
import           Clash.Backend.Verilog (VerilogState)
import qualified Clash.Driver
import           Clash.Driver.Types (ClashOpts(..))
import           Clash.GHC.Evaluator
import           Clash.GHC.GenerateBindings
import           Clash.GHC.NetlistTypes
import           Clash.GHCi.Common
import           Clash.Netlist.BlackBox.Types (HdlSyn)
import           Clash.Util (clashLibVersion, reportTimeDiff)
import qualified Data.Time.Clock as Clock
import qualified Paths_clash_ghc

import           Clash.Annotations.BitRepresentation.Internal (buildCustomReprs)

-----------------------------------------------------------------------------

data GhciSettings = GhciSettings {
        GhciSettings -> [Command]
availableCommands :: [Command],
        GhciSettings -> String
shortHelpText     :: String,
        GhciSettings -> String
fullHelpText      :: String,
        GhciSettings -> PromptFunction
defPrompt         :: PromptFunction,
        GhciSettings -> PromptFunction
defPromptCont     :: PromptFunction
    }

defaultGhciSettings :: IORef ClashOpts -> GhciSettings
defaultGhciSettings :: IORef ClashOpts -> GhciSettings
defaultGhciSettings opts :: IORef ClashOpts
opts =
    GhciSettings :: [Command]
-> String
-> String
-> PromptFunction
-> PromptFunction
-> GhciSettings
GhciSettings {
        availableCommands :: [Command]
availableCommands = IORef ClashOpts -> [Command]
ghciCommands IORef ClashOpts
opts,
        shortHelpText :: String
shortHelpText     = String
defShortHelpText,
        defPrompt :: PromptFunction
defPrompt         = PromptFunction
default_prompt,
        defPromptCont :: PromptFunction
defPromptCont     = PromptFunction
default_prompt_cont,
        fullHelpText :: String
fullHelpText      = String
defFullHelpText
    }

ghciWelcomeMsg :: String
ghciWelcomeMsg :: String
ghciWelcomeMsg = "Clashi, version " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Version -> String
Data.Version.showVersion Version
Paths_clash_ghc.version String -> String -> String
forall a. [a] -> [a] -> [a]
++
                 " (using clash-lib, version " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Version -> String
Data.Version.showVersion Version
clashLibVersion String -> String -> String
forall a. [a] -> [a] -> [a]
++
                 "):\nhttp://www.clash-lang.org/  :? for help"

ghciCommands :: IORef ClashOpts -> [Command]
ghciCommands :: IORef ClashOpts -> [Command]
ghciCommands opts :: IORef ClashOpts
opts = ((String, String -> InputT GHCi Bool, CompletionFunc GHCi)
 -> Command)
-> [(String, String -> InputT GHCi Bool, CompletionFunc GHCi)]
-> [Command]
forall a b. (a -> b) -> [a] -> [b]
map (String, String -> InputT GHCi Bool, CompletionFunc GHCi)
-> Command
mkCmd [
  -- Hugs users are accustomed to :e, so make sure it doesn't overlap
  ("?",         (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
help,                 CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("add",       ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths [String] -> InputT GHCi ()
addModule,       CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("abandon",   (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
abandonCmd,           CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("break",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
breakCmd,             CompletionFunc GHCi
completeIdentifier),
  ("back",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
backCmd,              CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("browse",    (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
browseCmd Bool
False),   CompletionFunc GHCi
completeModule),
  ("browse!",   (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
browseCmd Bool
True),    CompletionFunc GHCi
completeModule),
  ("cd",        (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
changeDirectory,     CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("check",     (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
checkModule,         CompletionFunc GHCi
completeHomeModule),
  ("continue",  (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
continueCmd,          CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("cmd",       (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
cmdCmd,               CompletionFunc GHCi
completeExpression),
  ("ctags",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
createCTagsWithLineNumbersCmd, CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("ctags!",    (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
createCTagsWithRegExesCmd, CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("def",       (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing (Bool -> String -> GHCi ()
defineMacro Bool
False),  CompletionFunc GHCi
completeExpression),
  ("def!",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing (Bool -> String -> GHCi ()
defineMacro Bool
True),   CompletionFunc GHCi
completeExpression),
  ("delete",    (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
deleteCmd,            CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("doc",       (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
docCmd,              CompletionFunc GHCi
completeIdentifier),
  ("edit",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
editFile,            CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("etags",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
createETagsFileCmd,   CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("force",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
forceCmd,             CompletionFunc GHCi
completeExpression),
  ("forward",   (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
forwardCmd,           CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("help",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
help,                 CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("history",   (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
historyCmd,           CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("info",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
info Bool
False),        CompletionFunc GHCi
completeIdentifier),
  ("info!",     (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
info Bool
True),         CompletionFunc GHCi
completeIdentifier),
  ("issafe",    (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
isSafeCmd,           CompletionFunc GHCi
completeModule),
  ("kind",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
kindOfType Bool
False),  CompletionFunc GHCi
completeIdentifier),
  ("kind!",     (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (Bool -> String -> InputT GHCi ()
kindOfType Bool
True),   CompletionFunc GHCi
completeIdentifier),
  ("load",      ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths [String] -> InputT GHCi ()
loadModule_,     CompletionFunc GHCi
completeHomeModuleOrFile),
  ("load!",     ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths [String] -> InputT GHCi ()
loadModuleDefer, CompletionFunc GHCi
completeHomeModuleOrFile),
  ("list",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
listCmd,             CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("module",    (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
moduleCmd,            CompletionFunc GHCi
completeSetModule),
  ("main",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
runMain,              CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("print",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
printCmd,             CompletionFunc GHCi
completeExpression),
  ("quit",      String -> InputT GHCi Bool
quit,                           CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("reload",    (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
reloadModule,        CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("reload!",   (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
reloadModuleDefer,   CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("run",       (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
runRun,               CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("script",    (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
scriptCmd,           CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("set",       (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
setCmd,               CompletionFunc GHCi
completeSetOptions),
  ("seti",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
setiCmd,              CompletionFunc GHCi
completeSeti),
  ("show",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
showCmd,              CompletionFunc GHCi
completeShowOptions),
  ("showi",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
showiCmd,             CompletionFunc GHCi
completeShowiOptions),
  ("sprint",    (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
sprintCmd,            CompletionFunc GHCi
completeExpression),
  ("step",      (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
stepCmd,              CompletionFunc GHCi
completeIdentifier),
  ("steplocal", (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
stepLocalCmd,         CompletionFunc GHCi
completeIdentifier),
  ("stepmodule",(String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
stepModuleCmd,        CompletionFunc GHCi
completeIdentifier),
  ("type",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
typeOfExpr,          CompletionFunc GHCi
completeExpression),
  ("trace",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
traceCmd,             CompletionFunc GHCi
completeExpression),
  ("unadd",     ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths [String] -> InputT GHCi ()
unAddModule,     CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename),
  ("undef",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
undefineMacro,        CompletionFunc GHCi
completeMacro),
  ("unset",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
unsetOptions,         CompletionFunc GHCi
completeSetOptions),
  ("where",     (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
whereCmd,             CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion),
  ("vhdl",      ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths (IORef ClashOpts -> [String] -> InputT GHCi ()
makeVHDL IORef ClashOpts
opts),        CompletionFunc GHCi
completeHomeModuleOrFile),
  ("verilog",   ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths (IORef ClashOpts -> [String] -> InputT GHCi ()
makeVerilog IORef ClashOpts
opts),     CompletionFunc GHCi
completeHomeModuleOrFile),
  ("systemverilog",   ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths (IORef ClashOpts -> [String] -> InputT GHCi ()
makeSystemVerilog IORef ClashOpts
opts),     CompletionFunc GHCi
completeHomeModuleOrFile)
  ] [Command] -> [Command] -> [Command]
forall a. [a] -> [a] -> [a]
++ ((String, String -> InputT GHCi Bool) -> Command)
-> [(String, String -> InputT GHCi Bool)] -> [Command]
forall a b. (a -> b) -> [a] -> [b]
map (String, String -> InputT GHCi Bool) -> Command
mkCmdHidden [ -- hidden commands
  ("all-types", (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
allTypesCmd),
  ("complete",  (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing String -> GHCi ()
completeCmd),
  ("loc-at",    (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
locAtCmd),
  ("type-at",   (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
typeAtCmd),
  ("uses",      (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' String -> InputT GHCi ()
usesCmd)
  ]
 where
  mkCmd :: (String, String -> InputT GHCi Bool, CompletionFunc GHCi)
-> Command
mkCmd (n :: String
n,a :: String -> InputT GHCi Bool
a,c :: CompletionFunc GHCi
c) = Command :: String
-> (String -> InputT GHCi Bool)
-> Bool
-> CompletionFunc GHCi
-> Command
Command { cmdName :: String
cmdName = String
n
                          , cmdAction :: String -> InputT GHCi Bool
cmdAction = String -> InputT GHCi Bool
a
                          , cmdHidden :: Bool
cmdHidden = Bool
False
                          , cmdCompletionFunc :: CompletionFunc GHCi
cmdCompletionFunc = CompletionFunc GHCi
c
                          }

  mkCmdHidden :: (String, String -> InputT GHCi Bool) -> Command
mkCmdHidden (n :: String
n,a :: String -> InputT GHCi Bool
a) = Command :: String
-> (String -> InputT GHCi Bool)
-> Bool
-> CompletionFunc GHCi
-> Command
Command { cmdName :: String
cmdName = String
n
                              , cmdAction :: String -> InputT GHCi Bool
cmdAction = String -> InputT GHCi Bool
a
                              , cmdHidden :: Bool
cmdHidden = Bool
True
                              , cmdCompletionFunc :: CompletionFunc GHCi
cmdCompletionFunc = CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion
                              }

-- We initialize readline (in the interactiveUI function) to use
-- word_break_chars as the default set of completion word break characters.
-- This can be overridden for a particular command (for example, filename
-- expansion shouldn't consider '/' to be a word break) by setting the third
-- entry in the Command tuple above.
--
-- NOTE: in order for us to override the default correctly, any custom entry
-- must be a SUBSET of word_break_chars.
word_break_chars :: String
word_break_chars :: String
word_break_chars = String
spaces String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
specials String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
symbols

symbols, specials, spaces :: String
symbols :: String
symbols = "!#$%&*+/<=>?@\\^|-~"
specials :: String
specials = "(),;[]`{}"
spaces :: String
spaces = " \t\n"

flagWordBreakChars :: String
flagWordBreakChars :: String
flagWordBreakChars = " \t\n"


keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
keepGoing :: (String -> GHCi ()) -> String -> InputT GHCi Bool
keepGoing a :: String -> GHCi ()
a str :: String
str = (String -> InputT GHCi ()) -> String -> InputT GHCi Bool
forall (m :: * -> *).
Monad m =>
(String -> m ()) -> String -> m Bool
keepGoing' (GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi () -> InputT GHCi ())
-> (String -> GHCi ()) -> String -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> GHCi ()
a) String
str

keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
keepGoing' :: (String -> m ()) -> String -> m Bool
keepGoing' a :: String -> m ()
a str :: String
str = String -> m ()
a String
str m () -> m Bool -> m Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> m Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
keepGoingPaths :: ([String] -> InputT GHCi ()) -> String -> InputT GHCi Bool
keepGoingPaths a :: [String] -> InputT GHCi ()
a str :: String
str
 = do case String -> Either String [String]
toArgs String
str of
          Left err :: String
err -> IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err
          Right args :: [String]
args -> [String] -> InputT GHCi ()
a [String]
args
      Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

defShortHelpText :: String
defShortHelpText :: String
defShortHelpText = "use :? for help.\n"

defFullHelpText :: String
defFullHelpText :: String
defFullHelpText =
  " Commands available from the prompt:\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   <statement>                 evaluate/run <statement>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :                           repeat last command\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :{\\n ..lines.. \\n:}\\n       multiline command\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :add [*]<module> ...        add module(s) to the current target set\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :browse[!] [[*]<mod>]       display the names defined by module <mod>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: more details; *: all top-level names)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :cd <dir>                   change directory to <dir>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :cmd <expr>                 run the commands returned by <expr>::IO String\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :complete <dom> [<rng>] <s> list completions for partial input string\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :ctags[!] [<file>]          create tags file <file> for Vi (default: \"tags\")\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: use regex instead of line number)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :def <cmd> <expr>           define command :<cmd> (later defined command has\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               precedence, ::<cmd> is always a builtin command)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :doc <name>                 display docs for the given name (experimental)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :edit <file>                edit file\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :edit                       edit last module\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :etags [<file>]             create tags file <file> for Emacs (default: \"TAGS\")\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :help, :?                   display this list of commands\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :info[!] [<name> ...]       display information about the given names\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: do not filter instances)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :issafe [<mod>]             display safe haskell information of module <mod>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :kind[!] <type>             show the kind of <type>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: also print the normalised type)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :load[!] [*]<module> ...    load module(s) and their dependents\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: defer type errors)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :main [<arguments> ...]     run the main function with the given arguments\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :module [+/-] [*]<mod> ...  set the context for expression evaluation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :quit                       exit GHCi\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :reload[!]                  reload the current module set\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                               (!: defer type errors)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :run function [<arguments> ...] run the function with the given arguments\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :script <file>              run the script <file>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :type <expr>                show the type of <expr>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :type +d <expr>             show the type of <expr>, defaulting type variables\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :type +v <expr>             show the type of <expr>, with its specified tyvars\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :unadd <module> ...         remove module(s) from the current target set\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :undef <cmd>                undefine user-defined command :<cmd>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :!<command>                 run the shell command <command>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :vhdl                       synthesize currently loaded module to vhdl\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :vhdl [<module>]            synthesize specified modules/files to vhdl\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :verilog                    synthesize currently loaded module to verilog\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :verilog [<module>]         synthesize specified modules/files to verilog\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :systemverilog              synthesize currently loaded module to systemverilog\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :systemverilog [<module>]   synthesize specified modules/files to systemverilog\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  " -- Commands for debugging:\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :abandon                    at a breakpoint, abandon current computation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :back [<n>]                 go back in the history N steps (after :trace)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :break [<mod>] <l> [<col>]  set a breakpoint at the specified location\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :break <name>               set a breakpoint on the specified function\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :continue                   resume after a breakpoint\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :delete <number>            delete the specified breakpoint\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :delete *                   delete all breakpoints\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :force <expr>               print <expr>, forcing unevaluated parts\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :forward [<n>]              go forward in the history N step s(after :back)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :history [<n>]              after :trace, show the execution history\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :list                       show the source code around current breakpoint\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :list <identifier>          show the source code for <identifier>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :list [<module>] <line>     show the source code around line number <line>\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :print [<name> ...]         show a value without forcing its computation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :sprint [<name> ...]        simplified version of :print\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :step                       single-step after stopping at a breakpoint\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :step <expr>                single-step into <expr>\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :steplocal                  single-step within the current top-level binding\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :stepmodule                 single-step restricted to the current module\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :trace                      trace after stopping at a breakpoint\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :trace <expr>               evaluate <expr> with tracing on (see :history)\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++

  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  " -- Commands for changing settings:\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set <option> ...           set options\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :seti <option> ...          set options for interactive evaluation only\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set args <arg> ...         set the arguments returned by System.getArgs\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set prog <progname>        set the value returned by System.getProgName\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set prompt <prompt>        set the prompt used in GHCi\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set prompt-cont <prompt>   set the continuation prompt used in GHCi\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set prompt-function <expr> set the function to handle the prompt\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set prompt-cont-function <expr>" String -> String -> String
forall a. [a] -> [a] -> [a]
++
                     "set the function to handle the continuation prompt\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set editor <cmd>           set the command used for :edit\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :set stop [<n>] <cmd>       set the command to run when a breakpoint is hit\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :unset <option> ...         unset options\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "  Options for ':set' and ':unset':\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    +m            allow multiline commands\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    +r            revert top-level expressions after each evaluation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    +s            print timing/memory stats after each evaluation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    +t            print type after evaluation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    +c            collect type/location info after loading modules\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "    -<flags>      most GHC command line flags can also be set here\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                         (eg. -v2, -XFlexibleInstances, etc.)\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                    for GHCi-specific flags, see User's Guide,\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                    Flag reference, Interactive-mode options\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  " -- Commands for displaying information:\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show bindings              show the current bindings made at the prompt\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show breaks                show the active breakpoints\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show context               show the breakpoint context\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show imports               show the current imports\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show linker                show current linker state\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show modules               show the currently loaded modules\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show packages              show the currently active package flags\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show paths                 show the currently active search paths\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show language              show the currently active language flags\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show targets               show the current set of targets\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :show <setting>             show value of <setting>, which is one of\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "                                  [args, prog, editor, stop]\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "   :showi language             show language flags for interactive evaluation\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
  "\n"

findEditor :: IO String
findEditor :: IO String
findEditor = do
  String -> IO String
getEnv "EDITOR"
    IO String -> (IOException -> IO String) -> IO String
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \_ -> do
#if defined(mingw32_HOST_OS)
        win <- System.Win32.getWindowsDirectory
        return (win </> "notepad.exe")
#else
        String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return ""
#endif

default_progname, default_stop :: String
default_progname :: String
default_progname = "<interactive>"
default_stop :: String
default_stop = ""

default_prompt, default_prompt_cont :: PromptFunction
default_prompt :: PromptFunction
default_prompt = String -> PromptFunction
generatePromptFunctionFromString "%s> "
default_prompt_cont :: PromptFunction
default_prompt_cont = String -> PromptFunction
generatePromptFunctionFromString "%s| "

default_args :: [String]
default_args :: [String]
default_args = []

interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
              -> Ghc ()
interactiveUI :: GhciSettings -> [(String, Maybe Phase)] -> Maybe [String] -> Ghc ()
interactiveUI config :: GhciSettings
config srcs :: [(String, Maybe Phase)]
srcs maybe_exprs :: Maybe [String]
maybe_exprs = do
   -- HACK! If we happen to get into an infinite loop (eg the user
   -- types 'let x=x in x' at the prompt), then the thread will block
   -- on a blackhole, and become unreachable during GC.  The GC will
   -- detect that it is unreachable and send it the NonTermination
   -- exception.  However, since the thread is unreachable, everything
   -- it refers to might be finalized, including the standard Handles.
   -- This sounds like a bug, but we don't have a good solution right
   -- now.
   StablePtr Handle
_ <- IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (StablePtr Handle) -> Ghc (StablePtr Handle))
-> IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall a b. (a -> b) -> a -> b
$ Handle -> IO (StablePtr Handle)
forall a. a -> IO (StablePtr a)
newStablePtr Handle
stdin
   StablePtr Handle
_ <- IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (StablePtr Handle) -> Ghc (StablePtr Handle))
-> IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall a b. (a -> b) -> a -> b
$ Handle -> IO (StablePtr Handle)
forall a. a -> IO (StablePtr a)
newStablePtr Handle
stdout
   StablePtr Handle
_ <- IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (StablePtr Handle) -> Ghc (StablePtr Handle))
-> IO (StablePtr Handle) -> Ghc (StablePtr Handle)
forall a b. (a -> b) -> a -> b
$ Handle -> IO (StablePtr Handle)
forall a. a -> IO (StablePtr a)
newStablePtr Handle
stderr

    -- Initialise buffering for the *interpreted* I/O system
   (nobuffering :: ForeignHValue
nobuffering, flush :: ForeignHValue
flush) <- Ghc (ForeignHValue, ForeignHValue)
initInterpBuffering

   -- The initial set of DynFlags used for interactive evaluation is the same
   -- as the global DynFlags, plus -XExtendedDefaultRules and
   -- -XNoMonomorphismRestriction.
   -- See note [Changing language extensions for interactive evaluation] #10857
   DynFlags
dflags <- Ghc DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
   let dflags' :: DynFlags
dflags' = (Extension
-> (DynFlags -> Extension -> DynFlags) -> DynFlags -> DynFlags
xopt_set_unlessExplSpec
                      Extension
LangExt.ExtendedDefaultRules DynFlags -> Extension -> DynFlags
xopt_set)
               (DynFlags -> DynFlags)
-> (DynFlags -> DynFlags) -> DynFlags -> DynFlags
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Extension
-> (DynFlags -> Extension -> DynFlags) -> DynFlags -> DynFlags
xopt_set_unlessExplSpec
                      Extension
LangExt.MonomorphismRestriction DynFlags -> Extension -> DynFlags
xopt_unset)
               (DynFlags -> DynFlags) -> DynFlags -> DynFlags
forall a b. (a -> b) -> a -> b
$ DynFlags
dflags
   DynFlags -> Ghc ()
forall (m :: * -> *). GhcMonad m => DynFlags -> m ()
GHC.setInteractiveDynFlags DynFlags
dflags'

   IORef [(FastString, Int)]
lastErrLocationsRef <- IO (IORef [(FastString, Int)]) -> Ghc (IORef [(FastString, Int)])
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (IORef [(FastString, Int)]) -> Ghc (IORef [(FastString, Int)]))
-> IO (IORef [(FastString, Int)])
-> Ghc (IORef [(FastString, Int)])
forall a b. (a -> b) -> a -> b
$ [(FastString, Int)] -> IO (IORef [(FastString, Int)])
forall a. a -> IO (IORef a)
newIORef []
   DynFlags
progDynFlags <- Ghc DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getProgramDynFlags
   [InstalledUnitId]
_ <- DynFlags -> Ghc [InstalledUnitId]
forall (m :: * -> *). GhcMonad m => DynFlags -> m [InstalledUnitId]
GHC.setProgramDynFlags (DynFlags -> Ghc [InstalledUnitId])
-> DynFlags -> Ghc [InstalledUnitId]
forall a b. (a -> b) -> a -> b
$
      -- Ensure we don't override the user's log action lest we break
      -- -ddump-json (#14078)
      DynFlags
progDynFlags { log_action :: LogAction
log_action = LogAction -> IORef [(FastString, Int)] -> LogAction
ghciLogAction (DynFlags -> LogAction
log_action DynFlags
progDynFlags)
                                                IORef [(FastString, Int)]
lastErrLocationsRef }

   Bool -> Ghc () -> Ghc ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Maybe [String] -> Bool
forall a. Maybe a -> Bool
isNothing Maybe [String]
maybe_exprs) (Ghc () -> Ghc ()) -> Ghc () -> Ghc ()
forall a b. (a -> b) -> a -> b
$ do
        -- Only for GHCi (not runghc and ghc -e):

        -- Turn buffering off for the compiled program's stdout/stderr
        ForeignHValue -> Ghc ()
forall (m :: * -> *). GhcMonad m => ForeignHValue -> m ()
turnOffBuffering_ ForeignHValue
nobuffering
        -- Turn buffering off for GHCi's stdout
        IO () -> Ghc ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Ghc ()) -> IO () -> Ghc ()
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hFlush Handle
stdout
        IO () -> Ghc ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Ghc ()) -> IO () -> Ghc ()
forall a b. (a -> b) -> a -> b
$ Handle -> BufferMode -> IO ()
hSetBuffering Handle
stdout BufferMode
NoBuffering
        -- We don't want the cmd line to buffer any input that might be
        -- intended for the program, so unbuffer stdin.
        IO () -> Ghc ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Ghc ()) -> IO () -> Ghc ()
forall a b. (a -> b) -> a -> b
$ Handle -> BufferMode -> IO ()
hSetBuffering Handle
stdin BufferMode
NoBuffering
        IO () -> Ghc ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Ghc ()) -> IO () -> Ghc ()
forall a b. (a -> b) -> a -> b
$ Handle -> BufferMode -> IO ()
hSetBuffering Handle
stderr BufferMode
NoBuffering
#if defined(mingw32_HOST_OS)
        -- On Unix, stdin will use the locale encoding.  The IO library
        -- doesn't do this on Windows (yet), so for now we use UTF-8,
        -- for consistency with GHC 6.10 and to make the tests work.
        liftIO $ hSetEncoding stdin utf8
#endif

   String
default_editor <- IO String -> Ghc String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> Ghc String) -> IO String -> Ghc String
forall a b. (a -> b) -> a -> b
$ IO String
findEditor
   ForeignHValue
eval_wrapper <- String -> [String] -> Ghc ForeignHValue
forall (m :: * -> *).
GhcMonad m =>
String -> [String] -> m ForeignHValue
mkEvalWrapper String
default_progname [String]
default_args
   let prelude_import :: ImportDecl (GhcPass p)
prelude_import = ModuleName -> ImportDecl (GhcPass p)
forall (p :: Pass). ModuleName -> ImportDecl (GhcPass p)
simpleImportDecl ModuleName
preludeModuleName
   GHCi () -> GHCiState -> Ghc ()
forall a. GHCi a -> GHCiState -> Ghc a
startGHCi ([(String, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi [(String, Maybe Phase)]
srcs Maybe [String]
maybe_exprs)
        $WGHCiState :: String
-> [String]
-> ForeignHValue
-> PromptFunction
-> PromptFunction
-> String
-> String
-> [GHCiOption]
-> Int
-> Int
-> [(Int, BreakLocation)]
-> ModuleEnv TickArray
-> [Command]
-> [Command]
-> Maybe Command
-> (InputT GHCi CommandResult -> InputT GHCi (Maybe Bool))
-> [String]
-> [InteractiveImport]
-> [InteractiveImport]
-> [ImportDecl GhcPs]
-> [ImportDecl GhcPs]
-> Bool
-> String
-> String
-> IORef [(FastString, Int)]
-> Map ModuleName ModInfo
-> ForeignHValue
-> ForeignHValue
-> GHCiState
GHCiState{ progname :: String
progname           = String
default_progname,
                   args :: [String]
args               = [String]
default_args,
                   evalWrapper :: ForeignHValue
evalWrapper        = ForeignHValue
eval_wrapper,
                   prompt :: PromptFunction
prompt             = GhciSettings -> PromptFunction
defPrompt GhciSettings
config,
                   prompt_cont :: PromptFunction
prompt_cont        = GhciSettings -> PromptFunction
defPromptCont GhciSettings
config,
                   stop :: String
stop               = String
default_stop,
                   editor :: String
editor             = String
default_editor,
                   options :: [GHCiOption]
options            = [],
                   -- We initialize line number as 0, not 1, because we use
                   -- current line number while reporting errors which is
                   -- incremented after reading a line.
                   line_number :: Int
line_number        = 0,
                   break_ctr :: Int
break_ctr          = 0,
                   breaks :: [(Int, BreakLocation)]
breaks             = [],
                   tickarrays :: ModuleEnv TickArray
tickarrays         = ModuleEnv TickArray
forall a. ModuleEnv a
emptyModuleEnv,
                   ghci_commands :: [Command]
ghci_commands      = GhciSettings -> [Command]
availableCommands GhciSettings
config,
                   ghci_macros :: [Command]
ghci_macros        = [],
                   last_command :: Maybe Command
last_command       = Maybe Command
forall a. Maybe a
Nothing,
                   cmd_wrapper :: InputT GHCi CommandResult -> InputT GHCi (Maybe Bool)
cmd_wrapper        = (CommandResult -> InputT GHCi (Maybe Bool)
forall (m :: * -> *).
MonadException m =>
CommandResult -> m (Maybe Bool)
cmdSuccess (CommandResult -> InputT GHCi (Maybe Bool))
-> InputT GHCi CommandResult -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<<),
                   cmdqueue :: [String]
cmdqueue           = [],
                   remembered_ctx :: [InteractiveImport]
remembered_ctx     = [],
                   transient_ctx :: [InteractiveImport]
transient_ctx      = [],
                   extra_imports :: [ImportDecl GhcPs]
extra_imports      = [],
                   prelude_imports :: [ImportDecl GhcPs]
prelude_imports    = [ImportDecl GhcPs
forall (p :: Pass). ImportDecl (GhcPass p)
prelude_import],
                   ghc_e :: Bool
ghc_e              = Maybe [String] -> Bool
forall a. Maybe a -> Bool
isJust Maybe [String]
maybe_exprs,
                   short_help :: String
short_help         = GhciSettings -> String
shortHelpText GhciSettings
config,
                   long_help :: String
long_help          = GhciSettings -> String
fullHelpText GhciSettings
config,
                   lastErrorLocations :: IORef [(FastString, Int)]
lastErrorLocations = IORef [(FastString, Int)]
lastErrLocationsRef,
                   mod_infos :: Map ModuleName ModInfo
mod_infos          = Map ModuleName ModInfo
forall k a. Map k a
M.empty,
                   flushStdHandles :: ForeignHValue
flushStdHandles    = ForeignHValue
flush,
                   noBuffering :: ForeignHValue
noBuffering        = ForeignHValue
nobuffering
                 }

   () -> Ghc ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

{-
Note [Changing language extensions for interactive evaluation]
--------------------------------------------------------------
GHCi maintains two sets of options:

- The "loading options" apply when loading modules
- The "interactive options" apply when evaluating expressions and commands
    typed at the GHCi prompt.

The loading options are mostly created in ghc/Main.hs:main' from the command
line flags. In the function ghc/GHCi/UI.hs:interactiveUI the loading options
are copied to the interactive options.

These interactive options (but not the loading options!) are supplemented
unconditionally by setting ExtendedDefaultRules ON and
MonomorphismRestriction OFF. The unconditional setting of these options
eventually overwrite settings already specified at the command line.

Therefore instead of unconditionally setting ExtendedDefaultRules and
NoMonomorphismRestriction for the interactive options, we use the function
'xopt_set_unlessExplSpec' to first check whether the extension has already
specified at the command line.

The ghci config file has not yet been processed.
-}

resetLastErrorLocations :: GHCi ()
resetLastErrorLocations :: GHCi ()
resetLastErrorLocations = do
    GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ IORef [(FastString, Int)] -> [(FastString, Int)] -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GHCiState -> IORef [(FastString, Int)]
lastErrorLocations GHCiState
st) []

ghciLogAction :: LogAction -> IORef [(FastString, Int)] ->  LogAction
ghciLogAction :: LogAction -> IORef [(FastString, Int)] -> LogAction
ghciLogAction old_log_action :: LogAction
old_log_action lastErrLocations :: IORef [(FastString, Int)]
lastErrLocations
              dflags :: DynFlags
dflags flag :: WarnReason
flag severity :: Severity
severity srcSpan :: SrcSpan
srcSpan style :: PprStyle
style msg :: MsgDoc
msg = do
    LogAction
old_log_action DynFlags
dflags WarnReason
flag Severity
severity SrcSpan
srcSpan PprStyle
style MsgDoc
msg
    case Severity
severity of
        SevError -> case SrcSpan
srcSpan of
            RealSrcSpan rsp :: RealSrcSpan
rsp -> IORef [(FastString, Int)]
-> ([(FastString, Int)] -> [(FastString, Int)]) -> IO ()
forall a. IORef a -> (a -> a) -> IO ()
modifyIORef IORef [(FastString, Int)]
lastErrLocations
                ([(FastString, Int)] -> [(FastString, Int)] -> [(FastString, Int)]
forall a. [a] -> [a] -> [a]
++ [(RealSrcLoc -> FastString
srcLocFile (RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
rsp), RealSrcLoc -> Int
srcLocLine (RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
rsp))])
            _ -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
        _ -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
withGhcAppData :: (String -> IO a) -> IO a -> IO a
withGhcAppData right :: String -> IO a
right left :: IO a
left = do
    Either IOException String
either_dir <- IO String -> IO (Either IOException String)
forall a. IO a -> IO (Either IOException a)
tryIO (String -> IO String
getAppUserDataDirectory "clash")
    case Either IOException String
either_dir of
        Right dir :: String
dir ->
            do Bool -> String -> IO ()
createDirectoryIfMissing Bool
False String
dir IO () -> (IOException -> IO ()) -> IO ()
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \_ -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
               String -> IO a
right String
dir
        _ -> IO a
left

runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi :: [(String, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi paths :: [(String, Maybe Phase)]
paths maybe_exprs :: Maybe [String]
maybe_exprs = do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let
   ignore_dot_ghci :: Bool
ignore_dot_ghci = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_IgnoreDotGhci DynFlags
dflags

   current_dir :: GHCi (Maybe String)
current_dir = Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just ".clashi")

   app_user_dir :: GHCi (Maybe String)
app_user_dir = IO (Maybe String) -> GHCi (Maybe String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe String) -> GHCi (Maybe String))
-> IO (Maybe String) -> GHCi (Maybe String)
forall a b. (a -> b) -> a -> b
$ (String -> IO (Maybe String))
-> IO (Maybe String) -> IO (Maybe String)
forall a. (String -> IO a) -> IO a -> IO a
withGhcAppData
                    (\dir :: String
dir -> Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just (String
dir String -> String -> String
</> "clashi.conf")))
                    (Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing)

   home_dir :: GHCi (Maybe String)
home_dir = do
    Either IOException String
either_dir <- IO (Either IOException String) -> GHCi (Either IOException String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException String)
 -> GHCi (Either IOException String))
-> IO (Either IOException String)
-> GHCi (Either IOException String)
forall a b. (a -> b) -> a -> b
$ IO String -> IO (Either IOException String)
forall a. IO a -> IO (Either IOException a)
tryIO (String -> IO String
getEnv "HOME")
    case Either IOException String
either_dir of
      Right home :: String
home -> Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just (String
home String -> String -> String
</> ".clashi"))
      _ -> Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing

   canonicalizePath' :: FilePath -> IO (Maybe FilePath)
   canonicalizePath' :: String -> IO (Maybe String)
canonicalizePath' fp :: String
fp = (String -> Maybe String) -> IO String -> IO (Maybe String)
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> Maybe String
forall a. a -> Maybe a
Just (String -> IO String
canonicalizePath String
fp)
                IO (Maybe String)
-> (IOException -> IO (Maybe String)) -> IO (Maybe String)
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \_ -> Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing

   sourceConfigFile :: FilePath -> GHCi ()
   sourceConfigFile :: String -> GHCi ()
sourceConfigFile file :: String
file = do
     Bool
exists <- IO Bool -> GHCi Bool
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> GHCi Bool) -> IO Bool -> GHCi Bool
forall a b. (a -> b) -> a -> b
$ String -> IO Bool
doesFileExist String
file
     Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
exists (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
       Either IOException Handle
either_hdl <- IO (Either IOException Handle) -> GHCi (Either IOException Handle)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException Handle)
 -> GHCi (Either IOException Handle))
-> IO (Either IOException Handle)
-> GHCi (Either IOException Handle)
forall a b. (a -> b) -> a -> b
$ IO Handle -> IO (Either IOException Handle)
forall a. IO a -> IO (Either IOException a)
tryIO (String -> IOMode -> IO Handle
openFile String
file IOMode
ReadMode)
       case Either IOException Handle
either_hdl of
         Left _e :: IOException
_e   -> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
         -- NOTE: this assumes that runInputT won't affect the terminal;
         -- can we assume this will always be the case?
         -- This would be a good place for runFileInputT.
         Right hdl :: Handle
hdl ->
             do Prefs -> Settings GHCi -> InputT GHCi () -> GHCi ()
forall (m :: * -> *) a.
MonadException m =>
Prefs -> Settings m -> InputT m a -> m a
runInputTWithPrefs Prefs
defaultPrefs Settings GHCi
forall (m :: * -> *). MonadIO m => Settings m
defaultSettings (InputT GHCi () -> GHCi ()) -> InputT GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$
                          InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands (InputT GHCi (Maybe String) -> InputT GHCi ())
-> InputT GHCi (Maybe String) -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> InputT GHCi (Maybe String)
fileLoop Handle
hdl
                IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> IO ()
hClose Handle
hdl IO () -> (IOException -> IO ()) -> IO ()
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \_ -> () -> IO ()
forall (m :: * -> *) a. Monad m => a -> m a
return ())
                -- Don't print a message if this is really ghc -e (#11478).
                -- Also, let the user silence the message with -v0
                -- (the default verbosity in GHCi is 1).
                Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Maybe [String] -> Bool
forall a. Maybe a -> Bool
isNothing Maybe [String]
maybe_exprs Bool -> Bool -> Bool
&& DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$
                  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn ("Loaded Clashi configuration from " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
file)

  --

  GHCi ()
setGHCContextFromGHCiState

  [String]
dot_cfgs <- if Bool
ignore_dot_ghci then [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return [] else do
    [String]
dot_files <- [Maybe String] -> [String]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe String] -> [String])
-> GHCi [Maybe String] -> GHCi [String]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [GHCi (Maybe String)] -> GHCi [Maybe String]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence [ GHCi (Maybe String)
current_dir, GHCi (Maybe String)
app_user_dir, GHCi (Maybe String)
home_dir ]
    IO [String] -> GHCi [String]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [String] -> GHCi [String]) -> IO [String] -> GHCi [String]
forall a b. (a -> b) -> a -> b
$ (String -> IO Bool) -> [String] -> IO [String]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM String -> IO Bool
checkFileAndDirPerms [String]
dot_files
  [Maybe String]
mdot_cfgs <- IO [Maybe String] -> GHCi [Maybe String]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [Maybe String] -> GHCi [Maybe String])
-> IO [Maybe String] -> GHCi [Maybe String]
forall a b. (a -> b) -> a -> b
$ (String -> IO (Maybe String)) -> [String] -> IO [Maybe String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> IO (Maybe String)
canonicalizePath' [String]
dot_cfgs

  let arg_cfgs :: [String]
arg_cfgs = [String] -> [String]
forall a. [a] -> [a]
reverse ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> [String]
ghciScripts DynFlags
dflags
    -- -ghci-script are collected in reverse order
    -- We don't require that a script explicitly added by -ghci-script
    -- is owned by the current user. (#6017)
  (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> GHCi ()
sourceConfigFile ([String] -> GHCi ()) -> [String] -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ ([Maybe String] -> [String]
forall a. [Maybe a] -> [a]
catMaybes [Maybe String]
mdot_cfgs) [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
arg_cfgs
    -- nub, because we don't want to read .ghci twice if the CWD is $HOME.

  -- Perform a :load for files given on the GHCi command line
  -- When in -e mode, if the load fails then we want to stop
  -- immediately rather than going on to evaluate the expression.
  Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([(String, Maybe Phase)] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(String, Maybe Phase)]
paths)) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
     SuccessFlag
ok <- (SomeException -> GHCi SuccessFlag)
-> GHCi SuccessFlag -> GHCi SuccessFlag
forall (m :: * -> *) a.
(HasDynFlags m, ExceptionMonad m) =>
(SomeException -> m a) -> m a -> m a
ghciHandle (\e :: SomeException
e -> do SomeException -> GHCi ()
showException SomeException
e; SuccessFlag -> GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
Failed) (GHCi SuccessFlag -> GHCi SuccessFlag)
-> GHCi SuccessFlag -> GHCi SuccessFlag
forall a b. (a -> b) -> a -> b
$
                -- TODO: this is a hack.
                Prefs
-> Settings GHCi -> InputT GHCi SuccessFlag -> GHCi SuccessFlag
forall (m :: * -> *) a.
MonadException m =>
Prefs -> Settings m -> InputT m a -> m a
runInputTWithPrefs Prefs
defaultPrefs Settings GHCi
forall (m :: * -> *). MonadIO m => Settings m
defaultSettings (InputT GHCi SuccessFlag -> GHCi SuccessFlag)
-> InputT GHCi SuccessFlag -> GHCi SuccessFlag
forall a b. (a -> b) -> a -> b
$
                    [(String, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule [(String, Maybe Phase)]
paths
     Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Maybe [String] -> Bool
forall a. Maybe a -> Bool
isJust Maybe [String]
maybe_exprs Bool -> Bool -> Bool
&& SuccessFlag -> Bool
failed SuccessFlag
ok) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$
        IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (ExitCode -> IO ()
forall a. ExitCode -> IO a
exitWith (Int -> ExitCode
ExitFailure 1))

  Maybe String -> Bool -> GHCi ()
installInteractivePrint (DynFlags -> Maybe String
interactivePrint DynFlags
dflags) (Maybe [String] -> Bool
forall a. Maybe a -> Bool
isJust Maybe [String]
maybe_exprs)

  -- if verbosity is greater than 0, or we are connected to a
  -- terminal, display the prompt in the interactive loop.
  Bool
is_tty <- IO Bool -> GHCi Bool
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> IO Bool
hIsTerminalDevice Handle
stdin)
  let show_prompt :: Bool
show_prompt = DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0 Bool -> Bool -> Bool
|| Bool
is_tty

  -- reset line number
  (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st :: GHCiState
st -> GHCiState
st{line_number :: Int
line_number=0}

  case Maybe [String]
maybe_exprs of
        Nothing ->
          do
            -- enter the interactive loop
            InputT GHCi () -> GHCi ()
forall a. InputT GHCi a -> GHCi a
runGHCiInput (InputT GHCi () -> GHCi ()) -> InputT GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands (InputT GHCi (Maybe String) -> InputT GHCi ())
-> InputT GHCi (Maybe String) -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine Bool
show_prompt Bool
is_tty
        Just exprs :: [String]
exprs -> do
            -- just evaluate the expression we were given
            [String] -> GHCi ()
enqueueCommands [String]
exprs
            let hdle :: SomeException -> GHCi b
hdle e :: SomeException
e = do GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
                            -- flush the interpreter's stdout/stderr on exit (#3890)
                            GHCi ()
flushInterpBuffers
                            -- Jump through some hoops to get the
                            -- current progname in the exception text:
                            -- <progname>: <exception>
                            IO b -> GHCi b
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO b -> GHCi b) -> IO b -> GHCi b
forall a b. (a -> b) -> a -> b
$ String -> IO b -> IO b
forall a. String -> IO a -> IO a
withProgName (GHCiState -> String
progname GHCiState
st)
                                   (IO b -> IO b) -> IO b -> IO b
forall a b. (a -> b) -> a -> b
$ SomeException -> IO b
forall a. SomeException -> IO a
topHandler SomeException
e
                                   -- this used to be topHandlerFastExit, see #2228
            Prefs -> Settings GHCi -> InputT GHCi () -> GHCi ()
forall (m :: * -> *) a.
MonadException m =>
Prefs -> Settings m -> InputT m a -> m a
runInputTWithPrefs Prefs
defaultPrefs Settings GHCi
forall (m :: * -> *). MonadIO m => Settings m
defaultSettings (InputT GHCi () -> GHCi ()) -> InputT GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
                -- make `ghc -e` exit nonzero on invalid input, see Trac #7962
                Maybe Bool
_ <- (SomeException -> GHCi Bool)
-> Maybe (GHCi ())
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runCommands' SomeException -> GHCi Bool
forall b. SomeException -> GHCi b
hdle
                     (GHCi () -> Maybe (GHCi ())
forall a. a -> Maybe a
Just (GHCi () -> Maybe (GHCi ())) -> GHCi () -> Maybe (GHCi ())
forall a b. (a -> b) -> a -> b
$ SomeException -> GHCi Any
forall b. SomeException -> GHCi b
hdle (ExitCode -> SomeException
forall e. Exception e => e -> SomeException
toException (ExitCode -> SomeException) -> ExitCode -> SomeException
forall a b. (a -> b) -> a -> b
$ Int -> ExitCode
ExitFailure 1) GHCi Any -> GHCi () -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ())
                     (Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing)
                () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

  -- and finally, exit
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Leaving Clashi."

runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput f :: InputT GHCi a
f = do
    DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
    let ghciHistory :: Bool
ghciHistory = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_GhciHistory DynFlags
dflags
    let localGhciHistory :: Bool
localGhciHistory = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_LocalGhciHistory DynFlags
dflags
    String
currentDirectory <- IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ IO String
getCurrentDirectory

    Maybe String
histFile <- case (Bool
ghciHistory, Bool
localGhciHistory) of
      (True, True) -> Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just (String
currentDirectory String -> String -> String
</> ".clashi_history"))
      (True, _) -> IO (Maybe String) -> GHCi (Maybe String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe String) -> GHCi (Maybe String))
-> IO (Maybe String) -> GHCi (Maybe String)
forall a b. (a -> b) -> a -> b
$ (String -> IO (Maybe String))
-> IO (Maybe String) -> IO (Maybe String)
forall a. (String -> IO a) -> IO a -> IO a
withGhcAppData
        (\dir :: String
dir -> Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just (String
dir String -> String -> String
</> "clashi_history"))) (Maybe String -> IO (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing)
      _ -> Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing

    Settings GHCi -> InputT GHCi a -> GHCi a
forall (m :: * -> *) a.
MonadException m =>
Settings m -> InputT m a -> m a
runInputT
        (CompletionFunc GHCi -> Settings GHCi -> Settings GHCi
forall (m :: * -> *). CompletionFunc m -> Settings m -> Settings m
setComplete CompletionFunc GHCi
ghciCompleteWord (Settings GHCi -> Settings GHCi) -> Settings GHCi -> Settings GHCi
forall a b. (a -> b) -> a -> b
$ Settings GHCi
forall (m :: * -> *). MonadIO m => Settings m
defaultSettings {historyFile :: Maybe String
historyFile = Maybe String
histFile})
        InputT GHCi a
f

-- | How to get the next input line from the user
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine show_prompt :: Bool
show_prompt is_tty :: Bool
is_tty
  | Bool
is_tty = do
    String
prmpt <- if Bool
show_prompt then GHCi String -> InputT GHCi String
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi String
mkPrompt else String -> InputT GHCi String
forall (m :: * -> *) a. Monad m => a -> m a
return ""
    Maybe String
r <- String -> InputT GHCi (Maybe String)
forall (m :: * -> *).
MonadException m =>
String -> InputT m (Maybe String)
getInputLine String
prmpt
    InputT GHCi ()
incrementLineNo
    Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
r
  | Bool
otherwise = do
    Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
show_prompt (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ GHCi String -> InputT GHCi String
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi String
mkPrompt InputT GHCi String -> (String -> InputT GHCi ()) -> InputT GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ())
-> (String -> IO ()) -> String -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStr
    Handle -> InputT GHCi (Maybe String)
fileLoop Handle
stdin

-- NOTE: We only read .ghci files if they are owned by the current user,
-- and aren't world writable (files owned by root are ok, see #9324).
-- Otherwise, we could be accidentally running code planted by
-- a malicious third party.

-- Furthermore, We only read ./.ghci if . is owned by the current user
-- and isn't writable by anyone else.  I think this is sufficient: we
-- don't need to check .. and ../.. etc. because "."  always refers to
-- the same directory while a process is running.

checkFileAndDirPerms :: FilePath -> IO Bool
checkFileAndDirPerms :: String -> IO Bool
checkFileAndDirPerms file :: String
file = do
  Bool
file_ok <- String -> IO Bool
checkPerms String
file
  -- Do not check dir perms when .ghci doesn't exist, otherwise GHCi will
  -- print some confusing and useless warnings in some cases (e.g. in
  -- travis). Note that we can't add a test for this, as all ghci tests should
  -- run with -ignore-dot-ghci, which means we never get here.
  if Bool
file_ok then String -> IO Bool
checkPerms (String -> String
getDirectory String
file) else Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
  where
  getDirectory :: String -> String
getDirectory f :: String
f = case String -> String
takeDirectory String
f of
    "" -> "."
    d :: String
d -> String
d

checkPerms :: FilePath -> IO Bool
#if defined(mingw32_HOST_OS)
checkPerms _ = return True
#else
checkPerms :: String -> IO Bool
checkPerms file :: String
file =
  (IOException -> IO Bool) -> IO Bool -> IO Bool
forall a. (IOException -> IO a) -> IO a -> IO a
handleIO (\_ -> Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False) (IO Bool -> IO Bool) -> IO Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ do
    FileStatus
st <- String -> IO FileStatus
getFileStatus String
file
    UserID
me <- IO UserID
getRealUserID
    let mode :: FileMode
mode = FileStatus -> FileMode
System.Posix.fileMode FileStatus
st
        ok :: Bool
ok = (FileStatus -> UserID
fileOwner FileStatus
st UserID -> UserID -> Bool
forall a. Eq a => a -> a -> Bool
== UserID
me Bool -> Bool -> Bool
|| FileStatus -> UserID
fileOwner FileStatus
st UserID -> UserID -> Bool
forall a. Eq a => a -> a -> Bool
== 0) Bool -> Bool -> Bool
&&
             FileMode
groupWriteMode FileMode -> FileMode -> Bool
forall a. Eq a => a -> a -> Bool
/= FileMode
mode FileMode -> FileMode -> FileMode
`intersectFileModes` FileMode
groupWriteMode Bool -> Bool -> Bool
&&
             FileMode
otherWriteMode FileMode -> FileMode -> Bool
forall a. Eq a => a -> a -> Bool
/= FileMode
mode FileMode -> FileMode -> FileMode
`intersectFileModes` FileMode
otherWriteMode
    Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
ok (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
      -- #8248: Improving warning to include a possible fix.
      String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "*** WARNING: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
file String -> String -> String
forall a. [a] -> [a] -> [a]
++
                 " is writable by someone else, IGNORING!" String -> String -> String
forall a. [a] -> [a] -> [a]
++
                 "\nSuggested fix: execute 'chmod go-w " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
file String -> String -> String
forall a. [a] -> [a] -> [a]
++ "'"
    Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
ok
#endif

incrementLineNo :: InputT GHCi ()
incrementLineNo :: InputT GHCi ()
incrementLineNo = (GHCiState -> GHCiState) -> InputT GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState GHCiState -> GHCiState
incLineNo
  where
    incLineNo :: GHCiState -> GHCiState
incLineNo st :: GHCiState
st = GHCiState
st { line_number :: Int
line_number = GHCiState -> Int
line_number GHCiState
st Int -> Int -> Int
forall a. Num a => a -> a -> a
+ 1 }

fileLoop :: Handle -> InputT GHCi (Maybe String)
fileLoop :: Handle -> InputT GHCi (Maybe String)
fileLoop hdl :: Handle
hdl = do
   Either IOException String
l <- IO (Either IOException String)
-> InputT GHCi (Either IOException String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException String)
 -> InputT GHCi (Either IOException String))
-> IO (Either IOException String)
-> InputT GHCi (Either IOException String)
forall a b. (a -> b) -> a -> b
$ IO String -> IO (Either IOException String)
forall a. IO a -> IO (Either IOException a)
tryIO (IO String -> IO (Either IOException String))
-> IO String -> IO (Either IOException String)
forall a b. (a -> b) -> a -> b
$ Handle -> IO String
hGetLine Handle
hdl
   case Either IOException String
l of
        Left e :: IOException
e | IOException -> Bool
isEOFError IOException
e              -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
               | -- as we share stdin with the program, the program
                 -- might have already closed it, so we might get a
                 -- handle-closed exception. We therefore catch that
                 -- too.
                 IOException -> Bool
isIllegalOperation IOException
e      -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
               | IOErrorType
InvalidArgument <- IOErrorType
etype  -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
               | Bool
otherwise                 -> IO (Maybe String) -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Maybe String) -> InputT GHCi (Maybe String))
-> IO (Maybe String) -> InputT GHCi (Maybe String)
forall a b. (a -> b) -> a -> b
$ IOException -> IO (Maybe String)
forall a. IOException -> IO a
ioError IOException
e
                where etype :: IOErrorType
etype = IOException -> IOErrorType
ioeGetErrorType IOException
e
                -- treat InvalidArgument in the same way as EOF:
                -- this can happen if the user closed stdin, or
                -- perhaps did getContents which closes stdin at
                -- EOF.
        Right l' :: String
l' -> do
           InputT GHCi ()
incrementLineNo
           Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just String
l')

formatCurrentTime :: String -> IO String
formatCurrentTime :: String -> IO String
formatCurrentTime format :: String
format =
  IO ZonedTime
getZonedTime IO ZonedTime -> (ZonedTime -> IO String) -> IO String
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> IO String)
-> (ZonedTime -> String) -> ZonedTime -> IO String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TimeLocale -> String -> ZonedTime -> String
forall t. FormatTime t => TimeLocale -> String -> t -> String
formatTime TimeLocale
defaultTimeLocale String
format)

getUserName :: IO String
getUserName :: IO String
getUserName = do
#if defined(mingw32_HOST_OS)
  getEnv "USERNAME"
    `catchIO` \e -> do
      putStrLn $ show e
      return ""
#else
  IO String
getLoginName
#endif

getInfoForPrompt :: GHCi (SDoc, [String], Int)
getInfoForPrompt :: GHCi (MsgDoc, [String], Int)
getInfoForPrompt = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  [InteractiveImport]
imports <- GHCi [InteractiveImport]
forall (m :: * -> *). GhcMonad m => m [InteractiveImport]
GHC.getContext
  [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext

  MsgDoc
context_bit <-
        case [Resume]
resumes of
            [] -> MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return MsgDoc
empty
            r :: Resume
r:_ -> do
                let ix :: Int
ix = Resume -> Int
GHC.resumeHistoryIx Resume
r
                if Int
ix Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0
                   then MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> MsgDoc
brackets (SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (Resume -> SrcSpan
GHC.resumeSpan Resume
r)) MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
space)
                   else do
                        let hist :: History
hist = Resume -> [History]
GHC.resumeHistory Resume
r [History] -> Int -> History
forall a. [a] -> Int -> a
!! (Int
ixInt -> Int -> Int
forall a. Num a => a -> a -> a
-1)
                        SrcSpan
pan <- History -> GHCi SrcSpan
forall (m :: * -> *). GhcMonad m => History -> m SrcSpan
GHC.getHistorySpan History
hist
                        MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> MsgDoc
brackets (Int -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (Int -> Int
forall a. Num a => a -> a
negate Int
ix) MsgDoc -> MsgDoc -> MsgDoc
<> Char -> MsgDoc
char ':'
                                          MsgDoc -> MsgDoc -> MsgDoc
<+> SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcSpan
pan) MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
space)

  let
        dots :: MsgDoc
dots | _:rs :: [Resume]
rs <- [Resume]
resumes, Bool -> Bool
not ([Resume] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Resume]
rs) = String -> MsgDoc
text "... "
             | Bool
otherwise = MsgDoc
empty

        rev_imports :: [InteractiveImport]
rev_imports = [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a]
reverse [InteractiveImport]
imports -- rightmost are the most recent

        myIdeclName :: ImportDecl pass -> ModuleName
myIdeclName d :: ImportDecl pass
d | Just m :: Located ModuleName
m <- ImportDecl pass -> Maybe (Located ModuleName)
forall pass. ImportDecl pass -> Maybe (Located ModuleName)
ideclAs ImportDecl pass
d = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc Located ModuleName
m
                      | Bool
otherwise           = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl pass -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl pass
d)

        modules_names :: [String]
modules_names =
             ['*'Char -> String -> String
forall a. a -> [a] -> [a]
:(ModuleName -> String
moduleNameString ModuleName
m) | IIModule m :: ModuleName
m <- [InteractiveImport]
rev_imports] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
             [ModuleName -> String
moduleNameString (ImportDecl GhcPs -> ModuleName
forall pass. ImportDecl pass -> ModuleName
myIdeclName ImportDecl GhcPs
d) | IIDecl d :: ImportDecl GhcPs
d <- [InteractiveImport]
rev_imports]
        line :: Int
line = 1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ GHCiState -> Int
line_number GHCiState
st

  (MsgDoc, [String], Int) -> GHCi (MsgDoc, [String], Int)
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc
dots MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
context_bit, [String]
modules_names, Int
line)

parseCallEscape :: String -> (String, String)
parseCallEscape :: String -> (String, String)
parseCallEscape s :: String
s
  | Bool -> Bool
not ((Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isSpace String
beforeOpen) = ("", "")
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
sinceOpen               = ("", "")
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
sinceClosed             = ("", "")
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
cmd                     = ("", "")
  | Bool
otherwise                    = (String
cmd, String -> String
forall a. [a] -> [a]
tail String
sinceClosed)
  where
    (beforeOpen :: String
beforeOpen, sinceOpen :: String
sinceOpen) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/='(') String
s
    (cmd :: String
cmd, sinceClosed :: String
sinceClosed) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/=')') (String -> String
forall a. [a] -> [a]
tail String
sinceOpen)

checkPromptStringForErrors :: String -> Maybe String
checkPromptStringForErrors :: String -> Maybe String
checkPromptStringForErrors ('%':'c':'a':'l':'l':xs :: String
xs) =
  case String -> (String, String)
parseCallEscape String
xs of
    ("", "") -> String -> Maybe String
forall a. a -> Maybe a
Just ("Incorrect %call syntax. " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                      "Should be %call(a command and arguments).")
    (_, afterClosed :: String
afterClosed) -> String -> Maybe String
checkPromptStringForErrors String
afterClosed
checkPromptStringForErrors ('%':'%':xs :: String
xs) = String -> Maybe String
checkPromptStringForErrors String
xs
checkPromptStringForErrors (_:xs :: String
xs) = String -> Maybe String
checkPromptStringForErrors String
xs
checkPromptStringForErrors "" = Maybe String
forall a. Maybe a
Nothing

generatePromptFunctionFromString :: String -> PromptFunction
generatePromptFunctionFromString :: String -> PromptFunction
generatePromptFunctionFromString promptS :: String
promptS modules_names :: [String]
modules_names line :: Int
line =
        String -> GHCi MsgDoc
processString String
promptS
  where
        processString :: String -> GHCi SDoc
        processString :: String -> GHCi MsgDoc
processString ('%':'s':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) (MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return MsgDoc
modules_list) (String -> GHCi MsgDoc
processString String
xs)
            where
              modules_list :: MsgDoc
modules_list = [MsgDoc] -> MsgDoc
hsep ([MsgDoc] -> MsgDoc) -> [MsgDoc] -> MsgDoc
forall a b. (a -> b) -> a -> b
$ (String -> MsgDoc) -> [String] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map String -> MsgDoc
text [String]
modules_names
        processString ('%':'l':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) (MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> GHCi MsgDoc) -> MsgDoc -> GHCi MsgDoc
forall a b. (a -> b) -> a -> b
$ Int -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Int
line) (String -> GHCi MsgDoc
processString String
xs)
        processString ('%':'d':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
formatted_time) (String -> GHCi MsgDoc
processString String
xs)
            where
              formatted_time :: GHCi String
formatted_time = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ String -> IO String
formatCurrentTime "%a %b %d"
        processString ('%':'t':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
formatted_time) (String -> GHCi MsgDoc
processString String
xs)
            where
              formatted_time :: GHCi String
formatted_time = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ String -> IO String
formatCurrentTime "%H:%M:%S"
        processString ('%':'T':xs :: String
xs) = do
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
formatted_time) (String -> GHCi MsgDoc
processString String
xs)
            where
              formatted_time :: GHCi String
formatted_time = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ String -> IO String
formatCurrentTime "%I:%M:%S"
        processString ('%':'@':xs :: String
xs) = do
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
formatted_time) (String -> GHCi MsgDoc
processString String
xs)
            where
              formatted_time :: GHCi String
formatted_time = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ String -> IO String
formatCurrentTime "%I:%M %P"
        processString ('%':'A':xs :: String
xs) = do
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
formatted_time) (String -> GHCi MsgDoc
processString String
xs)
            where
              formatted_time :: GHCi String
formatted_time = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ String -> IO String
formatCurrentTime "%H:%M"
        processString ('%':'u':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
user_name) (String -> GHCi MsgDoc
processString String
xs)
            where
              user_name :: GHCi String
user_name = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ IO String
getUserName
        processString ('%':'w':xs :: String
xs) =
            (MsgDoc -> MsgDoc -> MsgDoc)
-> GHCi MsgDoc -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 a2 r.
Monad m =>
(a1 -> a2 -> r) -> m a1 -> m a2 -> m r
liftM2 MsgDoc -> MsgDoc -> MsgDoc
(<>) ((String -> MsgDoc) -> GHCi String -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text GHCi String
current_directory) (String -> GHCi MsgDoc
processString String
xs)
            where
              current_directory :: GHCi String
current_directory = IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ IO String
getCurrentDirectory
        processString ('%':'o':xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> MsgDoc
text String
os) MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString ('%':'a':xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> MsgDoc
text String
arch) MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString ('%':'N':xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> MsgDoc
text String
compilerName) MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString ('%':'V':xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> MsgDoc
text (String -> MsgDoc) -> String -> MsgDoc
forall a b. (a -> b) -> a -> b
$ Version -> String
showVersion Version
compilerVersion) MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString ('%':'c':'a':'l':'l':xs :: String
xs) = do
            String
respond <- IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ do
                (code :: ExitCode
code, out :: String
out, err :: String
err) <-
                    String -> [String] -> String -> IO (ExitCode, String, String)
readProcessWithExitCode
                    ([String] -> String
forall a. [a] -> a
head [String]
list_words) ([String] -> [String]
forall a. [a] -> [a]
tail [String]
list_words) ""
                    IO (ExitCode, String, String)
-> (IOException -> IO (ExitCode, String, String))
-> IO (ExitCode, String, String)
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \e :: IOException
e -> (ExitCode, String, String) -> IO (ExitCode, String, String)
forall (m :: * -> *) a. Monad m => a -> m a
return (Int -> ExitCode
ExitFailure 1, "", IOException -> String
forall a. Show a => a -> String
show IOException
e)
                case ExitCode
code of
                    ExitSuccess -> String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return String
out
                    _ -> do
                        Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err
                        String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return ""
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((String -> MsgDoc
text String
respond) MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
afterClosed)
            where
              (cmd :: String
cmd, afterClosed :: String
afterClosed) = String -> (String, String)
parseCallEscape String
xs
              list_words :: [String]
list_words = String -> [String]
words String
cmd
        processString ('%':'%':xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((Char -> MsgDoc
char '%') MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString (x :: Char
x:xs :: String
xs) =
            (MsgDoc -> MsgDoc) -> GHCi MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM (Char -> MsgDoc
char Char
x MsgDoc -> MsgDoc -> MsgDoc
<>) (String -> GHCi MsgDoc
processString String
xs)
        processString "" =
            MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return MsgDoc
empty

mkPrompt :: GHCi String
mkPrompt :: GHCi String
mkPrompt = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  (context :: MsgDoc
context, modules_names :: [String]
modules_names, line :: Int
line) <- GHCi (MsgDoc, [String], Int)
getInfoForPrompt

  MsgDoc
prompt_string <- (GHCiState -> PromptFunction
prompt GHCiState
st) [String]
modules_names Int
line
  let prompt_doc :: MsgDoc
prompt_doc = MsgDoc
context MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
prompt_string

  String -> GHCi String
forall (m :: * -> *) a. Monad m => a -> m a
return (DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags MsgDoc
prompt_doc)

queryQueue :: GHCi (Maybe String)
queryQueue :: GHCi (Maybe String)
queryQueue = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  case GHCiState -> [String]
cmdqueue GHCiState
st of
    []   -> Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
    c :: String
c:cs :: [String]
cs -> do GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{ cmdqueue :: [String]
cmdqueue = [String]
cs }
               Maybe String -> GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just String
c)

-- Reconfigurable pretty-printing Ticket #5461
installInteractivePrint :: Maybe String -> Bool -> GHCi ()
installInteractivePrint :: Maybe String -> Bool -> GHCi ()
installInteractivePrint Nothing _  = () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
installInteractivePrint (Just ipFun :: String
ipFun) exprmode :: Bool
exprmode = do
  SuccessFlag
ok <- GHCi SuccessFlag -> GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess (GHCi SuccessFlag -> GHCi SuccessFlag)
-> GHCi SuccessFlag -> GHCi SuccessFlag
forall a b. (a -> b) -> a -> b
$ do
                [Name]
names <- String -> GHCi [Name]
forall (m :: * -> *). GhcMonad m => String -> m [Name]
GHC.parseName String
ipFun
                let name :: Name
name = case [Name]
names of
                             name' :: Name
name':_ -> Name
name'
                             [] -> String -> Name
forall a. String -> a
panic "installInteractivePrint"
                (HscEnv -> HscEnv) -> GHCi ()
forall (m :: * -> *). GhcMonad m => (HscEnv -> HscEnv) -> m ()
modifySession (\he :: HscEnv
he -> let new_ic :: InteractiveContext
new_ic = InteractiveContext -> Name -> InteractiveContext
setInteractivePrintName (HscEnv -> InteractiveContext
hsc_IC HscEnv
he) Name
name
                                      in HscEnv
he{hsc_IC :: InteractiveContext
hsc_IC = InteractiveContext
new_ic})
                SuccessFlag -> GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
Succeeded

  Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (SuccessFlag -> Bool
failed SuccessFlag
ok Bool -> Bool -> Bool
&& Bool
exprmode) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (ExitCode -> IO ()
forall a. ExitCode -> IO a
exitWith (Int -> ExitCode
ExitFailure 1))

-- | The main read-eval-print loop
runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
runCommands gCmd :: InputT GHCi (Maybe String)
gCmd = (SomeException -> GHCi Bool)
-> Maybe (GHCi ())
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runCommands' SomeException -> GHCi Bool
handler Maybe (GHCi ())
forall a. Maybe a
Nothing InputT GHCi (Maybe String)
gCmd InputT GHCi (Maybe Bool) -> InputT GHCi () -> InputT GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
             -> Maybe (GHCi ()) -- ^ Source error handler
             -> InputT GHCi (Maybe String)
             -> InputT GHCi (Maybe Bool)
         -- We want to return () here, but have to return (Maybe Bool)
         -- because gmask is not polymorphic enough: we want to use
         -- unmask at two different types.
runCommands' :: (SomeException -> GHCi Bool)
-> Maybe (GHCi ())
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runCommands' eh :: SomeException -> GHCi Bool
eh sourceErrorHandler :: Maybe (GHCi ())
sourceErrorHandler gCmd :: InputT GHCi (Maybe String)
gCmd = ((InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
 -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a b.
ExceptionMonad m =>
((m a -> m a) -> m b) -> m b
gmask (((InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
  -> InputT GHCi (Maybe Bool))
 -> InputT GHCi (Maybe Bool))
-> ((InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
    -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ \unmask :: InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
unmask -> do
    Maybe Bool
b <- (SomeException -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) e a.
(ExceptionMonad m, Exception e) =>
(e -> m a) -> m a -> m a
ghandle (\e :: SomeException
e -> case SomeException -> Maybe AsyncException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
e of
                          Just UserInterrupt -> Maybe Bool -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Bool -> InputT GHCi (Maybe Bool))
-> Maybe Bool -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False
                          _ -> case SomeException -> Maybe GhcException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
e of
                                 Just ghce :: GhcException
ghce ->
                                   do IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (GhcException -> IO ()
forall a. Show a => a -> IO ()
print (GhcException
ghce :: GhcException))
                                      Maybe Bool -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Bool
forall a. Maybe a
Nothing
                                 _other :: Maybe GhcException
_other ->
                                   IO (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (SomeException -> IO (Maybe Bool)
forall e a. Exception e => e -> IO a
Exception.throwIO SomeException
e))
            (InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
unmask (InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ (SomeException -> GHCi Bool)
-> InputT GHCi (Maybe String) -> InputT GHCi (Maybe Bool)
runOneCommand SomeException -> GHCi Bool
eh InputT GHCi (Maybe String)
gCmd)
    case Maybe Bool
b of
      Nothing -> Maybe Bool -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Bool
forall a. Maybe a
Nothing
      Just success :: Bool
success -> do
        Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
success (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ InputT GHCi ()
-> (GHCi () -> InputT GHCi ()) -> Maybe (GHCi ()) -> InputT GHCi ()
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (() -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()) GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift Maybe (GHCi ())
sourceErrorHandler
        InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
unmask (InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ (SomeException -> GHCi Bool)
-> Maybe (GHCi ())
-> InputT GHCi (Maybe String)
-> InputT GHCi (Maybe Bool)
runCommands' SomeException -> GHCi Bool
eh Maybe (GHCi ())
sourceErrorHandler InputT GHCi (Maybe String)
gCmd

-- | Evaluate a single line of user input (either :<command> or Haskell code).
-- A result of Nothing means there was no more input to process.
-- Otherwise the result is Just b where b is True if the command succeeded;
-- this is relevant only to ghc -e, which will exit with status 1
-- if the command was unsuccessful. GHCi will continue in either case.
runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
            -> InputT GHCi (Maybe Bool)
runOneCommand :: (SomeException -> GHCi Bool)
-> InputT GHCi (Maybe String) -> InputT GHCi (Maybe Bool)
runOneCommand eh :: SomeException -> GHCi Bool
eh gCmd :: InputT GHCi (Maybe String)
gCmd = do
  -- run a previously queued command if there is one, otherwise get new
  -- input from user
  Maybe String
mb_cmd0 <- InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
forall (m :: * -> *).
(HasGhciState m, ExceptionMonad m) =>
m (Maybe String) -> m (Maybe String)
noSpace (GHCi (Maybe String) -> InputT GHCi (Maybe String)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi (Maybe String)
queryQueue)
  Maybe String
mb_cmd1 <- InputT GHCi (Maybe String)
-> (String -> InputT GHCi (Maybe String))
-> Maybe String
-> InputT GHCi (Maybe String)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
forall (m :: * -> *).
(HasGhciState m, ExceptionMonad m) =>
m (Maybe String) -> m (Maybe String)
noSpace InputT GHCi (Maybe String)
gCmd) (Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe String -> InputT GHCi (Maybe String))
-> (String -> Maybe String) -> String -> InputT GHCi (Maybe String)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Maybe String
forall a. a -> Maybe a
Just) Maybe String
mb_cmd0
  case Maybe String
mb_cmd1 of
    Nothing -> Maybe Bool -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Bool
forall a. Maybe a
Nothing
    Just c :: String
c  -> do
      GHCiState
st <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      (SomeException -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a.
(HasDynFlags m, ExceptionMonad m) =>
(SomeException -> m a) -> m a -> m a
ghciHandle (\e :: SomeException
e -> GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
-> GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ SomeException -> GHCi Bool
eh SomeException
e GHCi Bool -> (Bool -> GHCi (Maybe Bool)) -> GHCi (Maybe Bool)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Maybe Bool -> GHCi (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Bool -> GHCi (Maybe Bool))
-> (Bool -> Maybe Bool) -> Bool -> GHCi (Maybe Bool)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> Maybe Bool
forall a. a -> Maybe a
Just) (InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$
        (SourceError -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> InputT GHCi (Maybe Bool)
forall (m :: * -> *). GhcMonad m => SourceError -> m (Maybe Bool)
printErrorAndFail (InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe Bool) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$
          GHCiState -> InputT GHCi CommandResult -> InputT GHCi (Maybe Bool)
cmd_wrapper GHCiState
st (InputT GHCi CommandResult -> InputT GHCi (Maybe Bool))
-> InputT GHCi CommandResult -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ String -> InputT GHCi CommandResult
doCommand String
c
               -- source error's are handled by runStmt
               -- is the handler necessary here?
  where
    printErrorAndFail :: SourceError -> m (Maybe Bool)
printErrorAndFail err :: SourceError
err = do
        SourceError -> m ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException SourceError
err
        Maybe Bool -> m (Maybe Bool)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Bool -> m (Maybe Bool)) -> Maybe Bool -> m (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
False     -- Exit ghc -e, but not GHCi

    noSpace :: m (Maybe String) -> m (Maybe String)
noSpace q :: m (Maybe String)
q = m (Maybe String)
q m (Maybe String)
-> (Maybe String -> m (Maybe String)) -> m (Maybe String)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= m (Maybe String)
-> (String -> m (Maybe String)) -> Maybe String -> m (Maybe String)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Maybe String -> m (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing)
                            (\c :: String
c -> case String -> String
removeSpaces String
c of
                                     ""   -> m (Maybe String) -> m (Maybe String)
noSpace m (Maybe String)
q
                                     ":{" -> m (Maybe String) -> m (Maybe String)
forall (m :: * -> *).
(HasGhciState m, ExceptionMonad m) =>
m (Maybe String) -> m (Maybe String)
multiLineCmd m (Maybe String)
q
                                     _    -> Maybe String -> m (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just String
c) )
    multiLineCmd :: m (Maybe String) -> m (Maybe String)
multiLineCmd q :: m (Maybe String)
q = do
      GHCiState
st <- m GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      let p :: PromptFunction
p = GHCiState -> PromptFunction
prompt GHCiState
st
      GHCiState -> m ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{ prompt :: PromptFunction
prompt = GHCiState -> PromptFunction
prompt_cont GHCiState
st }
      Maybe String
mb_cmd <- m (Maybe String) -> String -> m (Maybe String)
forall (m :: * -> *).
MonadIO m =>
m (Maybe String) -> String -> m (Maybe String)
collectCommand m (Maybe String)
q "" m (Maybe String) -> m () -> m (Maybe String)
forall (m :: * -> *) a b. ExceptionMonad m => m a -> m b -> m a
`GHC.gfinally`
                (GHCiState -> GHCiState) -> m ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st' :: GHCiState
st' -> GHCiState
st' { prompt :: PromptFunction
prompt = PromptFunction
p })
      Maybe String -> m (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
mb_cmd
    -- we can't use removeSpaces for the sublines here, so
    -- multiline commands are somewhat more brittle against
    -- fileformat errors (such as \r in dos input on unix),
    -- we get rid of any extra spaces for the ":}" test;
    -- we also avoid silent failure if ":}" is not found;
    -- and since there is no (?) valid occurrence of \r (as
    -- opposed to its String representation, "\r") inside a
    -- ghci command, we replace any such with ' ' (argh:-(
    collectCommand :: m (Maybe String) -> String -> m (Maybe String)
collectCommand q :: m (Maybe String)
q c :: String
c = m (Maybe String)
q m (Maybe String)
-> (Maybe String -> m (Maybe String)) -> m (Maybe String)
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
      m (Maybe String)
-> (String -> m (Maybe String)) -> Maybe String -> m (Maybe String)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (IO (Maybe String) -> m (Maybe String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IOException -> IO (Maybe String)
forall a. IOException -> IO a
ioError IOException
collectError))
            (\l :: String
l->if String -> String
removeSpaces String
l String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== ":}"
                 then Maybe String -> m (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String
forall a. a -> Maybe a
Just String
c)
                 else m (Maybe String) -> String -> m (Maybe String)
collectCommand m (Maybe String)
q (String
c String -> String -> String
forall a. [a] -> [a] -> [a]
++ "\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++ (Char -> Char) -> String -> String
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
normSpace String
l))
      where normSpace :: Char -> Char
normSpace '\r' = ' '
            normSpace   x :: Char
x  = Char
x
    -- SDM (2007-11-07): is userError the one to use here?
    collectError :: IOException
collectError = String -> IOException
userError "unterminated multiline command :{ .. :}"

    -- | Handle a line of input
    doCommand :: String -> InputT GHCi CommandResult

    -- command
    doCommand :: String -> InputT GHCi CommandResult
doCommand stmt :: String
stmt | stmt' :: String
stmt'@(':' : cmd :: String
cmd) <- String -> String
removeSpaces String
stmt = do
      (stats :: ActionStats
stats, result :: Either SomeException Bool
result) <- (Bool -> Maybe Integer)
-> InputT GHCi Bool
-> InputT GHCi (ActionStats, Either SomeException Bool)
forall (m :: * -> *) a.
ExceptionMonad m =>
(a -> Maybe Integer)
-> m a -> m (ActionStats, Either SomeException a)
runWithStats (Maybe Integer -> Bool -> Maybe Integer
forall a b. a -> b -> a
const Maybe Integer
forall a. Maybe a
Nothing) (InputT GHCi Bool
 -> InputT GHCi (ActionStats, Either SomeException Bool))
-> InputT GHCi Bool
-> InputT GHCi (ActionStats, Either SomeException Bool)
forall a b. (a -> b) -> a -> b
$ String -> InputT GHCi Bool
specialCommand String
cmd
      let processResult :: Bool -> Maybe Bool
processResult True = Maybe Bool
forall a. Maybe a
Nothing
          processResult False = Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
True
      CommandResult -> InputT GHCi CommandResult
forall (m :: * -> *) a. Monad m => a -> m a
return (CommandResult -> InputT GHCi CommandResult)
-> CommandResult -> InputT GHCi CommandResult
forall a b. (a -> b) -> a -> b
$ String
-> Either SomeException (Maybe Bool)
-> ActionStats
-> CommandResult
CommandComplete String
stmt' (Bool -> Maybe Bool
processResult (Bool -> Maybe Bool)
-> Either SomeException Bool -> Either SomeException (Maybe Bool)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either SomeException Bool
result) ActionStats
stats

    -- haskell
    doCommand stmt :: String
stmt = do
      -- if 'stmt' was entered via ':{' it will contain '\n's
      let stmt_nl_cnt :: Int
stmt_nl_cnt = [()] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ () | Char
'\n' <- String
stmt ]
      Bool
ml <- GHCi Bool -> InputT GHCi Bool
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Bool -> InputT GHCi Bool) -> GHCi Bool -> InputT GHCi Bool
forall a b. (a -> b) -> a -> b
$ GHCiOption -> GHCi Bool
isOptionSet GHCiOption
Multiline
      if Bool
ml Bool -> Bool -> Bool
&& Int
stmt_nl_cnt Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0 -- don't trigger automatic multi-line mode for ':{'-multiline input
        then do
          Int
fst_line_num <- GHCiState -> Int
line_number (GHCiState -> Int) -> InputT GHCi GHCiState -> InputT GHCi Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
          Maybe String
mb_stmt <- String -> InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
checkInputForLayout String
stmt InputT GHCi (Maybe String)
gCmd
          case Maybe String
mb_stmt of
            Nothing -> CommandResult -> InputT GHCi CommandResult
forall (m :: * -> *) a. Monad m => a -> m a
return CommandResult
CommandIncomplete
            Just ml_stmt :: String
ml_stmt -> do
              -- temporarily compensate line-number for multi-line input
              (stats :: ActionStats
stats, result :: Either SomeException (Maybe ExecResult)
result) <- (Maybe ExecResult -> Maybe Integer)
-> InputT GHCi (Maybe ExecResult)
-> InputT
     GHCi (ActionStats, Either SomeException (Maybe ExecResult))
forall a.
(a -> Maybe Integer)
-> InputT GHCi a
-> InputT GHCi (ActionStats, Either SomeException a)
runAndPrintStats Maybe ExecResult -> Maybe Integer
runAllocs (InputT GHCi (Maybe ExecResult)
 -> InputT
      GHCi (ActionStats, Either SomeException (Maybe ExecResult)))
-> InputT GHCi (Maybe ExecResult)
-> InputT
     GHCi (ActionStats, Either SomeException (Maybe ExecResult))
forall a b. (a -> b) -> a -> b
$ GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult))
-> GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult)
forall a b. (a -> b) -> a -> b
$
                Int -> String -> SingleStep -> GHCi (Maybe ExecResult)
runStmtWithLineNum Int
fst_line_num String
ml_stmt SingleStep
GHC.RunToCompletion
              CommandResult -> InputT GHCi CommandResult
forall (m :: * -> *) a. Monad m => a -> m a
return (CommandResult -> InputT GHCi CommandResult)
-> CommandResult -> InputT GHCi CommandResult
forall a b. (a -> b) -> a -> b
$
                String
-> Either SomeException (Maybe Bool)
-> ActionStats
-> CommandResult
CommandComplete String
ml_stmt (Bool -> Maybe Bool
forall a. a -> Maybe a
Just (Bool -> Maybe Bool)
-> (Maybe ExecResult -> Bool) -> Maybe ExecResult -> Maybe Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe ExecResult -> Bool
runSuccess (Maybe ExecResult -> Maybe Bool)
-> Either SomeException (Maybe ExecResult)
-> Either SomeException (Maybe Bool)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either SomeException (Maybe ExecResult)
result) ActionStats
stats
        else do -- single line input and :{ - multiline input
          Int
last_line_num <- GHCiState -> Int
line_number (GHCiState -> Int) -> InputT GHCi GHCiState -> InputT GHCi Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
          -- reconstruct first line num from last line num and stmt
          let fst_line_num :: Int
fst_line_num | Int
stmt_nl_cnt Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0 = Int
last_line_num Int -> Int -> Int
forall a. Num a => a -> a -> a
- (Int
stmt_nl_cnt2 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ 1)
                           | Bool
otherwise = Int
last_line_num -- single line input
              stmt_nl_cnt2 :: Int
stmt_nl_cnt2 = [()] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ () | Char
'\n' <- String
stmt' ]
              stmt' :: String
stmt' = String -> String
dropLeadingWhiteLines String
stmt -- runStmt doesn't like leading empty lines
          -- temporarily compensate line-number for multi-line input
          (stats :: ActionStats
stats, result :: Either SomeException (Maybe ExecResult)
result) <- (Maybe ExecResult -> Maybe Integer)
-> InputT GHCi (Maybe ExecResult)
-> InputT
     GHCi (ActionStats, Either SomeException (Maybe ExecResult))
forall a.
(a -> Maybe Integer)
-> InputT GHCi a
-> InputT GHCi (ActionStats, Either SomeException a)
runAndPrintStats Maybe ExecResult -> Maybe Integer
runAllocs (InputT GHCi (Maybe ExecResult)
 -> InputT
      GHCi (ActionStats, Either SomeException (Maybe ExecResult)))
-> InputT GHCi (Maybe ExecResult)
-> InputT
     GHCi (ActionStats, Either SomeException (Maybe ExecResult))
forall a b. (a -> b) -> a -> b
$ GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult))
-> GHCi (Maybe ExecResult) -> InputT GHCi (Maybe ExecResult)
forall a b. (a -> b) -> a -> b
$
            Int -> String -> SingleStep -> GHCi (Maybe ExecResult)
runStmtWithLineNum Int
fst_line_num String
stmt' SingleStep
GHC.RunToCompletion
          CommandResult -> InputT GHCi CommandResult
forall (m :: * -> *) a. Monad m => a -> m a
return (CommandResult -> InputT GHCi CommandResult)
-> CommandResult -> InputT GHCi CommandResult
forall a b. (a -> b) -> a -> b
$ String
-> Either SomeException (Maybe Bool)
-> ActionStats
-> CommandResult
CommandComplete String
stmt' (Bool -> Maybe Bool
forall a. a -> Maybe a
Just (Bool -> Maybe Bool)
-> (Maybe ExecResult -> Bool) -> Maybe ExecResult -> Maybe Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe ExecResult -> Bool
runSuccess (Maybe ExecResult -> Maybe Bool)
-> Either SomeException (Maybe ExecResult)
-> Either SomeException (Maybe Bool)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Either SomeException (Maybe ExecResult)
result) ActionStats
stats

    -- runStmt wrapper for temporarily overridden line-number
    runStmtWithLineNum :: Int -> String -> SingleStep
                       -> GHCi (Maybe GHC.ExecResult)
    runStmtWithLineNum :: Int -> String -> SingleStep -> GHCi (Maybe ExecResult)
runStmtWithLineNum lnum :: Int
lnum stmt :: String
stmt step :: SingleStep
step = do
        GHCiState
st0 <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
        GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st0 { line_number :: Int
line_number = Int
lnum }
        Maybe ExecResult
result <- String -> SingleStep -> GHCi (Maybe ExecResult)
runStmt String
stmt SingleStep
step
        -- restore original line_number
        GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState GHCi GHCiState -> (GHCiState -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \st :: GHCiState
st -> GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st { line_number :: Int
line_number = GHCiState -> Int
line_number GHCiState
st0 }
        Maybe ExecResult -> GHCi (Maybe ExecResult)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe ExecResult
result

    -- note: this is subtly different from 'unlines . dropWhile (all isSpace) . lines'
    dropLeadingWhiteLines :: String -> String
dropLeadingWhiteLines s :: String
s | (l0 :: String
l0,'\n':r :: String
r) <- (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
=='\n') String
s
                            , (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isSpace String
l0 = String -> String
dropLeadingWhiteLines String
r
                            | Bool
otherwise = String
s


-- #4316
-- lex the input.  If there is an unclosed layout context, request input
checkInputForLayout :: String -> InputT GHCi (Maybe String)
                    -> InputT GHCi (Maybe String)
checkInputForLayout :: String -> InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
checkInputForLayout stmt :: String
stmt getStmt :: InputT GHCi (Maybe String)
getStmt = do
   DynFlags
dflags' <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
   let dflags :: DynFlags
dflags = DynFlags -> Extension -> DynFlags
xopt_set DynFlags
dflags' Extension
LangExt.AlternativeLayoutRule
   GHCiState
st0 <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
   let buf' :: StringBuffer
buf'   =  String -> StringBuffer
stringToStringBuffer String
stmt
       loc :: RealSrcLoc
loc    = FastString -> Int -> Int -> RealSrcLoc
mkRealSrcLoc (String -> FastString
fsLit (GHCiState -> String
progname GHCiState
st0)) (GHCiState -> Int
line_number GHCiState
st0) 1
       pstate :: PState
pstate = DynFlags -> StringBuffer -> RealSrcLoc -> PState
Lexer.mkPState DynFlags
dflags StringBuffer
buf' RealSrcLoc
loc
   case P Bool -> PState -> ParseResult Bool
forall a. P a -> PState -> ParseResult a
Lexer.unP P Bool
goToEnd PState
pstate of
     (Lexer.POk _ False) -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe String -> InputT GHCi (Maybe String))
-> Maybe String -> InputT GHCi (Maybe String)
forall a b. (a -> b) -> a -> b
$ String -> Maybe String
forall a. a -> Maybe a
Just String
stmt
     _other :: ParseResult Bool
_other              -> do
       GHCiState
st1 <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
       let p :: PromptFunction
p = GHCiState -> PromptFunction
prompt GHCiState
st1
       GHCiState -> InputT GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st1{ prompt :: PromptFunction
prompt = GHCiState -> PromptFunction
prompt_cont GHCiState
st1 }
       Maybe String
mb_stmt <- (SomeException -> InputT GHCi (Maybe String))
-> InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
forall (m :: * -> *) a.
(HasDynFlags m, ExceptionMonad m) =>
(SomeException -> m a) -> m a -> m a
ghciHandle (\ex :: SomeException
ex -> case SomeException -> Maybe AsyncException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
ex of
                            Just UserInterrupt -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
                            _ -> case SomeException -> Maybe GhcException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
ex of
                                 Just ghce :: GhcException
ghce ->
                                   do IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (GhcException -> IO ()
forall a. Show a => a -> IO ()
print (GhcException
ghce :: GhcException))
                                      Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
                                 _other :: Maybe GhcException
_other -> IO (Maybe String) -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (SomeException -> IO (Maybe String)
forall e a. Exception e => e -> IO a
Exception.throwIO SomeException
ex))
                     InputT GHCi (Maybe String)
getStmt
       (GHCiState -> GHCiState) -> InputT GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st' :: GHCiState
st' -> GHCiState
st' { prompt :: PromptFunction
prompt = PromptFunction
p })
       -- the recursive call does not recycle parser state
       -- as we use a new string buffer
       case Maybe String
mb_stmt of
         Nothing  -> Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe String
forall a. Maybe a
Nothing
         Just str :: String
str -> if String
str String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== ""
           then Maybe String -> InputT GHCi (Maybe String)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe String -> InputT GHCi (Maybe String))
-> Maybe String -> InputT GHCi (Maybe String)
forall a b. (a -> b) -> a -> b
$ String -> Maybe String
forall a. a -> Maybe a
Just String
stmt
           else do
             String -> InputT GHCi (Maybe String) -> InputT GHCi (Maybe String)
checkInputForLayout (String
stmtString -> String -> String
forall a. [a] -> [a] -> [a]
++"\n"String -> String -> String
forall a. [a] -> [a] -> [a]
++String
str) InputT GHCi (Maybe String)
getStmt
     where goToEnd :: P Bool
goToEnd = do
             Bool
eof <- P Bool
Lexer.nextIsEOF
             if Bool
eof
               then P Bool
Lexer.activeContext
               else Bool -> (Located Token -> P (Located Token)) -> P (Located Token)
forall a. Bool -> (Located Token -> P a) -> P a
Lexer.lexer Bool
False Located Token -> P (Located Token)
forall (m :: * -> *) a. Monad m => a -> m a
return P (Located Token) -> P Bool -> P Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> P Bool
goToEnd

enqueueCommands :: [String] -> GHCi ()
enqueueCommands :: [String] -> GHCi ()
enqueueCommands cmds :: [String]
cmds = do
  -- make sure we force any exceptions in the commands while we're
  -- still inside the exception handler, otherwise bad things will
  -- happen (see #10501)
  [String]
cmds [String] -> GHCi () -> GHCi ()
forall a b. NFData a => a -> b -> b
`deepseq` () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st :: GHCiState
st -> GHCiState
st{ cmdqueue :: [String]
cmdqueue = [String]
cmds [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ GHCiState -> [String]
cmdqueue GHCiState
st }

-- | Entry point to execute some haskell code from user.
-- The return value True indicates success, as in `runOneCommand`.
runStmt :: String -> SingleStep -> GHCi (Maybe GHC.ExecResult)
runStmt :: String -> SingleStep -> GHCi (Maybe ExecResult)
runStmt input :: String
input step :: SingleStep
step = do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags
  -- In GHCi, we disable `-fdefer-type-errors`, as well as `-fdefer-type-holes`
  -- and `-fdefer-out-of-scope-variables` for **naked expressions**. The
  -- declarations and statements are not affected.
  -- See Note [Deferred type errors in GHCi] in typecheck/TcRnDriver.hs
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  let source :: String
source = GHCiState -> String
progname GHCiState
st
  let line :: Int
line = GHCiState -> Int
line_number GHCiState
st

  if | DynFlags -> String -> Bool
GHC.isStmt DynFlags
dflags String
input -> do
         HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
         Maybe (GhciLStmt GhcPs)
mb_stmt <- IO (Maybe (GhciLStmt GhcPs)) -> GHCi (Maybe (GhciLStmt GhcPs))
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (HscEnv
-> Hsc (Maybe (GhciLStmt GhcPs)) -> IO (Maybe (GhciLStmt GhcPs))
forall a. HscEnv -> Hsc a -> IO a
runInteractiveHsc HscEnv
hsc_env (String -> Int -> String -> Hsc (Maybe (GhciLStmt GhcPs))
hscParseStmtWithLocation String
source Int
line String
input))
         case Maybe (GhciLStmt GhcPs)
mb_stmt of
           Nothing ->
             -- empty statement / comment
             Maybe ExecResult -> GHCi (Maybe ExecResult)
forall (m :: * -> *) a. Monad m => a -> m a
return (ExecResult -> Maybe ExecResult
forall a. a -> Maybe a
Just ExecResult
exec_complete)
           Just stmt :: GhciLStmt GhcPs
stmt ->
             GhciLStmt GhcPs -> GHCi (Maybe ExecResult)
run_stmt GhciLStmt GhcPs
stmt

     | DynFlags -> String -> Bool
GHC.isImport DynFlags
dflags String
input -> GHCi (Maybe ExecResult)
run_import

     -- Every import declaration should be handled by `run_import`. As GHCi
     -- in general only accepts one command at a time, we simply throw an
     -- exception when the input contains multiple commands of which at least
     -- one is an import command (see #10663).
     | DynFlags -> String -> Bool
GHC.hasImport DynFlags
dflags String
input -> GhcException -> GHCi (Maybe ExecResult)
forall a. GhcException -> a
throwGhcException
       (String -> GhcException
CmdLineError "error: expecting a single import declaration")

     -- Otherwise assume a declaration (or a list of declarations)
     -- Note: `GHC.isDecl` returns False on input like
     -- `data Infix a b = a :@: b; infixl 4 :@:`
     -- and should therefore not be used here.
     | Bool
otherwise -> do
         HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
         [LHsDecl GhcPs]
decls <- IO [LHsDecl GhcPs] -> GHCi [LHsDecl GhcPs]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (HscEnv -> String -> Int -> String -> IO [LHsDecl GhcPs]
hscParseDeclsWithLocation HscEnv
hsc_env String
source Int
line String
input)
         [LHsDecl GhcPs] -> GHCi (Maybe ExecResult)
run_decls [LHsDecl GhcPs]
decls
  where
    exec_complete :: ExecResult
exec_complete = Either SomeException [Name] -> Word64 -> ExecResult
GHC.ExecComplete ([Name] -> Either SomeException [Name]
forall a b. b -> Either a b
Right []) 0

    run_import :: GHCi (Maybe ExecResult)
run_import = do
      String -> GHCi ()
addImportToContext String
input
      Maybe ExecResult -> GHCi (Maybe ExecResult)
forall (m :: * -> *) a. Monad m => a -> m a
return (ExecResult -> Maybe ExecResult
forall a. a -> Maybe a
Just ExecResult
exec_complete)

    run_stmt :: GhciLStmt GhcPs -> GHCi (Maybe GHC.ExecResult)
    run_stmt :: GhciLStmt GhcPs -> GHCi (Maybe ExecResult)
run_stmt stmt :: GhciLStmt GhcPs
stmt = do
           Maybe ExecResult
m_result <- GhciLStmt GhcPs -> String -> SingleStep -> GHCi (Maybe ExecResult)
GhciMonad.runStmt GhciLStmt GhcPs
stmt String
input SingleStep
step
           case Maybe ExecResult
m_result of
               Nothing     -> Maybe ExecResult -> GHCi (Maybe ExecResult)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe ExecResult
forall a. Maybe a
Nothing
               Just result :: ExecResult
result -> ExecResult -> Maybe ExecResult
forall a. a -> Maybe a
Just (ExecResult -> Maybe ExecResult)
-> GHCi ExecResult -> GHCi (Maybe ExecResult)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (SrcSpan -> Bool) -> ExecResult -> GHCi ExecResult
afterRunStmt (Bool -> SrcSpan -> Bool
forall a b. a -> b -> a
const Bool
True) ExecResult
result

    -- `x = y` (a declaration) should be treated as `let x = y` (a statement).
    -- The reason is because GHCi wasn't designed to support `x = y`, but then
    -- b98ff3 (#7253) added support for it, except it did not do a good job and
    -- caused problems like:
    --
    --  - not adding the binders defined this way in the necessary places caused
    --    `x = y` to not work in some cases (#12091).
    --  - some GHCi command crashed after `x = y` (#15721)
    --  - warning generation did not work for `x = y` (#11606)
    --  - because `x = y` is a declaration (instead of a statement) differences
    --    in generated code caused confusion (#16089)
    --
    -- Instead of dealing with all these problems individually here we fix this
    -- mess by just treating `x = y` as `let x = y`.
    run_decls :: [LHsDecl GhcPs] -> GHCi (Maybe GHC.ExecResult)
    -- Only turn `FunBind` and `VarBind` into statements, other bindings
    -- (e.g. `PatBind`) need to stay as decls.
    run_decls :: [LHsDecl GhcPs] -> GHCi (Maybe ExecResult)
run_decls [L l :: SrcSpan
l (ValD _ bind :: HsBind GhcPs
bind@FunBind{})] = GhciLStmt GhcPs -> GHCi (Maybe ExecResult)
run_stmt (SrcSpan -> HsBind GhcPs -> GhciLStmt GhcPs
mk_stmt SrcSpan
l HsBind GhcPs
bind)
    run_decls [L l :: SrcSpan
l (ValD _ bind :: HsBind GhcPs
bind@VarBind{})] = GhciLStmt GhcPs -> GHCi (Maybe ExecResult)
run_stmt (SrcSpan -> HsBind GhcPs -> GhciLStmt GhcPs
mk_stmt SrcSpan
l HsBind GhcPs
bind)
    -- Note that any `x = y` declarations below will be run as declarations
    -- instead of statements (e.g. `...; x = y; ...`)
    run_decls decls :: [LHsDecl GhcPs]
decls = do
      -- In the new IO library, read handles buffer data even if the Handle
      -- is set to NoBuffering.  This causes problems for GHCi where there
      -- are really two stdin Handles.  So we flush any bufferred data in
      -- GHCi's stdin Handle here (only relevant if stdin is attached to
      -- a file, otherwise the read buffer can't be flushed).
      Either IOException ()
_ <- IO (Either IOException ()) -> GHCi (Either IOException ())
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException ()) -> GHCi (Either IOException ()))
-> IO (Either IOException ()) -> GHCi (Either IOException ())
forall a b. (a -> b) -> a -> b
$ IO () -> IO (Either IOException ())
forall a. IO a -> IO (Either IOException a)
tryIO (IO () -> IO (Either IOException ()))
-> IO () -> IO (Either IOException ())
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hFlushAll Handle
stdin
      Maybe [Name]
m_result <- [LHsDecl GhcPs] -> GHCi (Maybe [Name])
GhciMonad.runDecls' [LHsDecl GhcPs]
decls
      Maybe [Name]
-> ([Name] -> GHCi ExecResult) -> GHCi (Maybe ExecResult)
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
t a -> (a -> m b) -> m (t b)
forM Maybe [Name]
m_result (([Name] -> GHCi ExecResult) -> GHCi (Maybe ExecResult))
-> ([Name] -> GHCi ExecResult) -> GHCi (Maybe ExecResult)
forall a b. (a -> b) -> a -> b
$ \result :: [Name]
result ->
        (SrcSpan -> Bool) -> ExecResult -> GHCi ExecResult
afterRunStmt (Bool -> SrcSpan -> Bool
forall a b. a -> b -> a
const Bool
True) (Either SomeException [Name] -> Word64 -> ExecResult
GHC.ExecComplete ([Name] -> Either SomeException [Name]
forall a b. b -> Either a b
Right [Name]
result) 0)

    mk_stmt :: SrcSpan -> HsBind GhcPs -> GhciLStmt GhcPs
    mk_stmt :: SrcSpan -> HsBind GhcPs -> GhciLStmt GhcPs
mk_stmt loc :: SrcSpan
loc bind :: HsBind GhcPs
bind =
      let l :: e -> GenLocated SrcSpan e
l = SrcSpan -> e -> GenLocated SrcSpan e
forall l e. l -> e -> GenLocated l e
L SrcSpan
loc
      in StmtLR GhcPs GhcPs (LHsExpr GhcPs) -> GhciLStmt GhcPs
forall e. e -> GenLocated SrcSpan e
l (XLetStmt GhcPs GhcPs (LHsExpr GhcPs)
-> LHsLocalBindsLR GhcPs GhcPs
-> StmtLR GhcPs GhcPs (LHsExpr GhcPs)
forall idL idR body.
XLetStmt idL idR body
-> LHsLocalBindsLR idL idR -> StmtLR idL idR body
LetStmt NoExt
XLetStmt GhcPs GhcPs (LHsExpr GhcPs)
noExt (HsLocalBindsLR GhcPs GhcPs -> LHsLocalBindsLR GhcPs GhcPs
forall e. e -> GenLocated SrcSpan e
l (XHsValBinds GhcPs GhcPs
-> HsValBindsLR GhcPs GhcPs -> HsLocalBindsLR GhcPs GhcPs
forall idL idR.
XHsValBinds idL idR
-> HsValBindsLR idL idR -> HsLocalBindsLR idL idR
HsValBinds NoExt
XHsValBinds GhcPs GhcPs
noExt (XValBinds GhcPs GhcPs
-> LHsBindsLR GhcPs GhcPs
-> [LSig GhcPs]
-> HsValBindsLR GhcPs GhcPs
forall idL idR.
XValBinds idL idR
-> LHsBindsLR idL idR -> [LSig idR] -> HsValBindsLR idL idR
ValBinds NoExt
XValBinds GhcPs GhcPs
noExt (GenLocated SrcSpan (HsBind GhcPs) -> LHsBindsLR GhcPs GhcPs
forall a. a -> Bag a
unitBag (HsBind GhcPs -> GenLocated SrcSpan (HsBind GhcPs)
forall e. e -> GenLocated SrcSpan e
l HsBind GhcPs
bind)) []))))

-- | Clean up the GHCi environment after a statement has run
afterRunStmt :: (SrcSpan -> Bool) -> GHC.ExecResult -> GHCi GHC.ExecResult
afterRunStmt :: (SrcSpan -> Bool) -> ExecResult -> GHCi ExecResult
afterRunStmt step_here :: SrcSpan -> Bool
step_here run_result :: ExecResult
run_result = do
  [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
  case ExecResult
run_result of
     GHC.ExecComplete{..} ->
       case Either SomeException [Name]
execResult of
          Left ex :: SomeException
ex -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ SomeException -> IO ()
forall e a. Exception e => e -> IO a
Exception.throwIO SomeException
ex
          Right names :: [Name]
names -> do
            Bool
show_types <- GHCiOption -> GHCi Bool
isOptionSet GHCiOption
ShowType
            Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
show_types (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [Name] -> GHCi ()
printTypeOfNames [Name]
names
     GHC.ExecBreak names :: [Name]
names mb_info :: Maybe BreakInfo
mb_info
         | Maybe BreakInfo -> Bool
forall a. Maybe a -> Bool
isNothing  Maybe BreakInfo
mb_info Bool -> Bool -> Bool
||
           SrcSpan -> Bool
step_here (Resume -> SrcSpan
GHC.resumeSpan (Resume -> SrcSpan) -> Resume -> SrcSpan
forall a b. (a -> b) -> a -> b
$ [Resume] -> Resume
forall a. [a] -> a
head [Resume]
resumes) -> do
               Maybe (Int, BreakLocation)
mb_id_loc <- Maybe BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation Maybe BreakInfo
mb_info
               let bCmd :: String
bCmd = String
-> ((Int, BreakLocation) -> String)
-> Maybe (Int, BreakLocation)
-> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe "" ( \(_,l :: BreakLocation
l) -> BreakLocation -> String
onBreakCmd BreakLocation
l ) Maybe (Int, BreakLocation)
mb_id_loc
               if (String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
bCmd)
                 then Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo ([Resume] -> Resume
forall a. [a] -> a
head [Resume]
resumes) [Name]
names
                 else [String] -> GHCi ()
enqueueCommands [String
bCmd]
               -- run the command set with ":set stop <cmd>"
               GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
               [String] -> GHCi ()
enqueueCommands [GHCiState -> String
stop GHCiState
st]
               () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
         | Bool
otherwise -> (SrcSpan -> Bool) -> SingleStep -> GHCi ExecResult
resume SrcSpan -> Bool
step_here SingleStep
GHC.SingleStep GHCi ExecResult
-> (ExecResult -> GHCi ExecResult) -> GHCi ExecResult
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>=
                        (SrcSpan -> Bool) -> ExecResult -> GHCi ExecResult
afterRunStmt SrcSpan -> Bool
step_here GHCi ExecResult -> GHCi () -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

  GHCi ()
flushInterpBuffers
  GHCi () -> GHCi ()
forall (m :: * -> *) a. (ExceptionMonad m, MonadIO m) => m a -> m a
withSignalHandlers (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
     Bool
b <- GHCiOption -> GHCi Bool
isOptionSet GHCiOption
RevertCAFs
     Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
b GHCi ()
revertCAFs

  ExecResult -> GHCi ExecResult
forall (m :: * -> *) a. Monad m => a -> m a
return ExecResult
run_result

runSuccess :: Maybe GHC.ExecResult -> Bool
runSuccess :: Maybe ExecResult -> Bool
runSuccess run_result :: Maybe ExecResult
run_result
  | Just (GHC.ExecComplete { execResult :: ExecResult -> Either SomeException [Name]
execResult = Right _ }) <- Maybe ExecResult
run_result = Bool
True
  | Bool
otherwise = Bool
False

runAllocs :: Maybe GHC.ExecResult -> Maybe Integer
runAllocs :: Maybe ExecResult -> Maybe Integer
runAllocs m :: Maybe ExecResult
m = do
  ExecResult
res <- Maybe ExecResult
m
  case ExecResult
res of
    GHC.ExecComplete{..} -> Integer -> Maybe Integer
forall a. a -> Maybe a
Just (Word64 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
execAllocation)
    _ -> Maybe Integer
forall a. Maybe a
Nothing

toBreakIdAndLocation ::
  Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation :: Maybe BreakInfo -> GHCi (Maybe (Int, BreakLocation))
toBreakIdAndLocation Nothing = Maybe (Int, BreakLocation) -> GHCi (Maybe (Int, BreakLocation))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Int, BreakLocation)
forall a. Maybe a
Nothing
toBreakIdAndLocation (Just inf :: BreakInfo
inf) = do
  let md :: Module
md = BreakInfo -> Module
GHC.breakInfo_module BreakInfo
inf
      nm :: Int
nm = BreakInfo -> Int
GHC.breakInfo_number BreakInfo
inf
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  Maybe (Int, BreakLocation) -> GHCi (Maybe (Int, BreakLocation))
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe (Int, BreakLocation) -> GHCi (Maybe (Int, BreakLocation)))
-> Maybe (Int, BreakLocation) -> GHCi (Maybe (Int, BreakLocation))
forall a b. (a -> b) -> a -> b
$ [(Int, BreakLocation)] -> Maybe (Int, BreakLocation)
forall a. [a] -> Maybe a
listToMaybe [ (Int, BreakLocation)
id_loc | id_loc :: (Int, BreakLocation)
id_loc@(_,loc :: BreakLocation
loc) <- GHCiState -> [(Int, BreakLocation)]
breaks GHCiState
st,
                                  BreakLocation -> Module
breakModule BreakLocation
loc Module -> Module -> Bool
forall a. Eq a => a -> a -> Bool
== Module
md,
                                  BreakLocation -> Int
breakTick BreakLocation
loc Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
nm ]

printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
printStoppedAtBreakInfo res :: Resume
res names :: [Name]
names = do
  MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Resume -> MsgDoc
pprStopped Resume
res
  --  printTypeOfNames session names
  let namesSorted :: [Name]
namesSorted = (Name -> Name -> Ordering) -> [Name] -> [Name]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy Name -> Name -> Ordering
compareNames [Name]
names
  [TyThing]
tythings <- [Maybe TyThing] -> [TyThing]
forall a. [Maybe a] -> [a]
catMaybes ([Maybe TyThing] -> [TyThing])
-> GHCi [Maybe TyThing] -> GHCi [TyThing]
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
`liftM` (Name -> GHCi (Maybe TyThing)) -> [Name] -> GHCi [Maybe TyThing]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Name -> GHCi (Maybe TyThing)
forall (m :: * -> *). GhcMonad m => Name -> m (Maybe TyThing)
GHC.lookupName [Name]
namesSorted
  [MsgDoc]
docs <- (Id -> GHCi MsgDoc) -> [Id] -> GHCi [MsgDoc]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Id -> GHCi MsgDoc
forall (m :: * -> *). GhcMonad m => Id -> m MsgDoc
pprTypeAndContents [Id
i | AnId i :: Id
i <- [TyThing]
tythings]
  MsgDoc -> GHCi ()
printForUserPartWay (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat [MsgDoc]
docs

printTypeOfNames :: [Name] -> GHCi ()
printTypeOfNames :: [Name] -> GHCi ()
printTypeOfNames names :: [Name]
names
 = (Name -> GHCi ()) -> [Name] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Name -> GHCi ()
printTypeOfName ) ([Name] -> GHCi ()) -> [Name] -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (Name -> Name -> Ordering) -> [Name] -> [Name]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy Name -> Name -> Ordering
compareNames [Name]
names

compareNames :: Name -> Name -> Ordering
n1 :: Name
n1 compareNames :: Name -> Name -> Ordering
`compareNames` n2 :: Name
n2 = Name -> (String, SrcSpan)
forall a. NamedThing a => a -> (String, SrcSpan)
compareWith Name
n1 (String, SrcSpan) -> (String, SrcSpan) -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` Name -> (String, SrcSpan)
forall a. NamedThing a => a -> (String, SrcSpan)
compareWith Name
n2
    where compareWith :: a -> (String, SrcSpan)
compareWith n :: a
n = (a -> String
forall a. NamedThing a => a -> String
getOccString a
n, a -> SrcSpan
forall a. NamedThing a => a -> SrcSpan
getSrcSpan a
n)

printTypeOfName :: Name -> GHCi ()
printTypeOfName :: Name -> GHCi ()
printTypeOfName n :: Name
n
   = do Maybe TyThing
maybe_tything <- Name -> GHCi (Maybe TyThing)
forall (m :: * -> *). GhcMonad m => Name -> m (Maybe TyThing)
GHC.lookupName Name
n
        case Maybe TyThing
maybe_tything of
            Nothing    -> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
            Just thing :: TyThing
thing -> TyThing -> GHCi ()
printTyThing TyThing
thing


data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand

-- | Entry point for execution a ':<command>' input from user
specialCommand :: String -> InputT GHCi Bool
specialCommand :: String -> InputT GHCi Bool
specialCommand ('!':str :: String
str) = GHCi Bool -> InputT GHCi Bool
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Bool -> InputT GHCi Bool) -> GHCi Bool -> InputT GHCi Bool
forall a b. (a -> b) -> a -> b
$ String -> GHCi Bool
shellEscape ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
str)
specialCommand str :: String
str = do
  let (cmd :: String
cmd,rest :: String
rest) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isSpace String
str
  MaybeCommand
maybe_cmd <- GHCi MaybeCommand -> InputT GHCi MaybeCommand
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi MaybeCommand -> InputT GHCi MaybeCommand)
-> GHCi MaybeCommand -> InputT GHCi MaybeCommand
forall a b. (a -> b) -> a -> b
$ String -> GHCi MaybeCommand
lookupCommand String
cmd
  String
htxt <- GHCiState -> String
short_help (GHCiState -> String)
-> InputT GHCi GHCiState -> InputT GHCi String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  case MaybeCommand
maybe_cmd of
    GotCommand cmd :: Command
cmd -> (Command -> String -> InputT GHCi Bool
cmdAction Command
cmd) ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest)
    BadCommand ->
      do IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStr Handle
stdout ("unknown command ':" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmd String -> String -> String
forall a. [a] -> [a] -> [a]
++ "'\n"
                           String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
htxt)
         Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
    NoLastCommand ->
      do IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStr Handle
stdout ("there is no last command to perform\n"
                           String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
htxt)
         Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

shellEscape :: String -> GHCi Bool
shellEscape :: String -> GHCi Bool
shellEscape str :: String
str = IO Bool -> GHCi Bool
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ExitCode
system String
str IO ExitCode -> IO Bool -> IO Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False)

lookupCommand :: String -> GHCi (MaybeCommand)
lookupCommand :: String -> GHCi MaybeCommand
lookupCommand "" = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  case GHCiState -> Maybe Command
last_command GHCiState
st of
      Just c :: Command
c -> MaybeCommand -> GHCi MaybeCommand
forall (m :: * -> *) a. Monad m => a -> m a
return (MaybeCommand -> GHCi MaybeCommand)
-> MaybeCommand -> GHCi MaybeCommand
forall a b. (a -> b) -> a -> b
$ Command -> MaybeCommand
GotCommand Command
c
      Nothing -> MaybeCommand -> GHCi MaybeCommand
forall (m :: * -> *) a. Monad m => a -> m a
return MaybeCommand
NoLastCommand
lookupCommand str :: String
str = do
  Maybe Command
mc <- String -> GHCi (Maybe Command)
lookupCommand' String
str
  (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st { last_command :: Maybe Command
last_command = Maybe Command
mc })
  MaybeCommand -> GHCi MaybeCommand
forall (m :: * -> *) a. Monad m => a -> m a
return (MaybeCommand -> GHCi MaybeCommand)
-> MaybeCommand -> GHCi MaybeCommand
forall a b. (a -> b) -> a -> b
$ case Maybe Command
mc of
           Just c :: Command
c -> Command -> MaybeCommand
GotCommand Command
c
           Nothing -> MaybeCommand
BadCommand

lookupCommand' :: String -> GHCi (Maybe Command)
lookupCommand' :: String -> GHCi (Maybe Command)
lookupCommand' ":" = Maybe Command -> GHCi (Maybe Command)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Command
forall a. Maybe a
Nothing
lookupCommand' str' :: String
str' = do
  [Command]
macros    <- GHCiState -> [Command]
ghci_macros (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  [Command]
ghci_cmds <- GHCiState -> [Command]
ghci_commands (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState

  let ghci_cmds_nohide :: [Command]
ghci_cmds_nohide = (Command -> Bool) -> [Command] -> [Command]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Command -> Bool) -> Command -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Command -> Bool
cmdHidden) [Command]
ghci_cmds

  let (str :: String
str, xcmds :: [Command]
xcmds) = case String
str' of
          ':' : rest :: String
rest -> (String
rest, [])     -- "::" selects a builtin command
          _          -> (String
str', [Command]
macros) -- otherwise include macros in lookup

      lookupExact :: String -> t Command -> Maybe Command
lookupExact  s :: String
s = (Command -> Bool) -> t Command -> Maybe Command
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Command -> Bool) -> t Command -> Maybe Command)
-> (Command -> Bool) -> t Command -> Maybe Command
forall a b. (a -> b) -> a -> b
$ (String
s String -> String -> Bool
forall a. Eq a => a -> a -> Bool
==)           (String -> Bool) -> (Command -> String) -> Command -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Command -> String
cmdName
      lookupPrefix :: String -> t Command -> Maybe Command
lookupPrefix s :: String
s = (Command -> Bool) -> t Command -> Maybe Command
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find ((Command -> Bool) -> t Command -> Maybe Command)
-> (Command -> Bool) -> t Command -> Maybe Command
forall a b. (a -> b) -> a -> b
$ (String
s String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) (String -> Bool) -> (Command -> String) -> Command -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Command -> String
cmdName

      -- hidden commands can only be matched exact
      builtinPfxMatch :: Maybe Command
builtinPfxMatch = String -> [Command] -> Maybe Command
forall (t :: * -> *).
Foldable t =>
String -> t Command -> Maybe Command
lookupPrefix String
str [Command]
ghci_cmds_nohide

  -- first, look for exact match (while preferring macros); then, look
  -- for first prefix match (preferring builtins), *unless* a macro
  -- overrides the builtin; see #8305 for motivation
  Maybe Command -> GHCi (Maybe Command)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Command -> GHCi (Maybe Command))
-> Maybe Command -> GHCi (Maybe Command)
forall a b. (a -> b) -> a -> b
$ String -> [Command] -> Maybe Command
forall (t :: * -> *).
Foldable t =>
String -> t Command -> Maybe Command
lookupExact String
str [Command]
xcmds Maybe Command -> Maybe Command -> Maybe Command
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
           String -> [Command] -> Maybe Command
forall (t :: * -> *).
Foldable t =>
String -> t Command -> Maybe Command
lookupExact String
str [Command]
ghci_cmds Maybe Command -> Maybe Command -> Maybe Command
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
           (Maybe Command
builtinPfxMatch Maybe Command -> (Command -> Maybe Command) -> Maybe Command
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \c :: Command
c -> String -> [Command] -> Maybe Command
forall (t :: * -> *).
Foldable t =>
String -> t Command -> Maybe Command
lookupExact (Command -> String
cmdName Command
c) [Command]
xcmds) Maybe Command -> Maybe Command -> Maybe Command
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
           Maybe Command
builtinPfxMatch Maybe Command -> Maybe Command -> Maybe Command
forall (f :: * -> *) a. Alternative f => f a -> f a -> f a
<|>
           String -> [Command] -> Maybe Command
forall (t :: * -> *).
Foldable t =>
String -> t Command -> Maybe Command
lookupPrefix String
str [Command]
xcmds

getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
getCurrentBreakSpan = do
  [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
  case [Resume]
resumes of
    [] -> Maybe SrcSpan -> GHCi (Maybe SrcSpan)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe SrcSpan
forall a. Maybe a
Nothing
    (r :: Resume
r:_) -> do
        let ix :: Int
ix = Resume -> Int
GHC.resumeHistoryIx Resume
r
        if Int
ix Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0
           then Maybe SrcSpan -> GHCi (Maybe SrcSpan)
forall (m :: * -> *) a. Monad m => a -> m a
return (SrcSpan -> Maybe SrcSpan
forall a. a -> Maybe a
Just (Resume -> SrcSpan
GHC.resumeSpan Resume
r))
           else do
                let hist :: History
hist = Resume -> [History]
GHC.resumeHistory Resume
r [History] -> Int -> History
forall a. [a] -> Int -> a
!! (Int
ixInt -> Int -> Int
forall a. Num a => a -> a -> a
-1)
                SrcSpan
pan <- History -> GHCi SrcSpan
forall (m :: * -> *). GhcMonad m => History -> m SrcSpan
GHC.getHistorySpan History
hist
                Maybe SrcSpan -> GHCi (Maybe SrcSpan)
forall (m :: * -> *) a. Monad m => a -> m a
return (SrcSpan -> Maybe SrcSpan
forall a. a -> Maybe a
Just SrcSpan
pan)

getCallStackAtCurrentBreakpoint :: GHCi (Maybe [String])
getCallStackAtCurrentBreakpoint :: GHCi (Maybe [String])
getCallStackAtCurrentBreakpoint = do
  [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
  case [Resume]
resumes of
    [] -> Maybe [String] -> GHCi (Maybe [String])
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe [String]
forall a. Maybe a
Nothing
    (r :: Resume
r:_) -> do
       HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
       [String] -> Maybe [String]
forall a. a -> Maybe a
Just ([String] -> Maybe [String])
-> GHCi [String] -> GHCi (Maybe [String])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO [String] -> GHCi [String]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (HscEnv -> RemotePtr CostCentreStack -> IO [String]
costCentreStackInfo HscEnv
hsc_env (Resume -> RemotePtr CostCentreStack
GHC.resumeCCS Resume
r))

getCurrentBreakModule :: GHCi (Maybe Module)
getCurrentBreakModule :: GHCi (Maybe Module)
getCurrentBreakModule = do
  [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
  case [Resume]
resumes of
    [] -> Maybe Module -> GHCi (Maybe Module)
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe Module
forall a. Maybe a
Nothing
    (r :: Resume
r:_) -> do
        let ix :: Int
ix = Resume -> Int
GHC.resumeHistoryIx Resume
r
        if Int
ix Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0
           then Maybe Module -> GHCi (Maybe Module)
forall (m :: * -> *) a. Monad m => a -> m a
return (BreakInfo -> Module
GHC.breakInfo_module (BreakInfo -> Module) -> Maybe BreakInfo -> Maybe Module
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
`liftM` Resume -> Maybe BreakInfo
GHC.resumeBreakInfo Resume
r)
           else do
                let hist :: History
hist = Resume -> [History]
GHC.resumeHistory Resume
r [History] -> Int -> History
forall a. [a] -> Int -> a
!! (Int
ixInt -> Int -> Int
forall a. Num a => a -> a -> a
-1)
                Maybe Module -> GHCi (Maybe Module)
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe Module -> GHCi (Maybe Module))
-> Maybe Module -> GHCi (Maybe Module)
forall a b. (a -> b) -> a -> b
$ Module -> Maybe Module
forall a. a -> Maybe a
Just (Module -> Maybe Module) -> Module -> Maybe Module
forall a b. (a -> b) -> a -> b
$ History -> Module
GHC.getHistoryModule  History
hist

-----------------------------------------------------------------------------
--
-- Commands
--
-----------------------------------------------------------------------------

noArgs :: GHCi () -> String -> GHCi ()
noArgs :: GHCi () -> String -> GHCi ()
noArgs m :: GHCi ()
m "" = GHCi ()
m
noArgs _ _  = IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "This command takes no arguments"

withSandboxOnly :: String -> GHCi () -> GHCi ()
withSandboxOnly :: String -> GHCi () -> GHCi ()
withSandboxOnly cmd :: String
cmd this :: GHCi ()
this = do
   DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
   if Bool -> Bool
not (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_GhciSandbox DynFlags
dflags)
      then MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (String -> MsgDoc
text String
cmd MsgDoc -> MsgDoc -> MsgDoc
<+>
                         PtrString -> MsgDoc
ptext (String -> PtrString
sLit "is not supported with -fno-ghci-sandbox"))
      else GHCi ()
this

-----------------------------------------------------------------------------
-- :help

help :: String -> GHCi ()
help :: String -> GHCi ()
help _ = do
    String
txt <- GHCiState -> String
long_help (GHCiState -> String) -> GHCi GHCiState -> GHCi String
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStr String
txt

-----------------------------------------------------------------------------
-- :info

info :: Bool -> String -> InputT GHCi ()
info :: Bool -> String -> InputT GHCi ()
info _ "" = GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax: ':i <thing-you-want-info-about>'")
info allInfo :: Bool
allInfo s :: String
s  = (SourceError -> InputT GHCi ()) -> InputT GHCi () -> InputT GHCi ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    PrintUnqualified
unqual <- InputT GHCi PrintUnqualified
forall (m :: * -> *). GhcMonad m => m PrintUnqualified
GHC.getPrintUnqual
    DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
    [MsgDoc]
sdocs  <- (String -> InputT GHCi MsgDoc) -> [String] -> InputT GHCi [MsgDoc]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool -> String -> InputT GHCi MsgDoc
forall (m :: * -> *). GhcMonad m => Bool -> String -> m MsgDoc
infoThing Bool
allInfo) (String -> [String]
words String
s)
    (MsgDoc -> InputT GHCi ()) -> [MsgDoc] -> InputT GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ())
-> (MsgDoc -> IO ()) -> MsgDoc -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> IO ()) -> (MsgDoc -> String) -> MsgDoc -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
dflags PrintUnqualified
unqual) [MsgDoc]
sdocs

infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
infoThing :: Bool -> String -> m MsgDoc
infoThing allInfo :: Bool
allInfo str :: String
str = do
    [Name]
names     <- String -> m [Name]
forall (m :: * -> *). GhcMonad m => String -> m [Name]
GHC.parseName String
str
    [Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
mb_stuffs <- (Name -> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)))
-> [Name]
-> m [Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (Bool
-> Name
-> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc))
forall (m :: * -> *).
GhcMonad m =>
Bool
-> Name
-> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc))
GHC.getInfo Bool
allInfo) [Name]
names
    let filtered :: [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
filtered = ((TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> TyThing)
-> [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
-> [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
forall a. (a -> TyThing) -> [a] -> [a]
filterOutChildren (\(t :: TyThing
t,_f :: Fixity
_f,_ci :: [ClsInst]
_ci,_fi :: [FamInst]
_fi,_sd :: MsgDoc
_sd) -> TyThing
t)
                                     ([Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
-> [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
forall a. [Maybe a] -> [a]
catMaybes [Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
mb_stuffs)
    MsgDoc -> m MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> m MsgDoc) -> MsgDoc -> m MsgDoc
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat (MsgDoc -> [MsgDoc] -> [MsgDoc]
forall a. a -> [a] -> [a]
intersperse (String -> MsgDoc
text "") ([MsgDoc] -> [MsgDoc]) -> [MsgDoc] -> [MsgDoc]
forall a b. (a -> b) -> a -> b
$ ((TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc)
-> [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc
pprInfo [(TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)]
filtered)

  -- Filter out names whose parent is also there Good
  -- example is '[]', which is both a type and data
  -- constructor in the same type
filterOutChildren :: (a -> TyThing) -> [a] -> [a]
filterOutChildren :: (a -> TyThing) -> [a] -> [a]
filterOutChildren get_thing :: a -> TyThing
get_thing xs :: [a]
xs
  = (a -> Bool) -> [a] -> [a]
forall a. (a -> Bool) -> [a] -> [a]
filterOut a -> Bool
has_parent [a]
xs
  where
    all_names :: NameSet
all_names = [Name] -> NameSet
mkNameSet ((a -> Name) -> [a] -> [Name]
forall a b. (a -> b) -> [a] -> [b]
map (TyThing -> Name
forall a. NamedThing a => a -> Name
getName (TyThing -> Name) -> (a -> TyThing) -> a -> Name
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> TyThing
get_thing) [a]
xs)
    has_parent :: a -> Bool
has_parent x :: a
x = case TyThing -> Maybe TyThing
tyThingParent_maybe (a -> TyThing
get_thing a
x) of
                     Just p :: TyThing
p  -> TyThing -> Name
forall a. NamedThing a => a -> Name
getName TyThing
p Name -> NameSet -> Bool
`elemNameSet` NameSet
all_names
                     Nothing -> Bool
False

pprInfo :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
pprInfo :: (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc
pprInfo (thing :: TyThing
thing, fixity :: Fixity
fixity, cls_insts :: [ClsInst]
cls_insts, fam_insts :: [FamInst]
fam_insts, docs :: MsgDoc
docs)
  =  MsgDoc
docs
  MsgDoc -> MsgDoc -> MsgDoc
$$ TyThing -> MsgDoc
pprTyThingInContextLoc TyThing
thing
  MsgDoc -> MsgDoc -> MsgDoc
$$ MsgDoc
show_fixity
  MsgDoc -> MsgDoc -> MsgDoc
$$ [MsgDoc] -> MsgDoc
vcat ((ClsInst -> MsgDoc) -> [ClsInst] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map ClsInst -> MsgDoc
GHC.pprInstance [ClsInst]
cls_insts)
  MsgDoc -> MsgDoc -> MsgDoc
$$ [MsgDoc] -> MsgDoc
vcat ((FamInst -> MsgDoc) -> [FamInst] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map FamInst -> MsgDoc
GHC.pprFamInst  [FamInst]
fam_insts)
  where
    show_fixity :: MsgDoc
show_fixity
        | Fixity
fixity Fixity -> Fixity -> Bool
forall a. Eq a => a -> a -> Bool
== Fixity
GHC.defaultFixity = MsgDoc
empty
        | Bool
otherwise                   = Fixity -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Fixity
fixity MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. (Outputable a, NamedThing a) => a -> MsgDoc
pprInfixName (TyThing -> Name
forall a. NamedThing a => a -> Name
GHC.getName TyThing
thing)

-----------------------------------------------------------------------------
-- :main

runMain :: String -> GHCi ()
runMain :: String -> GHCi ()
runMain s :: String
s = case String -> Either String [String]
toArgs String
s of
            Left err :: String
err   -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err)
            Right args :: [String]
args ->
                do DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
                   let main :: String
main = String -> Maybe String -> String
forall a. a -> Maybe a -> a
fromMaybe "main" (DynFlags -> Maybe String
mainFunIs DynFlags
dflags)
                   -- Wrap the main function in 'void' to discard its value instead
                   -- of printing it (#9086). See Haskell 2010 report Chapter 5.
                   [String] -> String -> GHCi ()
doWithArgs [String]
args (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ "Control.Monad.void (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
main String -> String -> String
forall a. [a] -> [a] -> [a]
++ ")"

-----------------------------------------------------------------------------
-- :run

runRun :: String -> GHCi ()
runRun :: String -> GHCi ()
runRun s :: String
s = case String -> Either String (String, [String])
toCmdArgs String
s of
           Left err :: String
err          -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err)
           Right (cmd :: String
cmd, args :: [String]
args) -> [String] -> String -> GHCi ()
doWithArgs [String]
args String
cmd

doWithArgs :: [String] -> String -> GHCi ()
doWithArgs :: [String] -> String -> GHCi ()
doWithArgs args :: [String]
args cmd :: String
cmd = [String] -> GHCi ()
enqueueCommands ["System.Environment.withArgs " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                                       [String] -> String
forall a. Show a => a -> String
show [String]
args String -> String -> String
forall a. [a] -> [a] -> [a]
++ " (" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmd String -> String -> String
forall a. [a] -> [a] -> [a]
++ ")"]

-----------------------------------------------------------------------------
-- :cd

changeDirectory :: String -> InputT GHCi ()
changeDirectory :: String -> InputT GHCi ()
changeDirectory "" = do
  -- :cd on its own changes to the user's home directory
  Either IOException String
either_dir <- IO (Either IOException String)
-> InputT GHCi (Either IOException String)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException String)
 -> InputT GHCi (Either IOException String))
-> IO (Either IOException String)
-> InputT GHCi (Either IOException String)
forall a b. (a -> b) -> a -> b
$ IO String -> IO (Either IOException String)
forall a. IO a -> IO (Either IOException a)
tryIO IO String
getHomeDirectory
  case Either IOException String
either_dir of
     Left _e :: IOException
_e -> () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
     Right dir :: String
dir -> String -> InputT GHCi ()
changeDirectory String
dir
changeDirectory dir :: String
dir = do
  ModuleGraph
graph <- InputT GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
  Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([ModSummary] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null ([ModSummary] -> Bool) -> [ModSummary] -> Bool
forall a b. (a -> b) -> a -> b
$ ModuleGraph -> [ModSummary]
GHC.mgModSummaries ModuleGraph
graph)) (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$
        IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
  [Target] -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => [Target] -> m ()
GHC.setTargets []
  SuccessFlag
_ <- LoadHowMuch -> InputT GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => LoadHowMuch -> m SuccessFlag
GHC.load LoadHowMuch
LoadAllTargets
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi () -> InputT GHCi ()) -> GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> [ModSummary] -> GHCi ()
setContextAfterLoad Bool
False []
  InputT GHCi ()
forall (m :: * -> *). GhcMonad m => m ()
GHC.workingDirectoryChanged
  String
dir' <- String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath String
dir
  IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
setCurrentDirectory String
dir'
  DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  -- With -fexternal-interpreter, we have to change the directory of the subprocess too.
  -- (this gives consistent behaviour with and without -fexternal-interpreter)
  Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags) (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    HscEnv
hsc_env <- InputT GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
    ForeignHValue
fhv <- String -> InputT GHCi ForeignHValue
forall (m :: * -> *). GhcMonad m => String -> m ForeignHValue
compileGHCiExpr (String -> InputT GHCi ForeignHValue)
-> String -> InputT GHCi ForeignHValue
forall a b. (a -> b) -> a -> b
$
      "System.Directory.setCurrentDirectory " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
forall a. Show a => a -> String
show String
dir'
    IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ HscEnv -> ForeignHValue -> IO ()
evalIO HscEnv
hsc_env ForeignHValue
fhv

trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess :: m SuccessFlag -> m SuccessFlag
trySuccess act :: m SuccessFlag
act =
    (SourceError -> m SuccessFlag) -> m SuccessFlag -> m SuccessFlag
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError (\e :: SourceError
e -> do SourceError -> m ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException SourceError
e
                                SuccessFlag -> m SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
Failed) (m SuccessFlag -> m SuccessFlag) -> m SuccessFlag -> m SuccessFlag
forall a b. (a -> b) -> a -> b
$ do
      m SuccessFlag
act

-----------------------------------------------------------------------------
-- :edit

editFile :: String -> InputT GHCi ()
editFile :: String -> InputT GHCi ()
editFile str :: String
str =
  do String
file <- if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
str then GHCi String -> InputT GHCi String
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi String
chooseEditFile else String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath String
str
     GHCiState
st <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
     [(FastString, Int)]
errs <- IO [(FastString, Int)] -> InputT GHCi [(FastString, Int)]
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [(FastString, Int)] -> InputT GHCi [(FastString, Int)])
-> IO [(FastString, Int)] -> InputT GHCi [(FastString, Int)]
forall a b. (a -> b) -> a -> b
$ IORef [(FastString, Int)] -> IO [(FastString, Int)]
forall a. IORef a -> IO a
readIORef (IORef [(FastString, Int)] -> IO [(FastString, Int)])
-> IORef [(FastString, Int)] -> IO [(FastString, Int)]
forall a b. (a -> b) -> a -> b
$ GHCiState -> IORef [(FastString, Int)]
lastErrorLocations GHCiState
st
     let cmd :: String
cmd = GHCiState -> String
editor GHCiState
st
     Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
cmd)
       (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "editor not set, use :set editor")
     String
lineOpt <- IO String -> InputT GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> InputT GHCi String)
-> IO String -> InputT GHCi String
forall a b. (a -> b) -> a -> b
$ do
         let sameFile :: String -> String -> IO Bool
sameFile p1 :: String
p1 p2 :: String
p2 = (String -> String -> Bool) -> IO String -> IO String -> IO Bool
forall (f :: * -> *) a b c.
Applicative f =>
(a -> b -> c) -> f a -> f b -> f c
liftA2 String -> String -> Bool
forall a. Eq a => a -> a -> Bool
(==) (String -> IO String
canonicalizePath String
p1) (String -> IO String
canonicalizePath String
p2)
              IO Bool -> (IOException -> IO Bool) -> IO Bool
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` (\_ -> Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False)

         [(FastString, Int)]
curFileErrs <- ((FastString, Int) -> IO Bool)
-> [(FastString, Int)] -> IO [(FastString, Int)]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (\(f :: FastString
f, _) -> FastString -> String
unpackFS FastString
f String -> String -> IO Bool
`sameFile` String
file) [(FastString, Int)]
errs
         String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> IO String) -> String -> IO String
forall a b. (a -> b) -> a -> b
$ case [(FastString, Int)]
curFileErrs of
             (_, line :: Int
line):_ -> " +" String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> String
forall a. Show a => a -> String
show Int
line
             _ -> ""
     let cmdArgs :: String
cmdArgs = ' 'Char -> String -> String
forall a. a -> [a] -> [a]
:(String
file String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
lineOpt)
     ExitCode
code <- IO ExitCode -> InputT GHCi ExitCode
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ExitCode -> InputT GHCi ExitCode)
-> IO ExitCode -> InputT GHCi ExitCode
forall a b. (a -> b) -> a -> b
$ String -> IO ExitCode
system (String
cmd String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
cmdArgs)

     Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ExitCode
code ExitCode -> ExitCode -> Bool
forall a. Eq a => a -> a -> Bool
== ExitCode
ExitSuccess)
       (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> InputT GHCi ()
reloadModule ""

-- The user didn't specify a file so we pick one for them.
-- Our strategy is to pick the first module that failed to load,
-- or otherwise the first target.
--
-- XXX: Can we figure out what happened if the depndecy analysis fails
--      (e.g., because the porgrammeer mistyped the name of a module)?
-- XXX: Can we figure out the location of an error to pass to the editor?
-- XXX: if we could figure out the list of errors that occured during the
-- last load/reaload, then we could start the editor focused on the first
-- of those.
chooseEditFile :: GHCi String
chooseEditFile :: GHCi String
chooseEditFile =
  do let hasFailed :: ModSummary -> f Bool
hasFailed x :: ModSummary
x = (Bool -> Bool) -> f Bool -> f Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Bool -> Bool
not (f Bool -> f Bool) -> f Bool -> f Bool
forall a b. (a -> b) -> a -> b
$ ModuleName -> f Bool
forall (m :: * -> *). GhcMonad m => ModuleName -> m Bool
GHC.isLoaded (ModuleName -> f Bool) -> ModuleName -> f Bool
forall a b. (a -> b) -> a -> b
$ ModSummary -> ModuleName
GHC.ms_mod_name ModSummary
x

     ModuleGraph
graph <- GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
     ModuleGraph
failed_graph <-
       [ModSummary] -> ModuleGraph
GHC.mkModuleGraph ([ModSummary] -> ModuleGraph)
-> GHCi [ModSummary] -> GHCi ModuleGraph
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (ModSummary -> GHCi Bool) -> [ModSummary] -> GHCi [ModSummary]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM ModSummary -> GHCi Bool
forall (f :: * -> *). GhcMonad f => ModSummary -> f Bool
hasFailed (ModuleGraph -> [ModSummary]
GHC.mgModSummaries ModuleGraph
graph)
     let order :: ModuleGraph -> [ModSummary]
order g :: ModuleGraph
g  = [SCC ModSummary] -> [ModSummary]
forall a. [SCC a] -> [a]
flattenSCCs ([SCC ModSummary] -> [ModSummary])
-> [SCC ModSummary] -> [ModSummary]
forall a b. (a -> b) -> a -> b
$ Bool -> ModuleGraph -> Maybe ModuleName -> [SCC ModSummary]
GHC.topSortModuleGraph Bool
True ModuleGraph
g Maybe ModuleName
forall a. Maybe a
Nothing
         pick :: [ModSummary] -> Maybe String
pick xs :: [ModSummary]
xs  = case [ModSummary]
xs of
                      x :: ModSummary
x : _ -> ModLocation -> Maybe String
GHC.ml_hs_file (ModSummary -> ModLocation
GHC.ms_location ModSummary
x)
                      _     -> Maybe String
forall a. Maybe a
Nothing

     case [ModSummary] -> Maybe String
pick (ModuleGraph -> [ModSummary]
order ModuleGraph
failed_graph) of
       Just file :: String
file -> String -> GHCi String
forall (m :: * -> *) a. Monad m => a -> m a
return String
file
       Nothing   ->
         do [Target]
targets <- GHCi [Target]
forall (m :: * -> *). GhcMonad m => m [Target]
GHC.getTargets
            case [Maybe String] -> Maybe String
forall (t :: * -> *) (m :: * -> *) a.
(Foldable t, MonadPlus m) =>
t (m a) -> m a
msum ((Target -> Maybe String) -> [Target] -> [Maybe String]
forall a b. (a -> b) -> [a] -> [b]
map Target -> Maybe String
fromTarget [Target]
targets) of
              Just file :: String
file -> String -> GHCi String
forall (m :: * -> *) a. Monad m => a -> m a
return String
file
              Nothing   -> GhcException -> GHCi String
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "No files to edit.")

  where fromTarget :: Target -> Maybe String
fromTarget (GHC.Target (GHC.TargetFile f :: String
f _) _ _) = String -> Maybe String
forall a. a -> Maybe a
Just String
f
        fromTarget _ = Maybe String
forall a. Maybe a
Nothing -- when would we get a module target?


-----------------------------------------------------------------------------
-- :def

defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
defineMacro :: Bool -> String -> GHCi ()
defineMacro _ (':':_) =
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "macro name cannot start with a colon"
defineMacro overwrite :: Bool
overwrite s :: String
s = do
  let (macro_name :: String
macro_name, definition :: String
definition) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isSpace String
s
  [Command]
macros <- GHCiState -> [Command]
ghci_macros (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  let defined :: [String]
defined = (Command -> String) -> [Command] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Command -> String
cmdName [Command]
macros
  if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
macro_name
        then if [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
defined
                then IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "no macros defined"
                else IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStr ("the following macros are defined:\n" String -> String -> String
forall a. [a] -> [a] -> [a]
++
                                      [String] -> String
unlines [String]
defined)
        else do
  if (Bool -> Bool
not Bool
overwrite Bool -> Bool -> Bool
&& String
macro_name String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [String]
defined)
        then GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError
                ("macro '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
macro_name String -> String -> String
forall a. [a] -> [a] -> [a]
++ "' is already defined"))
        else do

  -- compile the expression
  (SourceError -> GHCi ()) -> GHCi () -> GHCi ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    LHsExpr GhcPs
step <- GHCi (LHsExpr GhcPs)
getGhciStepIO
    LHsExpr GhcPs
expr <- String -> GHCi (LHsExpr GhcPs)
forall (m :: * -> *). GhcMonad m => String -> m (LHsExpr GhcPs)
GHC.parseExpr String
definition
    -- > ghciStepIO . definition :: String -> IO String
    let stringTy :: LHsType GhcPs
stringTy = IdP GhcPs -> LHsType GhcPs
forall (p :: Pass). IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar IdP GhcPs
RdrName
stringTy_RDR
        ioM :: LHsType GhcPs
ioM = IdP GhcPs -> LHsType GhcPs
forall (p :: Pass). IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar (Name -> RdrName
forall thing. NamedThing thing => thing -> RdrName
getRdrName Name
ioTyConName) LHsType GhcPs -> LHsType GhcPs -> LHsType GhcPs
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
`nlHsAppTy` LHsType GhcPs
stringTy
        body :: LHsExpr GhcPs
body = IdP GhcPs -> LHsExpr GhcPs
forall (id :: Pass). IdP (GhcPass id) -> LHsExpr (GhcPass id)
nlHsVar IdP GhcPs
RdrName
compose_RDR LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
forall (id :: Pass).
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
`mkHsApp` (LHsExpr GhcPs -> LHsExpr GhcPs
forall (id :: Pass). LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsPar LHsExpr GhcPs
step)
                                   LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
forall (id :: Pass).
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
`mkHsApp` (LHsExpr GhcPs -> LHsExpr GhcPs
forall (id :: Pass). LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
nlHsPar LHsExpr GhcPs
expr)
        tySig :: LHsSigWcType GhcPs
tySig = LHsType GhcPs -> LHsSigWcType GhcPs
mkLHsSigWcType (LHsType GhcPs
stringTy LHsType GhcPs -> LHsType GhcPs -> LHsType GhcPs
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
`nlHsFunTy` LHsType GhcPs
ioM)
        new_expr :: LHsExpr GhcPs
new_expr = SrcSpan -> HsExpr GhcPs -> LHsExpr GhcPs
forall l e. l -> e -> GenLocated l e
L (LHsExpr GhcPs -> SrcSpan
forall a. HasSrcSpan a => a -> SrcSpan
getLoc LHsExpr GhcPs
expr) (HsExpr GhcPs -> LHsExpr GhcPs) -> HsExpr GhcPs -> LHsExpr GhcPs
forall a b. (a -> b) -> a -> b
$ XExprWithTySig GhcPs
-> LHsExpr GhcPs -> LHsSigWcType (NoGhcTc GhcPs) -> HsExpr GhcPs
forall p.
XExprWithTySig p
-> LHsExpr p -> LHsSigWcType (NoGhcTc p) -> HsExpr p
ExprWithTySig NoExt
XExprWithTySig GhcPs
noExt LHsExpr GhcPs
body LHsSigWcType GhcPs
LHsSigWcType (NoGhcTc GhcPs)
tySig
    ForeignHValue
hv <- LHsExpr GhcPs -> GHCi ForeignHValue
forall (m :: * -> *).
GhcMonad m =>
LHsExpr GhcPs -> m ForeignHValue
GHC.compileParsedExprRemote LHsExpr GhcPs
new_expr

    let newCmd :: Command
newCmd = Command :: String
-> (String -> InputT GHCi Bool)
-> Bool
-> CompletionFunc GHCi
-> Command
Command { cmdName :: String
cmdName = String
macro_name
                         , cmdAction :: String -> InputT GHCi Bool
cmdAction = GHCi Bool -> InputT GHCi Bool
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Bool -> InputT GHCi Bool)
-> (String -> GHCi Bool) -> String -> InputT GHCi Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ForeignHValue -> String -> GHCi Bool
runMacro ForeignHValue
hv
                         , cmdHidden :: Bool
cmdHidden = Bool
False
                         , cmdCompletionFunc :: CompletionFunc GHCi
cmdCompletionFunc = CompletionFunc GHCi
forall (m :: * -> *). Monad m => CompletionFunc m
noCompletion
                         }

    -- later defined macros have precedence
    (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \s :: GHCiState
s ->
        let filtered :: [Command]
filtered = [ Command
cmd | Command
cmd <- [Command]
macros, Command -> String
cmdName Command
cmd String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
macro_name ]
        in GHCiState
s { ghci_macros :: [Command]
ghci_macros = Command
newCmd Command -> [Command] -> [Command]
forall a. a -> [a] -> [a]
: [Command]
filtered }

runMacro :: GHC.ForeignHValue{-String -> IO String-} -> String -> GHCi Bool
runMacro :: ForeignHValue -> String -> GHCi Bool
runMacro fun :: ForeignHValue
fun s :: String
s = do
  HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
  String
str <- IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ HscEnv -> ForeignHValue -> String -> IO String
evalStringToIOString HscEnv
hsc_env ForeignHValue
fun String
s
  [String] -> GHCi ()
enqueueCommands (String -> [String]
lines String
str)
  Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False


-----------------------------------------------------------------------------
-- :undef

undefineMacro :: String -> GHCi ()
undefineMacro :: String -> GHCi ()
undefineMacro str :: String
str = (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> GHCi ()
forall (m :: * -> *). (Monad m, HasGhciState m) => String -> m ()
undef (String -> [String]
words String
str)
 where undef :: String -> m ()
undef macro_name :: String
macro_name = do
        [Command]
cmds <- GHCiState -> [Command]
ghci_macros (GHCiState -> [Command]) -> m GHCiState -> m [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> m GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
        if (String
macro_name String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` (Command -> String) -> [Command] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Command -> String
cmdName [Command]
cmds)
           then GhcException -> m ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError
                ("macro '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
macro_name String -> String -> String
forall a. [a] -> [a] -> [a]
++ "' is not defined"))
           else do
            -- This is a tad racy but really, it's a shell
            (GHCiState -> GHCiState) -> m ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> m ())
-> (GHCiState -> GHCiState) -> m ()
forall a b. (a -> b) -> a -> b
$ \s :: GHCiState
s ->
                GHCiState
s { ghci_macros :: [Command]
ghci_macros = (Command -> Bool) -> [Command] -> [Command]
forall a. (a -> Bool) -> [a] -> [a]
filter ((String -> String -> Bool
forall a. Eq a => a -> a -> Bool
/= String
macro_name) (String -> Bool) -> (Command -> String) -> Command -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Command -> String
cmdName)
                                         (GHCiState -> [Command]
ghci_macros GHCiState
s) }


-----------------------------------------------------------------------------
-- :cmd

cmdCmd :: String -> GHCi ()
cmdCmd :: String -> GHCi ()
cmdCmd str :: String
str = (SourceError -> GHCi ()) -> GHCi () -> GHCi ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    LHsExpr GhcPs
step <- GHCi (LHsExpr GhcPs)
getGhciStepIO
    LHsExpr GhcPs
expr <- String -> GHCi (LHsExpr GhcPs)
forall (m :: * -> *). GhcMonad m => String -> m (LHsExpr GhcPs)
GHC.parseExpr String
str
    -- > ghciStepIO str :: IO String
    let new_expr :: LHsExpr GhcPs
new_expr = LHsExpr GhcPs
step LHsExpr GhcPs -> LHsExpr GhcPs -> LHsExpr GhcPs
forall (id :: Pass).
LHsExpr (GhcPass id)
-> LHsExpr (GhcPass id) -> LHsExpr (GhcPass id)
`mkHsApp` LHsExpr GhcPs
expr
    ForeignHValue
hv <- LHsExpr GhcPs -> GHCi ForeignHValue
forall (m :: * -> *).
GhcMonad m =>
LHsExpr GhcPs -> m ForeignHValue
GHC.compileParsedExprRemote LHsExpr GhcPs
new_expr

    HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
    String
cmds <- IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> GHCi String) -> IO String -> GHCi String
forall a b. (a -> b) -> a -> b
$ HscEnv -> ForeignHValue -> IO String
evalString HscEnv
hsc_env ForeignHValue
hv
    [String] -> GHCi ()
enqueueCommands (String -> [String]
lines String
cmds)

-- | Generate a typed ghciStepIO expression
-- @ghciStepIO :: Ty String -> IO String@.
getGhciStepIO :: GHCi (LHsExpr GhcPs)
getGhciStepIO :: GHCi (LHsExpr GhcPs)
getGhciStepIO = do
  Name
ghciTyConName <- GHCi Name
forall (m :: * -> *). GhcMonad m => m Name
GHC.getGHCiMonad
  let stringTy :: LHsType GhcPs
stringTy = IdP GhcPs -> LHsType GhcPs
forall (p :: Pass). IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar IdP GhcPs
RdrName
stringTy_RDR
      ghciM :: LHsType GhcPs
ghciM = IdP GhcPs -> LHsType GhcPs
forall (p :: Pass). IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar (Name -> RdrName
forall thing. NamedThing thing => thing -> RdrName
getRdrName Name
ghciTyConName) LHsType GhcPs -> LHsType GhcPs -> LHsType GhcPs
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
`nlHsAppTy` LHsType GhcPs
stringTy
      ioM :: LHsType GhcPs
ioM = IdP GhcPs -> LHsType GhcPs
forall (p :: Pass). IdP (GhcPass p) -> LHsType (GhcPass p)
nlHsTyVar (Name -> RdrName
forall thing. NamedThing thing => thing -> RdrName
getRdrName Name
ioTyConName) LHsType GhcPs -> LHsType GhcPs -> LHsType GhcPs
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
`nlHsAppTy` LHsType GhcPs
stringTy
      body :: LHsExpr GhcPs
body = IdP GhcPs -> LHsExpr GhcPs
forall (id :: Pass). IdP (GhcPass id) -> LHsExpr (GhcPass id)
nlHsVar (Name -> RdrName
forall thing. NamedThing thing => thing -> RdrName
getRdrName Name
ghciStepIoMName)
      tySig :: LHsSigWcType GhcPs
tySig = LHsType GhcPs -> LHsSigWcType GhcPs
mkLHsSigWcType (LHsType GhcPs
ghciM LHsType GhcPs -> LHsType GhcPs -> LHsType GhcPs
forall (p :: Pass).
LHsType (GhcPass p) -> LHsType (GhcPass p) -> LHsType (GhcPass p)
`nlHsFunTy` LHsType GhcPs
ioM)
  LHsExpr GhcPs -> GHCi (LHsExpr GhcPs)
forall (m :: * -> *) a. Monad m => a -> m a
return (LHsExpr GhcPs -> GHCi (LHsExpr GhcPs))
-> LHsExpr GhcPs -> GHCi (LHsExpr GhcPs)
forall a b. (a -> b) -> a -> b
$ SrcSpanLess (LHsExpr GhcPs) -> LHsExpr GhcPs
forall a. HasSrcSpan a => SrcSpanLess a -> a
noLoc (SrcSpanLess (LHsExpr GhcPs) -> LHsExpr GhcPs)
-> SrcSpanLess (LHsExpr GhcPs) -> LHsExpr GhcPs
forall a b. (a -> b) -> a -> b
$ XExprWithTySig GhcPs
-> LHsExpr GhcPs -> LHsSigWcType (NoGhcTc GhcPs) -> HsExpr GhcPs
forall p.
XExprWithTySig p
-> LHsExpr p -> LHsSigWcType (NoGhcTc p) -> HsExpr p
ExprWithTySig NoExt
XExprWithTySig GhcPs
noExt LHsExpr GhcPs
body LHsSigWcType GhcPs
LHsSigWcType (NoGhcTc GhcPs)
tySig

-----------------------------------------------------------------------------
-- :check

checkModule :: String -> InputT GHCi ()
checkModule :: String -> InputT GHCi ()
checkModule m :: String
m = do
  let modl :: ModuleName
modl = String -> ModuleName
GHC.mkModuleName String
m
  Bool
ok <- (SourceError -> InputT GHCi Bool)
-> InputT GHCi Bool -> InputT GHCi Bool
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError (\e :: SourceError
e -> SourceError -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException SourceError
e InputT GHCi () -> InputT GHCi Bool -> InputT GHCi Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False) (InputT GHCi Bool -> InputT GHCi Bool)
-> InputT GHCi Bool -> InputT GHCi Bool
forall a b. (a -> b) -> a -> b
$ do
          TypecheckedModule
r <- ParsedModule -> InputT GHCi TypecheckedModule
forall (m :: * -> *).
GhcMonad m =>
ParsedModule -> m TypecheckedModule
GHC.typecheckModule (ParsedModule -> InputT GHCi TypecheckedModule)
-> InputT GHCi ParsedModule -> InputT GHCi TypecheckedModule
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ModSummary -> InputT GHCi ParsedModule
forall (m :: * -> *). GhcMonad m => ModSummary -> m ParsedModule
GHC.parseModule (ModSummary -> InputT GHCi ParsedModule)
-> InputT GHCi ModSummary -> InputT GHCi ParsedModule
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ModuleName -> InputT GHCi ModSummary
forall (m :: * -> *). GhcMonad m => ModuleName -> m ModSummary
GHC.getModSummary ModuleName
modl
          DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
          IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
           case TypecheckedModule -> ModuleInfo
forall m. TypecheckedMod m => m -> ModuleInfo
GHC.moduleInfo TypecheckedModule
r of
             cm :: ModuleInfo
cm | Just scope :: [Name]
scope <- ModuleInfo -> Maybe [Name]
GHC.modInfoTopLevelScope ModuleInfo
cm ->
                let
                    (loc :: [Name]
loc, glob :: [Name]
glob) = ASSERT( all isExternalName scope )
                                  (Name -> Bool) -> [Name] -> ([Name], [Name])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ((ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
== ModuleName
modl) (ModuleName -> Bool) -> (Name -> ModuleName) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Module -> ModuleName
GHC.moduleName (Module -> ModuleName) -> (Name -> Module) -> Name -> ModuleName
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasDebugCallStack => Name -> Module
Name -> Module
GHC.nameModule) [Name]
scope
                in
                        (String -> MsgDoc
text "global names: " MsgDoc -> MsgDoc -> MsgDoc
<+> [Name] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [Name]
glob) MsgDoc -> MsgDoc -> MsgDoc
$$
                        (String -> MsgDoc
text "local  names: " MsgDoc -> MsgDoc -> MsgDoc
<+> [Name] -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr [Name]
loc)
             _ -> MsgDoc
empty
          Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
  SuccessFlag -> Bool -> InputT GHCi ()
afterLoad (Bool -> SuccessFlag
successIf Bool
ok) Bool
False

-----------------------------------------------------------------------------
-- :doc

docCmd :: String -> InputT GHCi ()
docCmd :: String -> InputT GHCi ()
docCmd "" =
  GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax: ':doc <thing-you-want-docs-for>'")
docCmd s :: String
s  = do
  -- TODO: Maybe also get module headers for module names
  [Name]
names <- String -> InputT GHCi [Name]
forall (m :: * -> *). GhcMonad m => String -> m [Name]
GHC.parseName String
s
  [Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)]
e_docss <- (Name
 -> InputT
      GHCi
      (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)))
-> [Name]
-> InputT
     GHCi
     [Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Name
-> InputT
     GHCi
     (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString))
forall (m :: * -> *).
GhcMonad m =>
Name
-> m (Either
        GetDocsFailure (Maybe HsDocString, Map Int HsDocString))
GHC.getDocs [Name]
names
  [MsgDoc]
sdocs <- (Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)
 -> InputT GHCi MsgDoc)
-> [Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)]
-> InputT GHCi [MsgDoc]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ((GetDocsFailure -> InputT GHCi MsgDoc)
-> ((Maybe HsDocString, Map Int HsDocString) -> InputT GHCi MsgDoc)
-> Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)
-> InputT GHCi MsgDoc
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either GetDocsFailure -> InputT GHCi MsgDoc
forall (m :: * -> *). GhcMonad m => GetDocsFailure -> m MsgDoc
handleGetDocsFailure (MsgDoc -> InputT GHCi MsgDoc
forall (f :: * -> *) a. Applicative f => a -> f a
pure (MsgDoc -> InputT GHCi MsgDoc)
-> ((Maybe HsDocString, Map Int HsDocString) -> MsgDoc)
-> (Maybe HsDocString, Map Int HsDocString)
-> InputT GHCi MsgDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Maybe HsDocString, Map Int HsDocString) -> MsgDoc
pprDocs)) [Either GetDocsFailure (Maybe HsDocString, Map Int HsDocString)]
e_docss
  let sdocs' :: MsgDoc
sdocs' = [MsgDoc] -> MsgDoc
vcat (MsgDoc -> [MsgDoc] -> [MsgDoc]
forall a. a -> [a] -> [a]
intersperse (String -> MsgDoc
text "") [MsgDoc]
sdocs)
  PrintUnqualified
unqual <- InputT GHCi PrintUnqualified
forall (m :: * -> *). GhcMonad m => m PrintUnqualified
GHC.getPrintUnqual
  DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ())
-> (MsgDoc -> IO ()) -> MsgDoc -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> IO ()) -> (MsgDoc -> String) -> MsgDoc -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
dflags PrintUnqualified
unqual) MsgDoc
sdocs'

-- TODO: also print arg docs.
pprDocs :: (Maybe HsDocString, Map Int HsDocString) -> SDoc
pprDocs :: (Maybe HsDocString, Map Int HsDocString) -> MsgDoc
pprDocs (mb_decl_docs :: Maybe HsDocString
mb_decl_docs, _arg_docs :: Map Int HsDocString
_arg_docs) =
  MsgDoc -> (HsDocString -> MsgDoc) -> Maybe HsDocString -> MsgDoc
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
    (String -> MsgDoc
text "<has no documentation>")
    (String -> MsgDoc
text (String -> MsgDoc)
-> (HsDocString -> String) -> HsDocString -> MsgDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HsDocString -> String
unpackHDS)
    Maybe HsDocString
mb_decl_docs

handleGetDocsFailure :: GHC.GhcMonad m => GetDocsFailure -> m SDoc
handleGetDocsFailure :: GetDocsFailure -> m MsgDoc
handleGetDocsFailure no_docs :: GetDocsFailure
no_docs = do
  DynFlags
dflags <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let msg :: String
msg = DynFlags -> GetDocsFailure -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags GetDocsFailure
no_docs
  GhcException -> m MsgDoc
forall a. GhcException -> a
throwGhcException (GhcException -> m MsgDoc) -> GhcException -> m MsgDoc
forall a b. (a -> b) -> a -> b
$ case GetDocsFailure
no_docs of
    NameHasNoModule {} -> String -> GhcException
Sorry String
msg
    NoDocsInIface {} -> String -> GhcException
InstallationError String
msg
    InteractiveName -> String -> GhcException
ProgramError String
msg

-----------------------------------------------------------------------------
-- :load, :add, :reload

-- | Sets '-fdefer-type-errors' if 'defer' is true, executes 'load' and unsets
-- '-fdefer-type-errors' again if it has not been set before.
wrapDeferTypeErrors :: InputT GHCi a -> InputT GHCi a
wrapDeferTypeErrors :: InputT GHCi a -> InputT GHCi a
wrapDeferTypeErrors load :: InputT GHCi a
load =
  InputT GHCi DynFlags
-> (DynFlags -> InputT GHCi ())
-> (DynFlags -> InputT GHCi a)
-> InputT GHCi a
forall (m :: * -> *) a b c.
ExceptionMonad m =>
m a -> (a -> m b) -> (a -> m c) -> m c
gbracket
    (do
      -- Force originalFlags to avoid leaking the associated HscEnv
      !DynFlags
originalFlags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
      InputT GHCi [InstalledUnitId] -> InputT GHCi ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (InputT GHCi [InstalledUnitId] -> InputT GHCi ())
-> InputT GHCi [InstalledUnitId] -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> InputT GHCi [InstalledUnitId]
forall (m :: * -> *). GhcMonad m => DynFlags -> m [InstalledUnitId]
GHC.setProgramDynFlags (DynFlags -> InputT GHCi [InstalledUnitId])
-> DynFlags -> InputT GHCi [InstalledUnitId]
forall a b. (a -> b) -> a -> b
$
         GeneralFlag -> DynFlags -> DynFlags
setGeneralFlag' GeneralFlag
Opt_DeferTypeErrors DynFlags
originalFlags
      DynFlags -> InputT GHCi DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return DynFlags
originalFlags)
    (\originalFlags :: DynFlags
originalFlags -> InputT GHCi [InstalledUnitId] -> InputT GHCi ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (InputT GHCi [InstalledUnitId] -> InputT GHCi ())
-> InputT GHCi [InstalledUnitId] -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> InputT GHCi [InstalledUnitId]
forall (m :: * -> *). GhcMonad m => DynFlags -> m [InstalledUnitId]
GHC.setProgramDynFlags DynFlags
originalFlags)
    (\_ -> InputT GHCi a
load)

loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule :: [(String, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule fs :: [(String, Maybe Phase)]
fs = do
  (_, result :: Either SomeException SuccessFlag
result) <- (SuccessFlag -> Maybe Integer)
-> InputT GHCi SuccessFlag
-> InputT GHCi (ActionStats, Either SomeException SuccessFlag)
forall a.
(a -> Maybe Integer)
-> InputT GHCi a
-> InputT GHCi (ActionStats, Either SomeException a)
runAndPrintStats (Maybe Integer -> SuccessFlag -> Maybe Integer
forall a b. a -> b -> a
const Maybe Integer
forall a. Maybe a
Nothing) ([(String, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' [(String, Maybe Phase)]
fs)
  (SomeException -> InputT GHCi SuccessFlag)
-> (SuccessFlag -> InputT GHCi SuccessFlag)
-> Either SomeException SuccessFlag
-> InputT GHCi SuccessFlag
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (IO SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO SuccessFlag -> InputT GHCi SuccessFlag)
-> (SomeException -> IO SuccessFlag)
-> SomeException
-> InputT GHCi SuccessFlag
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SomeException -> IO SuccessFlag
forall e a. Exception e => e -> IO a
Exception.throwIO) SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return Either SomeException SuccessFlag
result

-- | @:load@ command
loadModule_ :: [FilePath] -> InputT GHCi ()
loadModule_ :: [String] -> InputT GHCi ()
loadModule_ fs :: [String]
fs = InputT GHCi SuccessFlag -> InputT GHCi ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (InputT GHCi SuccessFlag -> InputT GHCi ())
-> InputT GHCi SuccessFlag -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ [(String, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule ([String] -> [Maybe Phase] -> [(String, Maybe Phase)]
forall a b. [a] -> [b] -> [(a, b)]
zip [String]
fs (Maybe Phase -> [Maybe Phase]
forall a. a -> [a]
repeat Maybe Phase
forall a. Maybe a
Nothing))

loadModuleDefer :: [FilePath] -> InputT GHCi ()
loadModuleDefer :: [String] -> InputT GHCi ()
loadModuleDefer = InputT GHCi () -> InputT GHCi ()
forall a. InputT GHCi a -> InputT GHCi a
wrapDeferTypeErrors (InputT GHCi () -> InputT GHCi ())
-> ([String] -> InputT GHCi ()) -> [String] -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> InputT GHCi ()
loadModule_

loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' :: [(String, Maybe Phase)] -> InputT GHCi SuccessFlag
loadModule' files :: [(String, Maybe Phase)]
files = do
  let (filenames :: [String]
filenames, phases :: [Maybe Phase]
phases) = [(String, Maybe Phase)] -> ([String], [Maybe Phase])
forall a b. [(a, b)] -> ([a], [b])
unzip [(String, Maybe Phase)]
files
  [String]
exp_filenames <- (String -> InputT GHCi String) -> [String] -> InputT GHCi [String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath [String]
filenames
  let files' :: [(String, Maybe Phase)]
files' = [String] -> [Maybe Phase] -> [(String, Maybe Phase)]
forall a b. [a] -> [b] -> [(a, b)]
zip [String]
exp_filenames [Maybe Phase]
phases
  [Target]
targets <- ((String, Maybe Phase) -> InputT GHCi Target)
-> [(String, Maybe Phase)] -> InputT GHCi [Target]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ((String -> Maybe Phase -> InputT GHCi Target)
-> (String, Maybe Phase) -> InputT GHCi Target
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry String -> Maybe Phase -> InputT GHCi Target
forall (m :: * -> *).
GhcMonad m =>
String -> Maybe Phase -> m Target
GHC.guessTarget) [(String, Maybe Phase)]
files'

  -- NOTE: we used to do the dependency anal first, so that if it
  -- fails we didn't throw away the current set of modules.  This would
  -- require some re-working of the GHC interface, so we'll leave it
  -- as a ToDo for now.

  HscEnv
hsc_env <- InputT GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession

  -- Grab references to the currently loaded modules so that we can
  -- see if they leak.
  let !dflags :: DynFlags
dflags = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
  LeakIndicators
leak_indicators <- if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_GhciLeakCheck DynFlags
dflags
    then IO LeakIndicators -> InputT GHCi LeakIndicators
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO LeakIndicators -> InputT GHCi LeakIndicators)
-> IO LeakIndicators -> InputT GHCi LeakIndicators
forall a b. (a -> b) -> a -> b
$ HscEnv -> IO LeakIndicators
getLeakIndicators HscEnv
hsc_env
    else LeakIndicators -> InputT GHCi LeakIndicators
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> LeakIndicators
forall a. String -> a
panic "no leak indicators")

  -- unload first
  Bool
_ <- InputT GHCi Bool
forall (m :: * -> *). GhcMonad m => m Bool
GHC.abandonAll
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
discardActiveBreakPoints
  [Target] -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => [Target] -> m ()
GHC.setTargets []
  SuccessFlag
_ <- LoadHowMuch -> InputT GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => LoadHowMuch -> m SuccessFlag
GHC.load LoadHowMuch
LoadAllTargets

  [Target] -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => [Target] -> m ()
GHC.setTargets [Target]
targets
  SuccessFlag
success <- Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo Bool
False LoadHowMuch
LoadAllTargets
  Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_GhciLeakCheck DynFlags
dflags) (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$
    IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> LeakIndicators -> IO ()
checkLeakIndicators DynFlags
dflags LeakIndicators
leak_indicators
  SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
success

-- | @:add@ command
addModule :: [FilePath] -> InputT GHCi ()
addModule :: [String] -> InputT GHCi ()
addModule files :: [String]
files = do
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
revertCAFs -- always revert CAFs on load/add.
  [String]
files' <- (String -> InputT GHCi String) -> [String] -> InputT GHCi [String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath [String]
files
  [Target]
targets <- (String -> InputT GHCi Target) -> [String] -> InputT GHCi [Target]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\m :: String
m -> String -> Maybe Phase -> InputT GHCi Target
forall (m :: * -> *).
GhcMonad m =>
String -> Maybe Phase -> m Target
GHC.guessTarget String
m Maybe Phase
forall a. Maybe a
Nothing) [String]
files'
  [Target]
targets' <- (Target -> InputT GHCi Bool) -> [Target] -> InputT GHCi [Target]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM Target -> InputT GHCi Bool
checkTarget [Target]
targets
  -- remove old targets with the same id; e.g. for :add *M
  (TargetId -> InputT GHCi ()) -> [TargetId] -> InputT GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ TargetId -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => TargetId -> m ()
GHC.removeTarget [ TargetId
tid | Target tid :: TargetId
tid _ _ <- [Target]
targets' ]
  (Target -> InputT GHCi ()) -> [Target] -> InputT GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Target -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => Target -> m ()
GHC.addTarget [Target]
targets'
  SuccessFlag
_ <- Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo Bool
False LoadHowMuch
LoadAllTargets
  () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
  where
    checkTarget :: Target -> InputT GHCi Bool
    checkTarget :: Target -> InputT GHCi Bool
checkTarget (Target (TargetModule m :: ModuleName
m) _ _) = ModuleName -> InputT GHCi Bool
checkTargetModule ModuleName
m
    checkTarget (Target (TargetFile f :: String
f _) _ _) = IO Bool -> InputT GHCi Bool
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> InputT GHCi Bool) -> IO Bool -> InputT GHCi Bool
forall a b. (a -> b) -> a -> b
$ String -> IO Bool
checkTargetFile String
f

    checkTargetModule :: ModuleName -> InputT GHCi Bool
    checkTargetModule :: ModuleName -> InputT GHCi Bool
checkTargetModule m :: ModuleName
m = do
      HscEnv
hsc_env <- InputT GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
      FindResult
result <- IO FindResult -> InputT GHCi FindResult
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO FindResult -> InputT GHCi FindResult)
-> IO FindResult -> InputT GHCi FindResult
forall a b. (a -> b) -> a -> b
$
        HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
Finder.findImportedModule HscEnv
hsc_env ModuleName
m (FastString -> Maybe FastString
forall a. a -> Maybe a
Just (String -> FastString
fsLit "this"))
      case FindResult
result of
        Found _ _ -> Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True
        _ -> (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$
          "Module " String -> String -> String
forall a. [a] -> [a] -> [a]
++ ModuleName -> String
moduleNameString ModuleName
m String -> String -> String
forall a. [a] -> [a] -> [a]
++ " not found") InputT GHCi () -> InputT GHCi Bool -> InputT GHCi Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

    checkTargetFile :: String -> IO Bool
    checkTargetFile :: String -> IO Bool
checkTargetFile f :: String
f = do
      Bool
exists <- (String -> IO Bool
doesFileExist String
f) :: IO Bool
      Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
exists (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "File " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
f String -> String -> String
forall a. [a] -> [a] -> [a]
++ " not found"
      Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
exists

-- | @:unadd@ command
unAddModule :: [FilePath] -> InputT GHCi ()
unAddModule :: [String] -> InputT GHCi ()
unAddModule files :: [String]
files = do
  [String]
files' <- (String -> InputT GHCi String) -> [String] -> InputT GHCi [String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath [String]
files
  [Target]
targets <- (String -> InputT GHCi Target) -> [String] -> InputT GHCi [Target]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM (\m :: String
m -> String -> Maybe Phase -> InputT GHCi Target
forall (m :: * -> *).
GhcMonad m =>
String -> Maybe Phase -> m Target
GHC.guessTarget String
m Maybe Phase
forall a. Maybe a
Nothing) [String]
files'
  (TargetId -> InputT GHCi ()) -> [TargetId] -> InputT GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ TargetId -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => TargetId -> m ()
GHC.removeTarget [ TargetId
tid | Target tid :: TargetId
tid _ _ <- [Target]
targets ]
  SuccessFlag
_ <- Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo Bool
False LoadHowMuch
LoadAllTargets
  () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-- | @:reload@ command
reloadModule :: String -> InputT GHCi ()
reloadModule :: String -> InputT GHCi ()
reloadModule m :: String
m = InputT GHCi SuccessFlag -> InputT GHCi ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (InputT GHCi SuccessFlag -> InputT GHCi ())
-> InputT GHCi SuccessFlag -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo Bool
True LoadHowMuch
loadTargets
  where
    loadTargets :: LoadHowMuch
loadTargets | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
m    = LoadHowMuch
LoadAllTargets
                | Bool
otherwise = ModuleName -> LoadHowMuch
LoadUpTo (String -> ModuleName
GHC.mkModuleName String
m)

reloadModuleDefer :: String -> InputT GHCi ()
reloadModuleDefer :: String -> InputT GHCi ()
reloadModuleDefer = InputT GHCi () -> InputT GHCi ()
forall a. InputT GHCi a -> InputT GHCi a
wrapDeferTypeErrors (InputT GHCi () -> InputT GHCi ())
-> (String -> InputT GHCi ()) -> String -> InputT GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> InputT GHCi ()
reloadModule

-- | Load/compile targets and (optionally) collect module-info
--
-- This collects the necessary SrcSpan annotated type information (via
-- 'collectInfo') required by the @:all-types@, @:loc-at@, @:type-at@,
-- and @:uses@ commands.
--
-- Meta-info collection is not enabled by default and needs to be
-- enabled explicitly via @:set +c@.  The reason is that collecting
-- the type-information for all sub-spans can be quite expensive, and
-- since those commands are designed to be used by editors and
-- tooling, it's useless to collect this data for normal GHCi
-- sessions.
doLoadAndCollectInfo :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoadAndCollectInfo retain_context :: Bool
retain_context howmuch :: LoadHowMuch
howmuch = do
  Bool
doCollectInfo <- GHCi Bool -> InputT GHCi Bool
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCiOption -> GHCi Bool
isOptionSet GHCiOption
CollectInfo)

  Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad Bool
retain_context LoadHowMuch
howmuch InputT GHCi SuccessFlag
-> (SuccessFlag -> InputT GHCi SuccessFlag)
-> InputT GHCi SuccessFlag
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
    Succeeded | Bool
doCollectInfo -> do
      [ModSummary]
mod_summaries <- ModuleGraph -> [ModSummary]
GHC.mgModSummaries (ModuleGraph -> [ModSummary])
-> InputT GHCi ModuleGraph -> InputT GHCi [ModSummary]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> InputT GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
getModuleGraph
      [ModuleName]
loaded <- (ModuleName -> InputT GHCi Bool)
-> [ModuleName] -> InputT GHCi [ModuleName]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM ModuleName -> InputT GHCi Bool
forall (m :: * -> *). GhcMonad m => ModuleName -> m Bool
GHC.isLoaded ([ModuleName] -> InputT GHCi [ModuleName])
-> [ModuleName] -> InputT GHCi [ModuleName]
forall a b. (a -> b) -> a -> b
$ (ModSummary -> ModuleName) -> [ModSummary] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map ModSummary -> ModuleName
GHC.ms_mod_name [ModSummary]
mod_summaries
      Map ModuleName ModInfo
v <- GHCiState -> Map ModuleName ModInfo
mod_infos (GHCiState -> Map ModuleName ModInfo)
-> InputT GHCi GHCiState -> InputT GHCi (Map ModuleName ModInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      !Map ModuleName ModInfo
newInfos <- Map ModuleName ModInfo
-> [ModuleName] -> InputT GHCi (Map ModuleName ModInfo)
forall (m :: * -> *).
GhcMonad m =>
Map ModuleName ModInfo
-> [ModuleName] -> m (Map ModuleName ModInfo)
collectInfo Map ModuleName ModInfo
v [ModuleName]
loaded
      (GHCiState -> GHCiState) -> InputT GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st { mod_infos :: Map ModuleName ModInfo
mod_infos = Map ModuleName ModInfo
newInfos })
      SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
Succeeded
    flag :: SuccessFlag
flag -> SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
flag

doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
doLoad retain_context :: Bool
retain_context howmuch :: LoadHowMuch
howmuch = do
  -- turn off breakpoints before we load: we can't turn them off later, because
  -- the ModBreaks will have gone away.
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
discardActiveBreakPoints

  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
resetLastErrorLocations
  -- Enable buffering stdout and stderr as we're compiling. Keeping these
  -- handles unbuffered will just slow the compilation down, especially when
  -- compiling in parallel.
  InputT GHCi ()
-> (() -> InputT GHCi ())
-> (() -> InputT GHCi SuccessFlag)
-> InputT GHCi SuccessFlag
forall (m :: * -> *) a b c.
ExceptionMonad m =>
m a -> (a -> m b) -> (a -> m c) -> m c
gbracket (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do Handle -> BufferMode -> IO ()
hSetBuffering Handle
stdout BufferMode
LineBuffering
                        Handle -> BufferMode -> IO ()
hSetBuffering Handle
stderr BufferMode
LineBuffering)
           (\_ ->
            IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do Handle -> BufferMode -> IO ()
hSetBuffering Handle
stdout BufferMode
NoBuffering
                        Handle -> BufferMode -> IO ()
hSetBuffering Handle
stderr BufferMode
NoBuffering) ((() -> InputT GHCi SuccessFlag) -> InputT GHCi SuccessFlag)
-> (() -> InputT GHCi SuccessFlag) -> InputT GHCi SuccessFlag
forall a b. (a -> b) -> a -> b
$ \_ -> do
      SuccessFlag
ok <- InputT GHCi SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => m SuccessFlag -> m SuccessFlag
trySuccess (InputT GHCi SuccessFlag -> InputT GHCi SuccessFlag)
-> InputT GHCi SuccessFlag -> InputT GHCi SuccessFlag
forall a b. (a -> b) -> a -> b
$ LoadHowMuch -> InputT GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => LoadHowMuch -> m SuccessFlag
GHC.load LoadHowMuch
howmuch
      SuccessFlag -> Bool -> InputT GHCi ()
afterLoad SuccessFlag
ok Bool
retain_context
      SuccessFlag -> InputT GHCi SuccessFlag
forall (m :: * -> *) a. Monad m => a -> m a
return SuccessFlag
ok


afterLoad :: SuccessFlag
          -> Bool   -- keep the remembered_ctx, as far as possible (:reload)
          -> InputT GHCi ()
afterLoad :: SuccessFlag -> Bool -> InputT GHCi ()
afterLoad ok :: SuccessFlag
ok retain_context :: Bool
retain_context = do
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
revertCAFs  -- always revert CAFs on load.
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi ()
discardTickArrays
  [ModSummary]
loaded_mods <- InputT GHCi [ModSummary]
forall (m :: * -> *). GhcMonad m => m [ModSummary]
getLoadedModules
  SuccessFlag -> [ModSummary] -> InputT GHCi ()
modulesLoadedMsg SuccessFlag
ok [ModSummary]
loaded_mods
  GHCi () -> InputT GHCi ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi () -> InputT GHCi ()) -> GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> [ModSummary] -> GHCi ()
setContextAfterLoad Bool
retain_context [ModSummary]
loaded_mods

setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
setContextAfterLoad :: Bool -> [ModSummary] -> GHCi ()
setContextAfterLoad keep_ctxt :: Bool
keep_ctxt [] = do
  Bool -> [InteractiveImport] -> GHCi ()
setContextKeepingPackageModules Bool
keep_ctxt []
setContextAfterLoad keep_ctxt :: Bool
keep_ctxt ms :: [ModSummary]
ms = do
  -- load a target if one is available, otherwise load the topmost module.
  [Target]
targets <- GHCi [Target]
forall (m :: * -> *). GhcMonad m => m [Target]
GHC.getTargets
  case [ ModSummary
m | Just m :: ModSummary
m <- (Target -> Maybe ModSummary) -> [Target] -> [Maybe ModSummary]
forall a b. (a -> b) -> [a] -> [b]
map ([ModSummary] -> Target -> Maybe ModSummary
findTarget [ModSummary]
ms) [Target]
targets ] of
        []    ->
          let graph :: ModuleGraph
graph = [ModSummary] -> ModuleGraph
GHC.mkModuleGraph [ModSummary]
ms
              graph' :: [ModSummary]
graph' = [SCC ModSummary] -> [ModSummary]
forall a. [SCC a] -> [a]
flattenSCCs (Bool -> ModuleGraph -> Maybe ModuleName -> [SCC ModSummary]
GHC.topSortModuleGraph Bool
True ModuleGraph
graph Maybe ModuleName
forall a. Maybe a
Nothing)
          in ModSummary -> GHCi ()
load_this ([ModSummary] -> ModSummary
forall a. [a] -> a
last [ModSummary]
graph')
        (m :: ModSummary
m:_) ->
          ModSummary -> GHCi ()
load_this ModSummary
m
 where
   findTarget :: [ModSummary] -> Target -> Maybe ModSummary
findTarget mds :: [ModSummary]
mds t :: Target
t
    = case (ModSummary -> Bool) -> [ModSummary] -> [ModSummary]
forall a. (a -> Bool) -> [a] -> [a]
filter (ModSummary -> Target -> Bool
`matches` Target
t) [ModSummary]
mds of
        []    -> Maybe ModSummary
forall a. Maybe a
Nothing
        (m :: ModSummary
m:_) -> ModSummary -> Maybe ModSummary
forall a. a -> Maybe a
Just ModSummary
m

   summary :: ModSummary
summary matches :: ModSummary -> Target -> Bool
`matches` Target (TargetModule m :: ModuleName
m) _ _
        = ModSummary -> ModuleName
GHC.ms_mod_name ModSummary
summary ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
== ModuleName
m
   summary :: ModSummary
summary `matches` Target (TargetFile f :: String
f _) _ _
        | Just f' :: String
f' <- ModLocation -> Maybe String
GHC.ml_hs_file (ModSummary -> ModLocation
GHC.ms_location ModSummary
summary)   = String
f String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
f'
   _ `matches` _
        = Bool
False

   load_this :: ModSummary -> GHCi ()
load_this summary :: ModSummary
summary | Module
m <- ModSummary -> Module
GHC.ms_mod ModSummary
summary = do
        Bool
is_interp <- Module -> GHCi Bool
forall (m :: * -> *). GhcMonad m => Module -> m Bool
GHC.moduleIsInterpreted Module
m
        DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
        let star_ok :: Bool
star_ok = Bool
is_interp Bool -> Bool -> Bool
&& Bool -> Bool
not (DynFlags -> Bool
safeLanguageOn DynFlags
dflags)
              -- We import the module with a * iff
              --   - it is interpreted, and
              --   - -XSafe is off (it doesn't allow *-imports)
        let new_ctx :: [InteractiveImport]
new_ctx | Bool
star_ok   = [ModuleName -> InteractiveImport
mkIIModule (Module -> ModuleName
GHC.moduleName Module
m)]
                    | Bool
otherwise = [ModuleName -> InteractiveImport
mkIIDecl   (Module -> ModuleName
GHC.moduleName Module
m)]
        Bool -> [InteractiveImport] -> GHCi ()
setContextKeepingPackageModules Bool
keep_ctxt [InteractiveImport]
new_ctx


-- | Keep any package modules (except Prelude) when changing the context.
setContextKeepingPackageModules
        :: Bool                 -- True  <=> keep all of remembered_ctx
                                -- False <=> just keep package imports
        -> [InteractiveImport]  -- new context
        -> GHCi ()

setContextKeepingPackageModules :: Bool -> [InteractiveImport] -> GHCi ()
setContextKeepingPackageModules keep_ctx :: Bool
keep_ctx trans_ctx :: [InteractiveImport]
trans_ctx = do

  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  let rem_ctx :: [InteractiveImport]
rem_ctx = GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st
  [InteractiveImport]
new_rem_ctx <- if Bool
keep_ctx then [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a. Monad m => a -> m a
return [InteractiveImport]
rem_ctx
                             else [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports [InteractiveImport]
rem_ctx
  GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{ remembered_ctx :: [InteractiveImport]
remembered_ctx = [InteractiveImport]
new_rem_ctx,
                   transient_ctx :: [InteractiveImport]
transient_ctx  = [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
filterSubsumed [InteractiveImport]
new_rem_ctx [InteractiveImport]
trans_ctx }
  GHCi ()
setGHCContextFromGHCiState

-- | Filters a list of 'InteractiveImport', clearing out any home package
-- imports so only imports from external packages are preserved.  ('IIModule'
-- counts as a home package import, because we are only able to bring a
-- full top-level into scope when the source is available.)
keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
keepPackageImports = (InteractiveImport -> GHCi Bool)
-> [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM InteractiveImport -> GHCi Bool
is_pkg_import
  where
     is_pkg_import :: InteractiveImport -> GHCi Bool
     is_pkg_import :: InteractiveImport -> GHCi Bool
is_pkg_import (IIModule _) = Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
     is_pkg_import (IIDecl d :: ImportDecl GhcPs
d)
         = do Either SomeException Module
e <- GHCi Module -> GHCi (Either SomeException Module)
forall (m :: * -> *) e a.
(ExceptionMonad m, Exception e) =>
m a -> m (Either e a)
gtry (GHCi Module -> GHCi (Either SomeException Module))
-> GHCi Module -> GHCi (Either SomeException Module)
forall a b. (a -> b) -> a -> b
$ ModuleName -> Maybe FastString -> GHCi Module
forall (m :: * -> *).
GhcMonad m =>
ModuleName -> Maybe FastString -> m Module
GHC.findModule ModuleName
mod_name ((StringLiteral -> FastString)
-> Maybe StringLiteral -> Maybe FastString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap StringLiteral -> FastString
sl_fs (Maybe StringLiteral -> Maybe FastString)
-> Maybe StringLiteral -> Maybe FastString
forall a b. (a -> b) -> a -> b
$ ImportDecl GhcPs -> Maybe StringLiteral
forall pass. ImportDecl pass -> Maybe StringLiteral
ideclPkgQual ImportDecl GhcPs
d)
              case Either SomeException Module
e :: Either SomeException Module of
                Left _  -> Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
                Right m :: Module
m -> Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (Bool -> Bool
not (Module -> Bool
isHomeModule Module
m))
        where
          mod_name :: SrcSpanLess (Located ModuleName)
mod_name = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d)


modulesLoadedMsg :: SuccessFlag -> [GHC.ModSummary] -> InputT GHCi ()
modulesLoadedMsg :: SuccessFlag -> [ModSummary] -> InputT GHCi ()
modulesLoadedMsg ok :: SuccessFlag
ok mods :: [ModSummary]
mods = do
  DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  PrintUnqualified
unqual <- InputT GHCi PrintUnqualified
forall (m :: * -> *). GhcMonad m => m PrintUnqualified
GHC.getPrintUnqual

  MsgDoc
msg <- if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ShowLoadedModules DynFlags
dflags
         then do
               [MsgDoc]
mod_names <- (ModSummary -> InputT GHCi MsgDoc)
-> [ModSummary] -> InputT GHCi [MsgDoc]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM ModSummary -> InputT GHCi MsgDoc
forall (m :: * -> *). GhcMonad m => ModSummary -> m MsgDoc
mod_name [ModSummary]
mods
               let mod_commas :: MsgDoc
mod_commas
                     | [ModSummary] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ModSummary]
mods = String -> MsgDoc
text "none."
                     | Bool
otherwise = [MsgDoc] -> MsgDoc
hsep (MsgDoc -> [MsgDoc] -> [MsgDoc]
punctuate MsgDoc
comma [MsgDoc]
mod_names) MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text "."
               MsgDoc -> InputT GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> InputT GHCi MsgDoc) -> MsgDoc -> InputT GHCi MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc
status MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text ", modules loaded:" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
mod_commas
         else do
               MsgDoc -> InputT GHCi MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> InputT GHCi MsgDoc) -> MsgDoc -> InputT GHCi MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc
status MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text ","
                    MsgDoc -> MsgDoc -> MsgDoc
<+> Int -> MsgDoc -> MsgDoc
speakNOf ([ModSummary] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [ModSummary]
mods) (String -> MsgDoc
text "module") MsgDoc -> MsgDoc -> MsgDoc
<+> "loaded."

  Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0) (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$
     IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
dflags PrintUnqualified
unqual MsgDoc
msg
  where
    status :: MsgDoc
status = case SuccessFlag
ok of
                  Failed    -> String -> MsgDoc
text "Failed"
                  Succeeded -> String -> MsgDoc
text "Ok"

    mod_name :: ModSummary -> m MsgDoc
mod_name mod :: ModSummary
mod = do
        Bool
is_interpreted <- ModSummary -> m Bool
forall (f :: * -> *). GhcMonad f => ModSummary -> f Bool
GHC.moduleIsBootOrNotObjectLinkable ModSummary
mod
        MsgDoc -> m MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> m MsgDoc) -> MsgDoc -> m MsgDoc
forall a b. (a -> b) -> a -> b
$ if Bool
is_interpreted
                 then Module -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (ModSummary -> Module
GHC.ms_mod ModSummary
mod)
                 else Module -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (ModSummary -> Module
GHC.ms_mod ModSummary
mod)
                      MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc -> MsgDoc
parens (String -> MsgDoc
text (String -> MsgDoc) -> String -> MsgDoc
forall a b. (a -> b) -> a -> b
$ String -> String
normalise (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ ModSummary -> String
msObjFilePath ModSummary
mod)
                      -- Fix #9887

-- | Run an 'ExceptT' wrapped 'GhcMonad' while handling source errors
-- and printing 'throwE' strings to 'stderr'
runExceptGhcMonad :: GHC.GhcMonad m => ExceptT SDoc m () -> m ()
runExceptGhcMonad :: ExceptT MsgDoc m () -> m ()
runExceptGhcMonad act :: ExceptT MsgDoc m ()
act = (SourceError -> m ()) -> m () -> m ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> m ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
                        (MsgDoc -> m ()) -> (() -> m ()) -> Either MsgDoc () -> m ()
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either MsgDoc -> m ()
forall (m :: * -> *). (HasDynFlags m, MonadIO m) => MsgDoc -> m ()
handleErr () -> m ()
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either MsgDoc () -> m ()) -> m (Either MsgDoc ()) -> m ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<<
                        ExceptT MsgDoc m () -> m (Either MsgDoc ())
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT ExceptT MsgDoc m ()
act
  where
    handleErr :: MsgDoc -> m ()
handleErr sdoc :: MsgDoc
sdoc = do
        DynFlags
dflags <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
        IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> (MsgDoc -> IO ()) -> MsgDoc -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> (MsgDoc -> String) -> MsgDoc -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
dflags PrintUnqualified
alwaysQualify (MsgDoc -> m ()) -> MsgDoc -> m ()
forall a b. (a -> b) -> a -> b
$ MsgDoc
sdoc

-- | Inverse of 'runExceptT' for \"pure\" computations
-- (c.f. 'except' for 'Except')
exceptT :: Applicative m => Either e a -> ExceptT e m a
exceptT :: Either e a -> ExceptT e m a
exceptT = m (Either e a) -> ExceptT e m a
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (m (Either e a) -> ExceptT e m a)
-> (Either e a -> m (Either e a)) -> Either e a -> ExceptT e m a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Either e a -> m (Either e a)
forall (f :: * -> *) a. Applicative f => a -> f a
pure

makeHDL' :: Clash.Backend.Backend backend
         => (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
         -> IORef ClashOpts
         -> [FilePath]
         -> InputT GHCi ()
makeHDL' :: (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
makeHDL' backend :: Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend
backend opts :: IORef ClashOpts
opts lst :: [String]
lst = (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
forall (m :: * -> *) backend.
(GhcMonad m, Backend backend) =>
(Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> m ()
makeHDL Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend
backend IORef ClashOpts
opts ([String] -> InputT GHCi ())
-> InputT GHCi [String] -> InputT GHCi ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< case [String]
lst of
  srcs :: [String]
srcs@(_:_) -> [String] -> InputT GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return [String]
srcs
  []         -> do
    ModuleGraph
modGraph <- InputT GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
    let sortedGraph :: [SCC ModSummary]
sortedGraph = Bool -> ModuleGraph -> Maybe ModuleName -> [SCC ModSummary]
GHC.topSortModuleGraph Bool
False ModuleGraph
modGraph Maybe ModuleName
forall a. Maybe a
Nothing
    [String] -> InputT GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> InputT GHCi [String])
-> [String] -> InputT GHCi [String]
forall a b. (a -> b) -> a -> b
$ case ([SCC ModSummary] -> [SCC ModSummary]
forall a. [a] -> [a]
reverse [SCC ModSummary]
sortedGraph) of
      ((AcyclicSCC top :: ModSummary
top) : _) -> Maybe String -> [String]
forall a. Maybe a -> [a]
maybeToList (Maybe String -> [String]) -> Maybe String -> [String]
forall a b. (a -> b) -> a -> b
$ (ModLocation -> Maybe String
GHC.ml_hs_file (ModLocation -> Maybe String)
-> (ModSummary -> ModLocation) -> ModSummary -> Maybe String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ModSummary -> ModLocation
GHC.ms_location) ModSummary
top
      _                      -> []

makeHDL :: GHC.GhcMonad m
        => Clash.Backend.Backend backend
        => (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
        -> IORef ClashOpts
        -> [FilePath]
        -> m ()
makeHDL :: (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> m ()
makeHDL backend :: Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend
backend optsRef :: IORef ClashOpts
optsRef srcs :: [String]
srcs = do
  DynFlags
dflags <- m DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getSessionDynFlags
  IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ do UTCTime
startTime <- IO UTCTime
Clock.getCurrentTime
              ClashOpts
opts0  <- IORef ClashOpts -> IO ClashOpts
forall a. IORef a -> IO a
readIORef IORef ClashOpts
optsRef
              let opts1 :: ClashOpts
opts1  = ClashOpts
opts0 { opt_color :: OverridingBool
opt_color = DynFlags -> OverridingBool
useColor DynFlags
dflags }
              let iw :: Int
iw     = ClashOpts -> Int
opt_intWidth ClashOpts
opts1
                  fp :: Bool
fp     = ClashOpts -> Bool
opt_floatSupport ClashOpts
opts1
                  syn :: HdlSyn
syn    = ClashOpts -> HdlSyn
opt_hdlSyn ClashOpts
opts1
                  color :: OverridingBool
color  = ClashOpts -> OverridingBool
opt_color ClashOpts
opts1
                  esc :: Bool
esc    = ClashOpts -> Bool
opt_escapedIds ClashOpts
opts1
                  frcUdf :: Maybe (Maybe Int)
frcUdf = ClashOpts -> Maybe (Maybe Int)
opt_forceUndefined ClashOpts
opts1
                  hdl :: HDL
hdl    = backend -> HDL
forall state. Backend state => state -> HDL
Clash.Backend.hdlKind backend
backend'
                  -- determine whether `-outputdir` was used
                  outputDir :: Maybe String
outputDir = do String
odir <- DynFlags -> Maybe String
objectDir DynFlags
dflags
                                 String
hidir <- DynFlags -> Maybe String
hiDir DynFlags
dflags
                                 String
sdir <- DynFlags -> Maybe String
stubDir DynFlags
dflags
                                 String
ddir <- DynFlags -> Maybe String
dumpDir DynFlags
dflags
                                 if (String -> Bool) -> [String] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
odir) [String
hidir,String
sdir,String
ddir]
                                    then String -> Maybe String
forall a. a -> Maybe a
Just String
odir
                                    else Maybe String
forall a. Maybe a
Nothing
                  idirs :: [String]
idirs = DynFlags -> [String]
importPaths DynFlags
dflags
                  opts2 :: ClashOpts
opts2 = ClashOpts
opts1 { opt_hdlDir :: Maybe String
opt_hdlDir = Maybe String
-> (String -> Maybe String) -> Maybe String -> Maybe String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Maybe String
outputDir String -> Maybe String
forall a. a -> Maybe a
Just (ClashOpts -> Maybe String
opt_hdlDir ClashOpts
opts1)
                                , opt_importPaths :: [String]
opt_importPaths = [String]
idirs}
                  backend' :: backend
backend' = Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend
backend Int
iw HdlSyn
syn Bool
esc Maybe (Maybe Int)
frcUdf

              DynFlags -> IO ()
checkMonoLocalBinds DynFlags
dflags
              ClashOpts -> [String] -> IO ()
forall (t :: * -> *). Foldable t => ClashOpts -> t String -> IO ()
checkImportDirs ClashOpts
opts0 [String]
idirs

              [String]
primDirs <- backend -> IO [String]
forall state. Backend state => state -> IO [String]
Clash.Backend.primDirs backend
backend'

              [String] -> (String -> IO ()) -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [String]
srcs ((String -> IO ()) -> IO ()) -> (String -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \src :: String
src -> do
                -- Generate bindings:
                let dbs :: [String]
dbs = [String] -> [String]
forall a. [a] -> [a]
reverse [String
p | PackageDB (PkgConfFile p :: String
p) <- DynFlags -> [PackageDBFlag]
packageDBFlags DynFlags
dflags]
                (bindingsMap :: BindingMap
bindingsMap,tcm :: TyConMap
tcm,tupTcm :: IntMap TyConName
tupTcm,topEntities :: [(Id, Maybe TopEntity, Maybe Id)]
topEntities,primMap :: CompiledPrimMap
primMap,reprs :: [DataRepr']
reprs) <-
                  OverridingBool
-> [String]
-> [String]
-> [String]
-> HDL
-> String
-> Maybe DynFlags
-> IO
     (BindingMap, TyConMap, IntMap TyConName,
      [(Id, Maybe TopEntity, Maybe Id)], CompiledPrimMap, [DataRepr'])
generateBindings OverridingBool
color [String]
primDirs [String]
idirs [String]
dbs HDL
hdl String
src (DynFlags -> Maybe DynFlags
forall a. a -> Maybe a
Just DynFlags
dflags)
                UTCTime
prepTime <- UTCTime
startTime UTCTime -> BindingMap -> BindingMap
forall a b. NFData a => a -> b -> b
`deepseq` BindingMap
bindingsMap BindingMap -> TyConMap -> TyConMap
forall a b. NFData a => a -> b -> b
`deepseq` TyConMap
tcm TyConMap -> IO UTCTime -> IO UTCTime
forall a b. NFData a => a -> b -> b
`deepseq` IO UTCTime
Clock.getCurrentTime
                let prepStartDiff :: String
prepStartDiff = UTCTime -> UTCTime -> String
reportTimeDiff UTCTime
prepTime UTCTime
startTime
                String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "GHC+Clash: Loading modules cumulatively took " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
prepStartDiff

                -- Generate HDL:
                CustomReprs
-> BindingMap
-> Maybe backend
-> CompiledPrimMap
-> TyConMap
-> IntMap TyConName
-> (CustomReprs
    -> TyConMap
    -> Type
    -> State HWMap (Maybe (Either String FilteredHWType)))
-> PrimEvaluator
-> [(Id, Maybe TopEntity, Maybe Id)]
-> ClashOpts
-> (UTCTime, UTCTime)
-> IO ()
forall backend.
Backend backend =>
CustomReprs
-> BindingMap
-> Maybe backend
-> CompiledPrimMap
-> TyConMap
-> IntMap TyConName
-> (CustomReprs
    -> TyConMap
    -> Type
    -> State HWMap (Maybe (Either String FilteredHWType)))
-> PrimEvaluator
-> [(Id, Maybe TopEntity, Maybe Id)]
-> ClashOpts
-> (UTCTime, UTCTime)
-> IO ()
Clash.Driver.generateHDL
                  ([DataRepr'] -> CustomReprs
buildCustomReprs [DataRepr']
reprs)
                  BindingMap
bindingsMap
                  (backend -> Maybe backend
forall a. a -> Maybe a
Just backend
backend')
                  CompiledPrimMap
primMap
                  TyConMap
tcm
                  IntMap TyConName
tupTcm
                  (Int
-> Bool
-> CustomReprs
-> TyConMap
-> Type
-> State HWMap (Maybe (Either String FilteredHWType))
ghcTypeToHWType Int
iw Bool
fp)
                  PrimEvaluator
reduceConstant
                  [(Id, Maybe TopEntity, Maybe Id)]
topEntities
                  ClashOpts
opts2
                  (UTCTime
startTime,UTCTime
prepTime)

makeVHDL :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
makeVHDL :: IORef ClashOpts -> [String] -> InputT GHCi ()
makeVHDL = (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> VHDLState)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
forall backend.
Backend backend =>
(Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
makeHDL' (Backend VHDLState =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> VHDLState
forall state.
Backend state =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> state
Clash.Backend.initBackend @VHDLState)

makeVerilog :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
makeVerilog :: IORef ClashOpts -> [String] -> InputT GHCi ()
makeVerilog = (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> VerilogState)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
forall backend.
Backend backend =>
(Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
makeHDL' (Backend VerilogState =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> VerilogState
forall state.
Backend state =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> state
Clash.Backend.initBackend @VerilogState)

makeSystemVerilog :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
makeSystemVerilog :: IORef ClashOpts -> [String] -> InputT GHCi ()
makeSystemVerilog = (Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> SystemVerilogState)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
forall backend.
Backend backend =>
(Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> backend)
-> IORef ClashOpts -> [String] -> InputT GHCi ()
makeHDL' (Backend SystemVerilogState =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> SystemVerilogState
forall state.
Backend state =>
Int -> HdlSyn -> Bool -> Maybe (Maybe Int) -> state
Clash.Backend.initBackend @SystemVerilogState)

-----------------------------------------------------------------------------
-- | @:type@ command. See also Note [TcRnExprMode] in TcRnDriver.

typeOfExpr :: String -> InputT GHCi ()
typeOfExpr :: String -> InputT GHCi ()
typeOfExpr str :: String
str = (SourceError -> InputT GHCi ()) -> InputT GHCi () -> InputT GHCi ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    let (mode :: TcRnExprMode
mode, expr_str :: String
expr_str) = case (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isSpace String
str of
          ("+d", rest :: String
rest) -> (TcRnExprMode
GHC.TM_Default, (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest)
          ("+v", rest :: String
rest) -> (TcRnExprMode
GHC.TM_NoInst,  (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest)
          _            -> (TcRnExprMode
GHC.TM_Inst,    String
str)
    Type
ty <- TcRnExprMode -> String -> InputT GHCi Type
forall (m :: * -> *).
GhcMonad m =>
TcRnExprMode -> String -> m Type
GHC.exprType TcRnExprMode
mode String
expr_str
    MsgDoc -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> InputT GHCi ()) -> MsgDoc -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
sep [String -> MsgDoc
text String
expr_str, Int -> MsgDoc -> MsgDoc
nest 2 (MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
pprTypeForUser Type
ty)]

-----------------------------------------------------------------------------
-- | @:type-at@ command

typeAtCmd :: String -> InputT GHCi ()
typeAtCmd :: String -> InputT GHCi ()
typeAtCmd str :: String
str = ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => ExceptT MsgDoc m () -> m ()
runExceptGhcMonad (ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ())
-> ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    (span' :: RealSrcSpan
span',sample :: String
sample) <- Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall (m :: * -> *) e a.
Applicative m =>
Either e a -> ExceptT e m a
exceptT (Either MsgDoc (RealSrcSpan, String)
 -> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String))
-> Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall a b. (a -> b) -> a -> b
$ String -> Either MsgDoc (RealSrcSpan, String)
parseSpanArg String
str
    Map ModuleName ModInfo
infos      <- GHCiState -> Map ModuleName ModInfo
mod_infos (GHCiState -> Map ModuleName ModInfo)
-> ExceptT MsgDoc (InputT GHCi) GHCiState
-> ExceptT MsgDoc (InputT GHCi) (Map ModuleName ModInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExceptT MsgDoc (InputT GHCi) GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    (info :: ModInfo
info, ty :: Type
ty) <- Map ModuleName ModInfo
-> RealSrcSpan
-> String
-> ExceptT MsgDoc (InputT GHCi) (ModInfo, Type)
forall (m :: * -> *).
GhcMonad m =>
Map ModuleName ModInfo
-> RealSrcSpan -> String -> ExceptT MsgDoc m (ModInfo, Type)
findType Map ModuleName ModInfo
infos RealSrcSpan
span' String
sample
    InputT GHCi () -> ExceptT MsgDoc (InputT GHCi) ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (InputT GHCi () -> ExceptT MsgDoc (InputT GHCi) ())
-> InputT GHCi () -> ExceptT MsgDoc (InputT GHCi) ()
forall a b. (a -> b) -> a -> b
$ ModuleInfo -> MsgDoc -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => ModuleInfo -> MsgDoc -> m ()
printForUserModInfo (ModInfo -> ModuleInfo
modinfoInfo ModInfo
info)
                               ([MsgDoc] -> MsgDoc
sep [String -> MsgDoc
text String
sample,Int -> MsgDoc -> MsgDoc
nest 2 (MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Type
ty)])

-----------------------------------------------------------------------------
-- | @:uses@ command

usesCmd :: String -> InputT GHCi ()
usesCmd :: String -> InputT GHCi ()
usesCmd str :: String
str = ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => ExceptT MsgDoc m () -> m ()
runExceptGhcMonad (ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ())
-> ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    (span' :: RealSrcSpan
span',sample :: String
sample) <- Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall (m :: * -> *) e a.
Applicative m =>
Either e a -> ExceptT e m a
exceptT (Either MsgDoc (RealSrcSpan, String)
 -> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String))
-> Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall a b. (a -> b) -> a -> b
$ String -> Either MsgDoc (RealSrcSpan, String)
parseSpanArg String
str
    Map ModuleName ModInfo
infos  <- GHCiState -> Map ModuleName ModInfo
mod_infos (GHCiState -> Map ModuleName ModInfo)
-> ExceptT MsgDoc (InputT GHCi) GHCiState
-> ExceptT MsgDoc (InputT GHCi) (Map ModuleName ModInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExceptT MsgDoc (InputT GHCi) GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    [SrcSpan]
uses   <- Map ModuleName ModInfo
-> RealSrcSpan -> String -> ExceptT MsgDoc (InputT GHCi) [SrcSpan]
forall (m :: * -> *).
GhcMonad m =>
Map ModuleName ModInfo
-> RealSrcSpan -> String -> ExceptT MsgDoc m [SrcSpan]
findNameUses Map ModuleName ModInfo
infos RealSrcSpan
span' String
sample
    [SrcSpan]
-> (SrcSpan -> ExceptT MsgDoc (InputT GHCi) ())
-> ExceptT MsgDoc (InputT GHCi) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ [SrcSpan]
uses (IO () -> ExceptT MsgDoc (InputT GHCi) ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> ExceptT MsgDoc (InputT GHCi) ())
-> (SrcSpan -> IO ()) -> SrcSpan -> ExceptT MsgDoc (InputT GHCi) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> IO ()) -> (SrcSpan -> String) -> SrcSpan -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SrcSpan -> String
showSrcSpan)

-----------------------------------------------------------------------------
-- | @:loc-at@ command

locAtCmd :: String -> InputT GHCi ()
locAtCmd :: String -> InputT GHCi ()
locAtCmd str :: String
str = ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => ExceptT MsgDoc m () -> m ()
runExceptGhcMonad (ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ())
-> ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    (span' :: RealSrcSpan
span',sample :: String
sample) <- Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall (m :: * -> *) e a.
Applicative m =>
Either e a -> ExceptT e m a
exceptT (Either MsgDoc (RealSrcSpan, String)
 -> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String))
-> Either MsgDoc (RealSrcSpan, String)
-> ExceptT MsgDoc (InputT GHCi) (RealSrcSpan, String)
forall a b. (a -> b) -> a -> b
$ String -> Either MsgDoc (RealSrcSpan, String)
parseSpanArg String
str
    Map ModuleName ModInfo
infos    <- GHCiState -> Map ModuleName ModInfo
mod_infos (GHCiState -> Map ModuleName ModInfo)
-> ExceptT MsgDoc (InputT GHCi) GHCiState
-> ExceptT MsgDoc (InputT GHCi) (Map ModuleName ModInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExceptT MsgDoc (InputT GHCi) GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    (_,_,sp :: SrcSpan
sp) <- Map ModuleName ModInfo
-> RealSrcSpan
-> String
-> ExceptT MsgDoc (InputT GHCi) (ModInfo, Name, SrcSpan)
forall (m :: * -> *).
GhcMonad m =>
Map ModuleName ModInfo
-> RealSrcSpan
-> String
-> ExceptT MsgDoc m (ModInfo, Name, SrcSpan)
findLoc Map ModuleName ModInfo
infos RealSrcSpan
span' String
sample
    IO () -> ExceptT MsgDoc (InputT GHCi) ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> ExceptT MsgDoc (InputT GHCi) ())
-> (SrcSpan -> IO ()) -> SrcSpan -> ExceptT MsgDoc (InputT GHCi) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> IO ()) -> (SrcSpan -> String) -> SrcSpan -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SrcSpan -> String
showSrcSpan (SrcSpan -> ExceptT MsgDoc (InputT GHCi) ())
-> SrcSpan -> ExceptT MsgDoc (InputT GHCi) ()
forall a b. (a -> b) -> a -> b
$ SrcSpan
sp

-----------------------------------------------------------------------------
-- | @:all-types@ command

allTypesCmd :: String -> InputT GHCi ()
allTypesCmd :: String -> InputT GHCi ()
allTypesCmd _ = ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => ExceptT MsgDoc m () -> m ()
runExceptGhcMonad (ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ())
-> ExceptT MsgDoc (InputT GHCi) () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    Map ModuleName ModInfo
infos <- GHCiState -> Map ModuleName ModInfo
mod_infos (GHCiState -> Map ModuleName ModInfo)
-> ExceptT MsgDoc (InputT GHCi) GHCiState
-> ExceptT MsgDoc (InputT GHCi) (Map ModuleName ModInfo)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ExceptT MsgDoc (InputT GHCi) GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    [ModInfo]
-> (ModInfo -> ExceptT MsgDoc (InputT GHCi) ())
-> ExceptT MsgDoc (InputT GHCi) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (Map ModuleName ModInfo -> [ModInfo]
forall k a. Map k a -> [a]
M.elems Map ModuleName ModInfo
infos) ((ModInfo -> ExceptT MsgDoc (InputT GHCi) ())
 -> ExceptT MsgDoc (InputT GHCi) ())
-> (ModInfo -> ExceptT MsgDoc (InputT GHCi) ())
-> ExceptT MsgDoc (InputT GHCi) ()
forall a b. (a -> b) -> a -> b
$ \mi :: ModInfo
mi ->
        [SpanInfo]
-> (SpanInfo -> ExceptT MsgDoc (InputT GHCi) ())
-> ExceptT MsgDoc (InputT GHCi) ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ (ModInfo -> [SpanInfo]
modinfoSpans ModInfo
mi) (InputT GHCi () -> ExceptT MsgDoc (InputT GHCi) ()
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (InputT GHCi () -> ExceptT MsgDoc (InputT GHCi) ())
-> (SpanInfo -> InputT GHCi ())
-> SpanInfo
-> ExceptT MsgDoc (InputT GHCi) ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SpanInfo -> InputT GHCi ()
forall (m :: * -> *).
(HasDynFlags m, MonadIO m) =>
SpanInfo -> m ()
printSpan)
  where
    printSpan :: SpanInfo -> m ()
printSpan span' :: SpanInfo
span'
      | Just ty :: Type
ty <- SpanInfo -> Maybe Type
spaninfoType SpanInfo
span' = do
        DynFlags
df <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
        let tyInfo :: String
tyInfo = [String] -> String
unwords ([String] -> String) -> (String -> [String]) -> String -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String]
words (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$
                     DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
df PrintUnqualified
alwaysQualify (Type -> MsgDoc
pprTypeForUser Type
ty)
        IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> (String -> IO ()) -> String -> m ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> m ()) -> String -> m ()
forall a b. (a -> b) -> a -> b
$
            RealSrcSpan -> String
showRealSrcSpan (SpanInfo -> RealSrcSpan
spaninfoSrcSpan SpanInfo
span') String -> String -> String
forall a. [a] -> [a] -> [a]
++ ": " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
tyInfo
      | Bool
otherwise = () -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-----------------------------------------------------------------------------
-- Helpers for locAtCmd/typeAtCmd/usesCmd

-- | Parse a span: <module-name/filepath> <sl> <sc> <el> <ec> <string>
parseSpanArg :: String -> Either SDoc (RealSrcSpan,String)
parseSpanArg :: String -> Either MsgDoc (RealSrcSpan, String)
parseSpanArg s :: String
s = do
    (fp :: String
fp,s0 :: String
s0) <- String -> Either MsgDoc (String, String)
readAsString (String -> String
skipWs String
s)
    String
s0'     <- String -> Either MsgDoc String
skipWs1 String
s0
    (sl :: Int
sl,s1 :: String
s1) <- String -> Either MsgDoc (Int, String)
readAsInt String
s0'
    String
s1'     <- String -> Either MsgDoc String
skipWs1 String
s1
    (sc :: Int
sc,s2 :: String
s2) <- String -> Either MsgDoc (Int, String)
readAsInt String
s1'
    String
s2'     <- String -> Either MsgDoc String
skipWs1 String
s2
    (el :: Int
el,s3 :: String
s3) <- String -> Either MsgDoc (Int, String)
readAsInt String
s2'
    String
s3'     <- String -> Either MsgDoc String
skipWs1 String
s3
    (ec :: Int
ec,s4 :: String
s4) <- String -> Either MsgDoc (Int, String)
readAsInt String
s3'

    String
trailer <- case String
s4 of
        [] -> String -> Either MsgDoc String
forall a b. b -> Either a b
Right ""
        _  -> String -> Either MsgDoc String
skipWs1 String
s4

    let fs :: FastString
fs    = String -> FastString
mkFastString String
fp
        span' :: RealSrcSpan
span' = RealSrcLoc -> RealSrcLoc -> RealSrcSpan
mkRealSrcSpan (FastString -> Int -> Int -> RealSrcLoc
mkRealSrcLoc FastString
fs Int
sl Int
sc)
                              (FastString -> Int -> Int -> RealSrcLoc
mkRealSrcLoc FastString
fs Int
el Int
ec)

    (RealSrcSpan, String) -> Either MsgDoc (RealSrcSpan, String)
forall (m :: * -> *) a. Monad m => a -> m a
return (RealSrcSpan
span',String
trailer)
  where
    readAsInt :: String -> Either SDoc (Int,String)
    readAsInt :: String -> Either MsgDoc (Int, String)
readAsInt "" = MsgDoc -> Either MsgDoc (Int, String)
forall a b. a -> Either a b
Left "Premature end of string while expecting Int"
    readAsInt s0 :: String
s0 = case ReadS Int
forall a. Read a => ReadS a
reads String
s0 of
        [s_rest :: (Int, String)
s_rest] -> (Int, String) -> Either MsgDoc (Int, String)
forall a b. b -> Either a b
Right (Int, String)
s_rest
        _        -> MsgDoc -> Either MsgDoc (Int, String)
forall a b. a -> Either a b
Left ("Couldn't read" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text (String -> String
forall a. Show a => a -> String
show String
s0) MsgDoc -> MsgDoc -> MsgDoc
<+> "as Int")

    readAsString :: String -> Either SDoc (String,String)
    readAsString :: String -> Either MsgDoc (String, String)
readAsString s0 :: String
s0
      | '"':_ <- String
s0 = case ReadS String
forall a. Read a => ReadS a
reads String
s0 of
          [s_rest :: (String, String)
s_rest] -> (String, String) -> Either MsgDoc (String, String)
forall a b. b -> Either a b
Right (String, String)
s_rest
          _        -> Either MsgDoc (String, String)
forall b. Either MsgDoc b
leftRes
      | s_rest :: (String, String)
s_rest@(_:_,_) <- String -> (String, String)
breakWs String
s0 = (String, String) -> Either MsgDoc (String, String)
forall a b. b -> Either a b
Right (String, String)
s_rest
      | Bool
otherwise = Either MsgDoc (String, String)
forall b. Either MsgDoc b
leftRes
      where
        leftRes :: Either MsgDoc b
leftRes = MsgDoc -> Either MsgDoc b
forall a b. a -> Either a b
Left ("Couldn't read" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text (String -> String
forall a. Show a => a -> String
show String
s0) MsgDoc -> MsgDoc -> MsgDoc
<+> "as String")

    skipWs1 :: String -> Either SDoc String
    skipWs1 :: String -> Either MsgDoc String
skipWs1 (c :: Char
c:cs :: String
cs) | Char -> Bool
isWs Char
c = String -> Either MsgDoc String
forall a b. b -> Either a b
Right (String -> String
skipWs String
cs)
    skipWs1 s0 :: String
s0 = MsgDoc -> Either MsgDoc String
forall a b. a -> Either a b
Left ("Expected whitespace in" MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text (String -> String
forall a. Show a => a -> String
show String
s0))

    isWs :: Char -> Bool
isWs    = (Char -> String -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [' ','\t'])
    skipWs :: String -> String
skipWs  = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isWs
    breakWs :: String -> (String, String)
breakWs = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isWs


-- | Pretty-print \"real\" 'SrcSpan's as
-- @<filename>:(<line>,<col>)-(<line-end>,<col-end>)@
-- while simply unpacking 'UnhelpfulSpan's
showSrcSpan :: SrcSpan -> String
showSrcSpan :: SrcSpan -> String
showSrcSpan (UnhelpfulSpan s :: FastString
s)  = FastString -> String
unpackFS FastString
s
showSrcSpan (RealSrcSpan spn :: RealSrcSpan
spn)  = RealSrcSpan -> String
showRealSrcSpan RealSrcSpan
spn

-- | Variant of 'showSrcSpan' for 'RealSrcSpan's
showRealSrcSpan :: RealSrcSpan -> String
showRealSrcSpan :: RealSrcSpan -> String
showRealSrcSpan spn :: RealSrcSpan
spn = [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat [ String
fp, ":(", Int -> String
forall a. Show a => a -> String
show Int
sl, ",", Int -> String
forall a. Show a => a -> String
show Int
sc
                             , ")-(", Int -> String
forall a. Show a => a -> String
show Int
el, ",", Int -> String
forall a. Show a => a -> String
show Int
ec, ")"
                             ]
  where
    fp :: String
fp = FastString -> String
unpackFS (RealSrcSpan -> FastString
srcSpanFile RealSrcSpan
spn)
    sl :: Int
sl = RealSrcSpan -> Int
srcSpanStartLine RealSrcSpan
spn
    sc :: Int
sc = RealSrcSpan -> Int
srcSpanStartCol  RealSrcSpan
spn
    el :: Int
el = RealSrcSpan -> Int
srcSpanEndLine   RealSrcSpan
spn
    ec :: Int
ec = RealSrcSpan -> Int
srcSpanEndCol    RealSrcSpan
spn

-----------------------------------------------------------------------------
-- | @:kind@ command

kindOfType :: Bool -> String -> InputT GHCi ()
kindOfType :: Bool -> String -> InputT GHCi ()
kindOfType norm :: Bool
norm str :: String
str = (SourceError -> InputT GHCi ()) -> InputT GHCi () -> InputT GHCi ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    (ty :: Type
ty, kind :: Type
kind) <- Bool -> String -> InputT GHCi (Type, Type)
forall (m :: * -> *).
GhcMonad m =>
Bool -> String -> m (Type, Type)
GHC.typeKind Bool
norm String
str
    MsgDoc -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> InputT GHCi ()) -> MsgDoc -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat [ String -> MsgDoc
text String
str MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
dcolon MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
pprTypeForUser Type
kind
                        , Bool -> MsgDoc -> MsgDoc
ppWhen Bool
norm (MsgDoc -> MsgDoc) -> MsgDoc -> MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc
equals MsgDoc -> MsgDoc -> MsgDoc
<+> Type -> MsgDoc
pprTypeForUser Type
ty ]

-----------------------------------------------------------------------------
-- :quit

quit :: String -> InputT GHCi Bool
quit :: String -> InputT GHCi Bool
quit _ = Bool -> InputT GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True


-----------------------------------------------------------------------------
-- :script

-- running a script file #1363

scriptCmd :: String -> InputT GHCi ()
scriptCmd :: String -> InputT GHCi ()
scriptCmd ws :: String
ws = do
  case String -> [String]
words String
ws of
    [s :: String
s]    -> String -> InputT GHCi ()
runScript String
s
    _      -> GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax:  :script <filename>")

runScript :: String    -- ^ filename
           -> InputT GHCi ()
runScript :: String -> InputT GHCi ()
runScript filename :: String
filename = do
  String
filename' <- String -> InputT GHCi String
forall (m :: * -> *). MonadIO m => String -> InputT m String
expandPath String
filename
  Either IOException Handle
either_script <- IO (Either IOException Handle)
-> InputT GHCi (Either IOException Handle)
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (Either IOException Handle)
 -> InputT GHCi (Either IOException Handle))
-> IO (Either IOException Handle)
-> InputT GHCi (Either IOException Handle)
forall a b. (a -> b) -> a -> b
$ IO Handle -> IO (Either IOException Handle)
forall a. IO a -> IO (Either IOException a)
tryIO (String -> IOMode -> IO Handle
openFile String
filename' IOMode
ReadMode)
  case Either IOException Handle
either_script of
    Left _err :: IOException
_err    -> GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError (String -> GhcException) -> String -> GhcException
forall a b. (a -> b) -> a -> b
$ "IO error:  \""String -> String -> String
forall a. [a] -> [a] -> [a]
++String
filenameString -> String -> String
forall a. [a] -> [a] -> [a]
++"\" "
                      String -> String -> String
forall a. [a] -> [a] -> [a]
++(IOException -> String
ioeGetErrorString IOException
_err))
    Right script :: Handle
script -> do
      GHCiState
st <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      let prog :: String
prog = GHCiState -> String
progname GHCiState
st
          line :: Int
line = GHCiState -> Int
line_number GHCiState
st
      GHCiState -> InputT GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{progname :: String
progname=String
filename',line_number :: Int
line_number=0}
      Handle -> InputT GHCi ()
scriptLoop Handle
script
      IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hClose Handle
script
      GHCiState
new_st <- InputT GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      GHCiState -> InputT GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
new_st{progname :: String
progname=String
prog,line_number :: Int
line_number=Int
line}
  where scriptLoop :: Handle -> InputT GHCi ()
scriptLoop script :: Handle
script = do
          Maybe Bool
res <- (SomeException -> GHCi Bool)
-> InputT GHCi (Maybe String) -> InputT GHCi (Maybe Bool)
runOneCommand SomeException -> GHCi Bool
handler (InputT GHCi (Maybe String) -> InputT GHCi (Maybe Bool))
-> InputT GHCi (Maybe String) -> InputT GHCi (Maybe Bool)
forall a b. (a -> b) -> a -> b
$ Handle -> InputT GHCi (Maybe String)
fileLoop Handle
script
          case Maybe Bool
res of
            Nothing -> () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
            Just s :: Bool
s  -> if Bool
s
              then Handle -> InputT GHCi ()
scriptLoop Handle
script
              else () -> InputT GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

-----------------------------------------------------------------------------
-- :issafe

-- Displaying Safe Haskell properties of a module

isSafeCmd :: String -> InputT GHCi ()
isSafeCmd :: String -> InputT GHCi ()
isSafeCmd m :: String
m =
    case String -> [String]
words String
m of
        [s :: String
s] | String -> Bool
looksLikeModuleName String
s -> do
            Module
md <- GHCi Module -> InputT GHCi Module
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Module -> InputT GHCi Module)
-> GHCi Module -> InputT GHCi Module
forall a b. (a -> b) -> a -> b
$ String -> GHCi Module
forall (m :: * -> *). GhcMonad m => String -> m Module
lookupModule String
s
            Module -> InputT GHCi ()
isSafeModule Module
md
        [] -> do Module
md <- String -> InputT GHCi Module
guessCurrentModule "issafe"
                 Module -> InputT GHCi ()
isSafeModule Module
md
        _ -> GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax:  :issafe <module>")

isSafeModule :: Module -> InputT GHCi ()
isSafeModule :: Module -> InputT GHCi ()
isSafeModule m :: Module
m = do
    Maybe ModuleInfo
mb_mod_info <- Module -> InputT GHCi (Maybe ModuleInfo)
forall (m :: * -> *). GhcMonad m => Module -> m (Maybe ModuleInfo)
GHC.getModuleInfo Module
m
    Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Maybe ModuleInfo -> Bool
forall a. Maybe a -> Bool
isNothing Maybe ModuleInfo
mb_mod_info)
         (GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> InputT GHCi ()) -> GhcException -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GhcException
CmdLineError (String -> GhcException) -> String -> GhcException
forall a b. (a -> b) -> a -> b
$ "unknown module: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
mname)

    DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
    let iface :: Maybe ModIface
iface = ModuleInfo -> Maybe ModIface
GHC.modInfoIface (ModuleInfo -> Maybe ModIface) -> ModuleInfo -> Maybe ModIface
forall a b. (a -> b) -> a -> b
$ Maybe ModuleInfo -> ModuleInfo
forall a. HasCallStack => Maybe a -> a
fromJust Maybe ModuleInfo
mb_mod_info
    Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Maybe ModIface -> Bool
forall a. Maybe a -> Bool
isNothing Maybe ModIface
iface)
         (GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> InputT GHCi ()) -> GhcException -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GhcException
CmdLineError (String -> GhcException) -> String -> GhcException
forall a b. (a -> b) -> a -> b
$ "can't load interface file for module: " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                                    (ModuleName -> String
GHC.moduleNameString (ModuleName -> String) -> ModuleName -> String
forall a b. (a -> b) -> a -> b
$ Module -> ModuleName
GHC.moduleName Module
m))

    (msafe :: Bool
msafe, pkgs :: Set InstalledUnitId
pkgs) <- Module -> InputT GHCi (Bool, Set InstalledUnitId)
forall (m :: * -> *).
GhcMonad m =>
Module -> m (Bool, Set InstalledUnitId)
GHC.moduleTrustReqs Module
m
    let trust :: String
trust  = DynFlags -> SafeHaskellMode -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags (SafeHaskellMode -> String) -> SafeHaskellMode -> String
forall a b. (a -> b) -> a -> b
$ IfaceTrustInfo -> SafeHaskellMode
getSafeMode (IfaceTrustInfo -> SafeHaskellMode)
-> IfaceTrustInfo -> SafeHaskellMode
forall a b. (a -> b) -> a -> b
$ ModIface -> IfaceTrustInfo
GHC.mi_trust (ModIface -> IfaceTrustInfo) -> ModIface -> IfaceTrustInfo
forall a b. (a -> b) -> a -> b
$ Maybe ModIface -> ModIface
forall a. HasCallStack => Maybe a -> a
fromJust Maybe ModIface
iface
        pkg :: String
pkg    = if DynFlags -> Module -> Bool
packageTrusted DynFlags
dflags Module
m then "trusted" else "untrusted"
        (good :: Set InstalledUnitId
good, bad :: Set InstalledUnitId
bad) = DynFlags
-> Set InstalledUnitId
-> (Set InstalledUnitId, Set InstalledUnitId)
tallyPkgs DynFlags
dflags Set InstalledUnitId
pkgs

    -- print info to user...
    IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "Trust type is (Module: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
trust String -> String -> String
forall a. [a] -> [a] -> [a]
++ ", Package: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
pkg String -> String -> String
forall a. [a] -> [a] -> [a]
++ ")"
    IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "Package Trust: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ (if DynFlags -> Bool
packageTrustOn DynFlags
dflags then "On" else "Off")
    Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set InstalledUnitId -> Bool
forall a. Set a -> Bool
S.null Set InstalledUnitId
good)
         (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "Trusted package dependencies (trusted): " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                        (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate ", " ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (InstalledUnitId -> String) -> [InstalledUnitId] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> InstalledUnitId -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) (Set InstalledUnitId -> [InstalledUnitId]
forall a. Set a -> [a]
S.toList Set InstalledUnitId
good)))
    case Bool
msafe Bool -> Bool -> Bool
&& Set InstalledUnitId -> Bool
forall a. Set a -> Bool
S.null Set InstalledUnitId
bad of
        True -> IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
mname String -> String -> String
forall a. [a] -> [a] -> [a]
++ " is trusted!"
        False -> do
            Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ Set InstalledUnitId -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null Set InstalledUnitId
bad)
                 (IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "Trusted package dependencies (untrusted): "
                            String -> String -> String
forall a. [a] -> [a] -> [a]
++ (String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate ", " ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (InstalledUnitId -> String) -> [InstalledUnitId] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> InstalledUnitId -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) (Set InstalledUnitId -> [InstalledUnitId]
forall a. Set a -> [a]
S.toList Set InstalledUnitId
bad)))
            IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
mname String -> String -> String
forall a. [a] -> [a] -> [a]
++ " is NOT trusted!"

  where
    mname :: String
mname = ModuleName -> String
GHC.moduleNameString (ModuleName -> String) -> ModuleName -> String
forall a b. (a -> b) -> a -> b
$ Module -> ModuleName
GHC.moduleName Module
m

    packageTrusted :: DynFlags -> Module -> Bool
packageTrusted dflags :: DynFlags
dflags md :: Module
md
        | DynFlags -> UnitId
thisPackage DynFlags
dflags UnitId -> UnitId -> Bool
forall a. Eq a => a -> a -> Bool
== Module -> UnitId
moduleUnitId Module
md = Bool
True
        | Bool
otherwise = InstalledPackageInfo
  ComponentId
  SourcePackageId
  PackageName
  InstalledUnitId
  UnitId
  ModuleName
  Module
-> Bool
forall compid srcpkgid srcpkgname instunitid unitid modulename mod.
InstalledPackageInfo
  compid srcpkgid srcpkgname instunitid unitid modulename mod
-> Bool
trusted (InstalledPackageInfo
   ComponentId
   SourcePackageId
   PackageName
   InstalledUnitId
   UnitId
   ModuleName
   Module
 -> Bool)
-> InstalledPackageInfo
     ComponentId
     SourcePackageId
     PackageName
     InstalledUnitId
     UnitId
     ModuleName
     Module
-> Bool
forall a b. (a -> b) -> a -> b
$ DynFlags
-> UnitId
-> InstalledPackageInfo
     ComponentId
     SourcePackageId
     PackageName
     InstalledUnitId
     UnitId
     ModuleName
     Module
getPackageDetails DynFlags
dflags (Module -> UnitId
moduleUnitId Module
md)

    tallyPkgs :: DynFlags
-> Set InstalledUnitId
-> (Set InstalledUnitId, Set InstalledUnitId)
tallyPkgs dflags :: DynFlags
dflags deps :: Set InstalledUnitId
deps | Bool -> Bool
not (DynFlags -> Bool
packageTrustOn DynFlags
dflags) = (Set InstalledUnitId
forall a. Set a
S.empty, Set InstalledUnitId
forall a. Set a
S.empty)
                          | Bool
otherwise = (InstalledUnitId -> Bool)
-> Set InstalledUnitId
-> (Set InstalledUnitId, Set InstalledUnitId)
forall a. (a -> Bool) -> Set a -> (Set a, Set a)
S.partition InstalledUnitId -> Bool
part Set InstalledUnitId
deps
        where part :: InstalledUnitId -> Bool
part pkg :: InstalledUnitId
pkg = InstalledPackageInfo
  ComponentId
  SourcePackageId
  PackageName
  InstalledUnitId
  UnitId
  ModuleName
  Module
-> Bool
forall compid srcpkgid srcpkgname instunitid unitid modulename mod.
InstalledPackageInfo
  compid srcpkgid srcpkgname instunitid unitid modulename mod
-> Bool
trusted (InstalledPackageInfo
   ComponentId
   SourcePackageId
   PackageName
   InstalledUnitId
   UnitId
   ModuleName
   Module
 -> Bool)
-> InstalledPackageInfo
     ComponentId
     SourcePackageId
     PackageName
     InstalledUnitId
     UnitId
     ModuleName
     Module
-> Bool
forall a b. (a -> b) -> a -> b
$ DynFlags
-> InstalledUnitId
-> InstalledPackageInfo
     ComponentId
     SourcePackageId
     PackageName
     InstalledUnitId
     UnitId
     ModuleName
     Module
getInstalledPackageDetails DynFlags
dflags InstalledUnitId
pkg

-----------------------------------------------------------------------------
-- :browse

-- Browsing a module's contents

browseCmd :: Bool -> String -> InputT GHCi ()
browseCmd :: Bool -> String -> InputT GHCi ()
browseCmd bang :: Bool
bang m :: String
m =
  case String -> [String]
words String
m of
    ['*':s :: String
s] | String -> Bool
looksLikeModuleName String
s -> do
        Module
md <- GHCi Module -> InputT GHCi Module
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Module -> InputT GHCi Module)
-> GHCi Module -> InputT GHCi Module
forall a b. (a -> b) -> a -> b
$ String -> GHCi Module
forall (m :: * -> *). GhcMonad m => String -> m Module
wantInterpretedModule String
s
        Bool -> Module -> Bool -> InputT GHCi ()
browseModule Bool
bang Module
md Bool
False
    [s :: String
s] | String -> Bool
looksLikeModuleName String
s -> do
        Module
md <- GHCi Module -> InputT GHCi Module
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Module -> InputT GHCi Module)
-> GHCi Module -> InputT GHCi Module
forall a b. (a -> b) -> a -> b
$ String -> GHCi Module
forall (m :: * -> *). GhcMonad m => String -> m Module
lookupModule String
s
        Bool -> Module -> Bool -> InputT GHCi ()
browseModule Bool
bang Module
md Bool
True
    [] -> do Module
md <- String -> InputT GHCi Module
guessCurrentModule ("browse" String -> String -> String
forall a. [a] -> [a] -> [a]
++ if Bool
bang then "!" else "")
             Bool -> Module -> Bool -> InputT GHCi ()
browseModule Bool
bang Module
md Bool
True
    _ -> GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax:  :browse <module>")

guessCurrentModule :: String -> InputT GHCi Module
-- Guess which module the user wants to browse.  Pick
-- modules that are interpreted first.  The most
-- recently-added module occurs last, it seems.
guessCurrentModule :: String -> InputT GHCi Module
guessCurrentModule cmd :: String
cmd
  = do [InteractiveImport]
imports <- InputT GHCi [InteractiveImport]
forall (m :: * -> *). GhcMonad m => m [InteractiveImport]
GHC.getContext
       Bool -> InputT GHCi () -> InputT GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ([InteractiveImport] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [InteractiveImport]
imports) (InputT GHCi () -> InputT GHCi ())
-> InputT GHCi () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> InputT GHCi ()) -> GhcException -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$
          String -> GhcException
CmdLineError (':' Char -> String -> String
forall a. a -> [a] -> [a]
: String
cmd String -> String -> String
forall a. [a] -> [a] -> [a]
++ ": no current module")
       case ([InteractiveImport] -> InteractiveImport
forall a. [a] -> a
head [InteractiveImport]
imports) of
          IIModule m :: ModuleName
m -> ModuleName -> Maybe FastString -> InputT GHCi Module
forall (m :: * -> *).
GhcMonad m =>
ModuleName -> Maybe FastString -> m Module
GHC.findModule ModuleName
m Maybe FastString
forall a. Maybe a
Nothing
          IIDecl d :: ImportDecl GhcPs
d   -> ModuleName -> Maybe FastString -> InputT GHCi Module
forall (m :: * -> *).
GhcMonad m =>
ModuleName -> Maybe FastString -> m Module
GHC.findModule (Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d))
                                       ((StringLiteral -> FastString)
-> Maybe StringLiteral -> Maybe FastString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap StringLiteral -> FastString
sl_fs (Maybe StringLiteral -> Maybe FastString)
-> Maybe StringLiteral -> Maybe FastString
forall a b. (a -> b) -> a -> b
$ ImportDecl GhcPs -> Maybe StringLiteral
forall pass. ImportDecl pass -> Maybe StringLiteral
ideclPkgQual ImportDecl GhcPs
d)

-- without bang, show items in context of their parents and omit children
-- with bang, show class methods and data constructors separately, and
--            indicate import modules, to aid qualifying unqualified names
-- with sorted, sort items alphabetically
browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
browseModule bang :: Bool
bang modl :: Module
modl exports_only :: Bool
exports_only = do
  -- :browse reports qualifiers wrt current context
  PrintUnqualified
unqual <- InputT GHCi PrintUnqualified
forall (m :: * -> *). GhcMonad m => m PrintUnqualified
GHC.getPrintUnqual

  Maybe ModuleInfo
mb_mod_info <- Module -> InputT GHCi (Maybe ModuleInfo)
forall (m :: * -> *). GhcMonad m => Module -> m (Maybe ModuleInfo)
GHC.getModuleInfo Module
modl
  case Maybe ModuleInfo
mb_mod_info of
    Nothing -> GhcException -> InputT GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError ("unknown module: " String -> String -> String
forall a. [a] -> [a] -> [a]
++
                                ModuleName -> String
GHC.moduleNameString (Module -> ModuleName
GHC.moduleName Module
modl)))
    Just mod_info :: ModuleInfo
mod_info -> do
        DynFlags
dflags <- InputT GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
        let names :: [Name]
names
               | Bool
exports_only = ModuleInfo -> [Name]
GHC.modInfoExports ModuleInfo
mod_info
               | Bool
otherwise    = ModuleInfo -> Maybe [Name]
GHC.modInfoTopLevelScope ModuleInfo
mod_info
                                Maybe [Name] -> [Name] -> [Name]
forall a. Maybe a -> a -> a
`orElse` []

                -- sort alphabetically name, but putting locally-defined
                -- identifiers first. We would like to improve this; see #1799.
            sorted_names :: [Name]
sorted_names = [Name] -> [Name]
loc_sort [Name]
local [Name] -> [Name] -> [Name]
forall a. [a] -> [a] -> [a]
++ [Name] -> [Name]
occ_sort [Name]
external
                where
                (local :: [Name]
local,external :: [Name]
external) = ASSERT( all isExternalName names )
                                   (Name -> Bool) -> [Name] -> ([Name], [Name])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ((Module -> Module -> Bool
forall a. Eq a => a -> a -> Bool
==Module
modl) (Module -> Bool) -> (Name -> Module) -> Name -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. HasDebugCallStack => Name -> Module
Name -> Module
nameModule) [Name]
names
                occ_sort :: [Name] -> [Name]
occ_sort = (Name -> Name -> Ordering) -> [Name] -> [Name]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (OccName -> OccName -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (OccName -> OccName -> Ordering)
-> (Name -> OccName) -> Name -> Name -> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` Name -> OccName
nameOccName)
                -- try to sort by src location. If the first name in our list
                -- has a good source location, then they all should.
                loc_sort :: [Name] -> [Name]
loc_sort ns :: [Name]
ns
                      | n :: Name
n:_ <- [Name]
ns, SrcSpan -> Bool
isGoodSrcSpan (Name -> SrcSpan
nameSrcSpan Name
n)
                      = (Name -> Name -> Ordering) -> [Name] -> [Name]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (SrcSpan -> SrcSpan -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (SrcSpan -> SrcSpan -> Ordering)
-> (Name -> SrcSpan) -> Name -> Name -> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` Name -> SrcSpan
nameSrcSpan) [Name]
ns
                      | Bool
otherwise
                      = [Name] -> [Name]
occ_sort [Name]
ns

        [Maybe TyThing]
mb_things <- (Name -> InputT GHCi (Maybe TyThing))
-> [Name] -> InputT GHCi [Maybe TyThing]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM Name -> InputT GHCi (Maybe TyThing)
forall (m :: * -> *). GhcMonad m => Name -> m (Maybe TyThing)
GHC.lookupName [Name]
sorted_names
        let filtered_things :: [TyThing]
filtered_things = (TyThing -> TyThing) -> [TyThing] -> [TyThing]
forall a. (a -> TyThing) -> [a] -> [a]
filterOutChildren (\t :: TyThing
t -> TyThing
t) ([Maybe TyThing] -> [TyThing]
forall a. [Maybe a] -> [a]
catMaybes [Maybe TyThing]
mb_things)

        GlobalRdrEnv
rdr_env <- InputT GHCi GlobalRdrEnv
forall (m :: * -> *). GhcMonad m => m GlobalRdrEnv
GHC.getGRE

        let things :: [TyThing]
things | Bool
bang      = [Maybe TyThing] -> [TyThing]
forall a. [Maybe a] -> [a]
catMaybes [Maybe TyThing]
mb_things
                   | Bool
otherwise = [TyThing]
filtered_things
            pretty :: TyThing -> MsgDoc
pretty | Bool
bang      = ShowSub -> TyThing -> MsgDoc
pprTyThing ShowSub
showToHeader
                   | Bool
otherwise = ShowSub -> TyThing -> MsgDoc
pprTyThingInContext ShowSub
showToHeader

            labels :: [Maybe [ModuleName]] -> MsgDoc
labels  [] = String -> MsgDoc
text "-- not currently imported"
            labels  l :: [Maybe [ModuleName]]
l  = String -> MsgDoc
text (String -> MsgDoc) -> String -> MsgDoc
forall a b. (a -> b) -> a -> b
$ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate "\n" ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (Maybe [ModuleName] -> String) -> [Maybe [ModuleName]] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Maybe [ModuleName] -> String
qualifier [Maybe [ModuleName]]
l

            qualifier :: Maybe [ModuleName] -> String
            qualifier :: Maybe [ModuleName] -> String
qualifier  = String -> ([ModuleName] -> String) -> Maybe [ModuleName] -> String
forall b a. b -> (a -> b) -> Maybe a -> b
maybe "-- defined locally"
                             (("-- imported via "String -> String -> String
forall a. [a] -> [a] -> [a]
++) (String -> String)
-> ([ModuleName] -> String) -> [ModuleName] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate ", "
                               ([String] -> String)
-> ([ModuleName] -> [String]) -> [ModuleName] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (ModuleName -> String) -> [ModuleName] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> String
GHC.moduleNameString)
            importInfo :: Name -> [Maybe [ModuleName]]
importInfo = GlobalRdrEnv -> Name -> [Maybe [ModuleName]]
RdrName.getGRE_NameQualifier_maybes GlobalRdrEnv
rdr_env

            modNames :: [[Maybe [ModuleName]]]
            modNames :: [[Maybe [ModuleName]]]
modNames   = (TyThing -> [Maybe [ModuleName]])
-> [TyThing] -> [[Maybe [ModuleName]]]
forall a b. (a -> b) -> [a] -> [b]
map (Name -> [Maybe [ModuleName]]
importInfo (Name -> [Maybe [ModuleName]])
-> (TyThing -> Name) -> TyThing -> [Maybe [ModuleName]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyThing -> Name
forall a. NamedThing a => a -> Name
GHC.getName) [TyThing]
things

            -- annotate groups of imports with their import modules
            -- the default ordering is somewhat arbitrary, so we group
            -- by header and sort groups; the names themselves should
            -- really come in order of source appearance.. (trac #1799)
            annotate :: [([Maybe [ModuleName]], MsgDoc)] -> [MsgDoc]
annotate mts :: [([Maybe [ModuleName]], MsgDoc)]
mts = (([Maybe [ModuleName]], [MsgDoc]) -> [MsgDoc])
-> [([Maybe [ModuleName]], [MsgDoc])] -> [MsgDoc]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (\(m :: [Maybe [ModuleName]]
m,ts :: [MsgDoc]
ts)->[Maybe [ModuleName]] -> MsgDoc
labels [Maybe [ModuleName]]
mMsgDoc -> [MsgDoc] -> [MsgDoc]
forall a. a -> [a] -> [a]
:[MsgDoc]
ts)
                         ([([Maybe [ModuleName]], [MsgDoc])] -> [MsgDoc])
-> [([Maybe [ModuleName]], [MsgDoc])] -> [MsgDoc]
forall a b. (a -> b) -> a -> b
$ (([Maybe [ModuleName]], [MsgDoc])
 -> ([Maybe [ModuleName]], [MsgDoc]) -> Ordering)
-> [([Maybe [ModuleName]], [MsgDoc])]
-> [([Maybe [ModuleName]], [MsgDoc])]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ([Maybe [ModuleName]], [MsgDoc])
-> ([Maybe [ModuleName]], [MsgDoc]) -> Ordering
forall b.
([Maybe [ModuleName]], b) -> ([Maybe [ModuleName]], b) -> Ordering
cmpQualifiers ([([Maybe [ModuleName]], [MsgDoc])]
 -> [([Maybe [ModuleName]], [MsgDoc])])
-> [([Maybe [ModuleName]], [MsgDoc])]
-> [([Maybe [ModuleName]], [MsgDoc])]
forall a b. (a -> b) -> a -> b
$ [([Maybe [ModuleName]], MsgDoc)]
-> [([Maybe [ModuleName]], [MsgDoc])]
forall a b. Eq a => [(a, b)] -> [(a, [b])]
grp [([Maybe [ModuleName]], MsgDoc)]
mts
              where cmpQualifiers :: ([Maybe [ModuleName]], b) -> ([Maybe [ModuleName]], b) -> Ordering
cmpQualifiers =
                      [Maybe [FastString]] -> [Maybe [FastString]] -> Ordering
forall a. Ord a => a -> a -> Ordering
compare ([Maybe [FastString]] -> [Maybe [FastString]] -> Ordering)
-> (([Maybe [ModuleName]], b) -> [Maybe [FastString]])
-> ([Maybe [ModuleName]], b)
-> ([Maybe [ModuleName]], b)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` ((Maybe [ModuleName] -> Maybe [FastString])
-> [Maybe [ModuleName]] -> [Maybe [FastString]]
forall a b. (a -> b) -> [a] -> [b]
map (([ModuleName] -> [FastString])
-> Maybe [ModuleName] -> Maybe [FastString]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((ModuleName -> FastString) -> [ModuleName] -> [FastString]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> FastString
moduleNameFS)) ([Maybe [ModuleName]] -> [Maybe [FastString]])
-> (([Maybe [ModuleName]], b) -> [Maybe [ModuleName]])
-> ([Maybe [ModuleName]], b)
-> [Maybe [FastString]]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Maybe [ModuleName]], b) -> [Maybe [ModuleName]]
forall a b. (a, b) -> a
fst)
            grp :: [(a, b)] -> [(a, [b])]
grp []            = []
            grp mts :: [(a, b)]
mts@((m :: a
m,_):_) = (a
m,((a, b) -> b) -> [(a, b)] -> [b]
forall a b. (a -> b) -> [a] -> [b]
map (a, b) -> b
forall a b. (a, b) -> b
snd [(a, b)]
g) (a, [b]) -> [(a, [b])] -> [(a, [b])]
forall a. a -> [a] -> [a]
: [(a, b)] -> [(a, [b])]
grp [(a, b)]
ng
              where (g :: [(a, b)]
g,ng :: [(a, b)]
ng) = ((a, b) -> Bool) -> [(a, b)] -> ([(a, b)], [(a, b)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition ((a -> a -> Bool
forall a. Eq a => a -> a -> Bool
==a
m)(a -> Bool) -> ((a, b) -> a) -> (a, b) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(a, b) -> a
forall a b. (a, b) -> a
fst) [(a, b)]
mts

        let prettyThings, prettyThings' :: [SDoc]
            prettyThings :: [MsgDoc]
prettyThings = (TyThing -> MsgDoc) -> [TyThing] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map TyThing -> MsgDoc
pretty [TyThing]
things
            prettyThings' :: [MsgDoc]
prettyThings' | Bool
bang      = [([Maybe [ModuleName]], MsgDoc)] -> [MsgDoc]
annotate ([([Maybe [ModuleName]], MsgDoc)] -> [MsgDoc])
-> [([Maybe [ModuleName]], MsgDoc)] -> [MsgDoc]
forall a b. (a -> b) -> a -> b
$ [[Maybe [ModuleName]]]
-> [MsgDoc] -> [([Maybe [ModuleName]], MsgDoc)]
forall a b. [a] -> [b] -> [(a, b)]
zip [[Maybe [ModuleName]]]
modNames [MsgDoc]
prettyThings
                          | Bool
otherwise = [MsgDoc]
prettyThings
        IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> PrintUnqualified -> MsgDoc -> String
showSDocForUser DynFlags
dflags PrintUnqualified
unqual ([MsgDoc] -> MsgDoc
vcat [MsgDoc]
prettyThings')
        -- ToDo: modInfoInstances currently throws an exception for
        -- package modules.  When it works, we can do this:
        --        $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))


-----------------------------------------------------------------------------
-- :module

-- Setting the module context.  For details on context handling see
-- "remembered_ctx" and "transient_ctx" in GhciMonad.

moduleCmd :: String -> GHCi ()
moduleCmd :: String -> GHCi ()
moduleCmd str :: String
str
  | (String -> Bool) -> [String] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all String -> Bool
sensible [String]
strs = GHCi ()
cmd
  | Bool
otherwise = GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "syntax:  :module [+/-] [*]M1 ... [*]Mn")
  where
    (cmd :: GHCi ()
cmd, strs :: [String]
strs) =
        case String
str of
          '+':stuff :: String
stuff -> ([ModuleName] -> [ModuleName] -> GHCi ())
-> String -> (GHCi (), [String])
forall a.
([ModuleName] -> [ModuleName] -> a) -> String -> (a, [String])
rest [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext   String
stuff
          '-':stuff :: String
stuff -> ([ModuleName] -> [ModuleName] -> GHCi ())
-> String -> (GHCi (), [String])
forall a.
([ModuleName] -> [ModuleName] -> a) -> String -> (a, [String])
rest [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext String
stuff
          stuff :: String
stuff     -> ([ModuleName] -> [ModuleName] -> GHCi ())
-> String -> (GHCi (), [String])
forall a.
([ModuleName] -> [ModuleName] -> a) -> String -> (a, [String])
rest [ModuleName] -> [ModuleName] -> GHCi ()
setContext            String
stuff

    rest :: ([ModuleName] -> [ModuleName] -> a) -> String -> (a, [String])
rest op :: [ModuleName] -> [ModuleName] -> a
op stuff :: String
stuff = ([ModuleName] -> [ModuleName] -> a
op [ModuleName]
as [ModuleName]
bs, [String]
stuffs)
       where (as :: [ModuleName]
as,bs :: [ModuleName]
bs) = (String -> Either ModuleName ModuleName)
-> [String] -> ([ModuleName], [ModuleName])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith String -> Either ModuleName ModuleName
starred [String]
stuffs
             stuffs :: [String]
stuffs  = String -> [String]
words String
stuff

    sensible :: String -> Bool
sensible ('*':m :: String
m) = String -> Bool
looksLikeModuleName String
m
    sensible m :: String
m       = String -> Bool
looksLikeModuleName String
m

    starred :: String -> Either ModuleName ModuleName
starred ('*':m :: String
m) = ModuleName -> Either ModuleName ModuleName
forall a b. a -> Either a b
Left  (String -> ModuleName
GHC.mkModuleName String
m)
    starred m :: String
m       = ModuleName -> Either ModuleName ModuleName
forall a b. b -> Either a b
Right (String -> ModuleName
GHC.mkModuleName String
m)


-- -----------------------------------------------------------------------------
-- Four ways to manipulate the context:
--   (a) :module +<stuff>:     addModulesToContext
--   (b) :module -<stuff>:     remModulesFromContext
--   (c) :module <stuff>:      setContext
--   (d) import <module>...:   addImportToContext

addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext starred :: [ModuleName]
starred unstarred :: [ModuleName]
unstarred = GHCi () -> GHCi ()
forall a. GHCi a -> GHCi a
restoreContextOnFailure (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
   [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ [ModuleName]
starred [ModuleName]
unstarred

addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ starred :: [ModuleName]
starred unstarred :: [ModuleName]
unstarred = do
   (InteractiveImport -> GHCi ()) -> [InteractiveImport] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ InteractiveImport -> GHCi ()
addII ((ModuleName -> InteractiveImport)
-> [ModuleName] -> [InteractiveImport]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> InteractiveImport
mkIIModule [ModuleName]
starred [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a] -> [a]
++ (ModuleName -> InteractiveImport)
-> [ModuleName] -> [InteractiveImport]
forall a b. (a -> b) -> [a] -> [b]
map ModuleName -> InteractiveImport
mkIIDecl [ModuleName]
unstarred)
   GHCi ()
setGHCContextFromGHCiState

remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
remModulesFromContext  starred :: [ModuleName]
starred unstarred :: [ModuleName]
unstarred = do
   -- we do *not* call restoreContextOnFailure here.  If the user
   -- is trying to fix up a context that contains errors by removing
   -- modules, we don't want GHC to silently put them back in again.
   (ModuleName -> GHCi ()) -> [ModuleName] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ModuleName -> GHCi ()
rm ([ModuleName]
starred [ModuleName] -> [ModuleName] -> [ModuleName]
forall a. [a] -> [a] -> [a]
++ [ModuleName]
unstarred)
   GHCi ()
setGHCContextFromGHCiState
 where
   rm :: ModuleName -> GHCi ()
   rm :: ModuleName -> GHCi ()
rm str :: ModuleName
str = do
     ModuleName
m <- Module -> ModuleName
moduleName (Module -> ModuleName) -> GHCi Module -> GHCi ModuleName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ModuleName -> GHCi Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
lookupModuleName ModuleName
str
     let filt :: [InteractiveImport] -> [InteractiveImport]
filt = (InteractiveImport -> Bool)
-> [InteractiveImport] -> [InteractiveImport]
forall a. (a -> Bool) -> [a] -> [a]
filter (ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
(/=) ModuleName
m (ModuleName -> Bool)
-> (InteractiveImport -> ModuleName) -> InteractiveImport -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InteractiveImport -> ModuleName
iiModuleName)
     (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st :: GHCiState
st ->
        GHCiState
st { remembered_ctx :: [InteractiveImport]
remembered_ctx = [InteractiveImport] -> [InteractiveImport]
filt (GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st)
           , transient_ctx :: [InteractiveImport]
transient_ctx  = [InteractiveImport] -> [InteractiveImport]
filt (GHCiState -> [InteractiveImport]
transient_ctx GHCiState
st) }

setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
setContext starred :: [ModuleName]
starred unstarred :: [ModuleName]
unstarred = GHCi () -> GHCi ()
forall a. GHCi a -> GHCi a
restoreContextOnFailure (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
  (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st :: GHCiState
st -> GHCiState
st { remembered_ctx :: [InteractiveImport]
remembered_ctx = [], transient_ctx :: [InteractiveImport]
transient_ctx = [] }
                                -- delete the transient context
  [ModuleName] -> [ModuleName] -> GHCi ()
addModulesToContext_ [ModuleName]
starred [ModuleName]
unstarred

addImportToContext :: String -> GHCi ()
addImportToContext :: String -> GHCi ()
addImportToContext str :: String
str = GHCi () -> GHCi ()
forall a. GHCi a -> GHCi a
restoreContextOnFailure (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
  ImportDecl GhcPs
idecl <- String -> GHCi (ImportDecl GhcPs)
forall (m :: * -> *). GhcMonad m => String -> m (ImportDecl GhcPs)
GHC.parseImportDecl String
str
  InteractiveImport -> GHCi ()
addII (ImportDecl GhcPs -> InteractiveImport
IIDecl ImportDecl GhcPs
idecl)   -- #5836
  GHCi ()
setGHCContextFromGHCiState

-- Util used by addImportToContext and addModulesToContext
addII :: InteractiveImport -> GHCi ()
addII :: InteractiveImport -> GHCi ()
addII iidecl :: InteractiveImport
iidecl = do
  InteractiveImport -> GHCi ()
checkAdd InteractiveImport
iidecl
  (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st :: GHCiState
st ->
     GHCiState
st { remembered_ctx :: [InteractiveImport]
remembered_ctx = InteractiveImport -> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed InteractiveImport
iidecl (GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st)
        , transient_ctx :: [InteractiveImport]
transient_ctx = (InteractiveImport -> Bool)
-> [InteractiveImport] -> [InteractiveImport]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> (InteractiveImport -> Bool) -> InteractiveImport -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InteractiveImport
iidecl InteractiveImport -> InteractiveImport -> Bool
`iiSubsumes`))
                                 (GHCiState -> [InteractiveImport]
transient_ctx GHCiState
st)
        }

-- Sometimes we can't tell whether an import is valid or not until
-- we finally call 'GHC.setContext'.  e.g.
--
--   import System.IO (foo)
--
-- will fail because System.IO does not export foo.  In this case we
-- don't want to store the import in the context permanently, so we
-- catch the failure from 'setGHCContextFromGHCiState' and set the
-- context back to what it was.
--
-- See #6007
--
restoreContextOnFailure :: GHCi a -> GHCi a
restoreContextOnFailure :: GHCi a -> GHCi a
restoreContextOnFailure do_this :: GHCi a
do_this = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  let rc :: [InteractiveImport]
rc = GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st; tc :: [InteractiveImport]
tc = GHCiState -> [InteractiveImport]
transient_ctx GHCiState
st
  GHCi a
do_this GHCi a -> GHCi () -> GHCi a
forall (m :: * -> *) a b. ExceptionMonad m => m a -> m b -> m a
`gonException` ((GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState ((GHCiState -> GHCiState) -> GHCi ())
-> (GHCiState -> GHCiState) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \st' :: GHCiState
st' ->
     GHCiState
st' { remembered_ctx :: [InteractiveImport]
remembered_ctx = [InteractiveImport]
rc, transient_ctx :: [InteractiveImport]
transient_ctx = [InteractiveImport]
tc })

-- -----------------------------------------------------------------------------
-- Validate a module that we want to add to the context

checkAdd :: InteractiveImport -> GHCi ()
checkAdd :: InteractiveImport -> GHCi ()
checkAdd ii :: InteractiveImport
ii = do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let safe :: Bool
safe = DynFlags -> Bool
safeLanguageOn DynFlags
dflags
  case InteractiveImport
ii of
    IIModule modname :: ModuleName
modname
       | Bool
safe -> GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> GHCi ()) -> GhcException -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GhcException
CmdLineError "can't use * imports with Safe Haskell"
       | Bool
otherwise -> ModuleName -> GHCi Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName ModuleName
modname GHCi Module -> GHCi () -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

    IIDecl d :: ImportDecl GhcPs
d -> do
       let modname :: SrcSpanLess (Located ModuleName)
modname = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d)
           pkgqual :: Maybe StringLiteral
pkgqual = ImportDecl GhcPs -> Maybe StringLiteral
forall pass. ImportDecl pass -> Maybe StringLiteral
ideclPkgQual ImportDecl GhcPs
d
       Module
m <- ModuleName -> Maybe FastString -> GHCi Module
forall (m :: * -> *).
GhcMonad m =>
ModuleName -> Maybe FastString -> m Module
GHC.lookupModule ModuleName
modname ((StringLiteral -> FastString)
-> Maybe StringLiteral -> Maybe FastString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap StringLiteral -> FastString
sl_fs Maybe StringLiteral
pkgqual)
       Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when Bool
safe (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
           Bool
t <- Module -> GHCi Bool
forall (m :: * -> *). GhcMonad m => Module -> m Bool
GHC.isModuleTrusted Module
m
           Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
t) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> GHCi ()) -> GhcException -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GhcException
ProgramError (String -> GhcException) -> String -> GhcException
forall a b. (a -> b) -> a -> b
$ ""

-- -----------------------------------------------------------------------------
-- Update the GHC API's view of the context

-- | Sets the GHC context from the GHCi state.  The GHC context is
-- always set this way, we never modify it incrementally.
--
-- We ignore any imports for which the ModuleName does not currently
-- exist.  This is so that the remembered_ctx can contain imports for
-- modules that are not currently loaded, perhaps because we just did
-- a :reload and encountered errors.
--
-- Prelude is added if not already present in the list.  Therefore to
-- override the implicit Prelude import you can say 'import Prelude ()'
-- at the prompt, just as in Haskell source.
--
setGHCContextFromGHCiState :: GHCi ()
setGHCContextFromGHCiState :: GHCi ()
setGHCContextFromGHCiState = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      -- re-use checkAdd to check whether the module is valid.  If the
      -- module does not exist, we do *not* want to print an error
      -- here, we just want to silently keep the module in the context
      -- until such time as the module reappears again.  So we ignore
      -- the actual exception thrown by checkAdd, using tryBool to
      -- turn it into a Bool.
  [InteractiveImport]
iidecls <- (InteractiveImport -> GHCi Bool)
-> [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (GHCi () -> GHCi Bool
forall a. GHCi a -> GHCi Bool
tryBool(GHCi () -> GHCi Bool)
-> (InteractiveImport -> GHCi ()) -> InteractiveImport -> GHCi Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.InteractiveImport -> GHCi ()
checkAdd) (GHCiState -> [InteractiveImport]
transient_ctx GHCiState
st [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a] -> [a]
++ GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st)

  [InteractiveImport]
prel_iidecls <- [InteractiveImport] -> GHCi [InteractiveImport]
getImplicitPreludeImports [InteractiveImport]
iidecls
  [InteractiveImport]
valid_prel_iidecls <- (InteractiveImport -> GHCi Bool)
-> [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (GHCi () -> GHCi Bool
forall a. GHCi a -> GHCi Bool
tryBool (GHCi () -> GHCi Bool)
-> (InteractiveImport -> GHCi ()) -> InteractiveImport -> GHCi Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InteractiveImport -> GHCi ()
checkAdd) [InteractiveImport]
prel_iidecls

  [InteractiveImport]
extra_imports <- (InteractiveImport -> GHCi Bool)
-> [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (GHCi () -> GHCi Bool
forall a. GHCi a -> GHCi Bool
tryBool (GHCi () -> GHCi Bool)
-> (InteractiveImport -> GHCi ()) -> InteractiveImport -> GHCi Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InteractiveImport -> GHCi ()
checkAdd) ((ImportDecl GhcPs -> InteractiveImport)
-> [ImportDecl GhcPs] -> [InteractiveImport]
forall a b. (a -> b) -> [a] -> [b]
map ImportDecl GhcPs -> InteractiveImport
IIDecl (GHCiState -> [ImportDecl GhcPs]
extra_imports GHCiState
st))

  [InteractiveImport] -> GHCi ()
forall (m :: * -> *). GhcMonad m => [InteractiveImport] -> m ()
GHC.setContext ([InteractiveImport] -> GHCi ()) -> [InteractiveImport] -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [InteractiveImport]
iidecls [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a] -> [a]
++ [InteractiveImport]
extra_imports [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a] -> [a]
++ [InteractiveImport]
valid_prel_iidecls


getImplicitPreludeImports :: [InteractiveImport] -> GHCi [InteractiveImport]
getImplicitPreludeImports :: [InteractiveImport] -> GHCi [InteractiveImport]
getImplicitPreludeImports iidecls :: [InteractiveImport]
iidecls = do
     -- allow :seti to override -XNoImplicitPrelude
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState

  -- We add the prelude imports if there are no *-imports, and we also
  -- allow each prelude import to be subsumed by another explicit import
  -- of the same module.  This means that you can override the prelude import
  -- with "import Prelude hiding (map)", for example.
  let prel_iidecls :: [InteractiveImport]
prel_iidecls =
        if Bool -> Bool
not ((InteractiveImport -> Bool) -> [InteractiveImport] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any InteractiveImport -> Bool
isIIModule [InteractiveImport]
iidecls)
            then [ ImportDecl GhcPs -> InteractiveImport
IIDecl ImportDecl GhcPs
imp
                 | ImportDecl GhcPs
imp <- GHCiState -> [ImportDecl GhcPs]
prelude_imports GHCiState
st
                 , Bool -> Bool
not ((InteractiveImport -> Bool) -> [InteractiveImport] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (ImportDecl GhcPs -> InteractiveImport -> Bool
sameImpModule ImportDecl GhcPs
imp) [InteractiveImport]
iidecls) ]
            else []

  [InteractiveImport] -> GHCi [InteractiveImport]
forall (m :: * -> *) a. Monad m => a -> m a
return [InteractiveImport]
prel_iidecls

-- -----------------------------------------------------------------------------
-- Utils on InteractiveImport

mkIIModule :: ModuleName -> InteractiveImport
mkIIModule :: ModuleName -> InteractiveImport
mkIIModule = ModuleName -> InteractiveImport
IIModule

mkIIDecl :: ModuleName -> InteractiveImport
mkIIDecl :: ModuleName -> InteractiveImport
mkIIDecl = ImportDecl GhcPs -> InteractiveImport
IIDecl (ImportDecl GhcPs -> InteractiveImport)
-> (ModuleName -> ImportDecl GhcPs)
-> ModuleName
-> InteractiveImport
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ModuleName -> ImportDecl GhcPs
forall (p :: Pass). ModuleName -> ImportDecl (GhcPass p)
simpleImportDecl

iiModules :: [InteractiveImport] -> [ModuleName]
iiModules :: [InteractiveImport] -> [ModuleName]
iiModules is :: [InteractiveImport]
is = [ModuleName
m | IIModule m :: ModuleName
m <- [InteractiveImport]
is]

isIIModule :: InteractiveImport -> Bool
isIIModule :: InteractiveImport -> Bool
isIIModule (IIModule _) = Bool
True
isIIModule _ = Bool
False

iiModuleName :: InteractiveImport -> ModuleName
iiModuleName :: InteractiveImport -> ModuleName
iiModuleName (IIModule m :: ModuleName
m) = ModuleName
m
iiModuleName (IIDecl d :: ImportDecl GhcPs
d)   = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d)

preludeModuleName :: ModuleName
preludeModuleName :: ModuleName
preludeModuleName = String -> ModuleName
GHC.mkModuleName "Clash.Prelude"

sameImpModule :: ImportDecl GhcPs -> InteractiveImport -> Bool
sameImpModule :: ImportDecl GhcPs -> InteractiveImport -> Bool
sameImpModule _ (IIModule _) = Bool
False -- we only care about imports here
sameImpModule imp :: ImportDecl GhcPs
imp (IIDecl d :: ImportDecl GhcPs
d) = Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d) ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
== Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
imp)

addNotSubsumed :: InteractiveImport
               -> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed :: InteractiveImport -> [InteractiveImport] -> [InteractiveImport]
addNotSubsumed i :: InteractiveImport
i is :: [InteractiveImport]
is
  | (InteractiveImport -> Bool) -> [InteractiveImport] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (InteractiveImport -> InteractiveImport -> Bool
`iiSubsumes` InteractiveImport
i) [InteractiveImport]
is = [InteractiveImport]
is
  | Bool
otherwise               = InteractiveImport
i InteractiveImport -> [InteractiveImport] -> [InteractiveImport]
forall a. a -> [a] -> [a]
: (InteractiveImport -> Bool)
-> [InteractiveImport] -> [InteractiveImport]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> (InteractiveImport -> Bool) -> InteractiveImport -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (InteractiveImport
i InteractiveImport -> InteractiveImport -> Bool
`iiSubsumes`)) [InteractiveImport]
is

-- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
-- by any of @is@.
filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
               -> [InteractiveImport]
filterSubsumed :: [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
filterSubsumed is :: [InteractiveImport]
is js :: [InteractiveImport]
js = (InteractiveImport -> Bool)
-> [InteractiveImport] -> [InteractiveImport]
forall a. (a -> Bool) -> [a] -> [a]
filter (\j :: InteractiveImport
j -> Bool -> Bool
not ((InteractiveImport -> Bool) -> [InteractiveImport] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (InteractiveImport -> InteractiveImport -> Bool
`iiSubsumes` InteractiveImport
j) [InteractiveImport]
is)) [InteractiveImport]
js

-- | Returns True if the left import subsumes the right one.  Doesn't
-- need to be 100% accurate, conservatively returning False is fine.
-- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
-- plusProv will ensue (#5904))
--
-- Note that an IIModule does not necessarily subsume an IIDecl,
-- because e.g. a module might export a name that is only available
-- qualified within the module itself.
--
-- Note that 'import M' does not necessarily subsume 'import M(foo)',
-- because M might not export foo and we want an error to be produced
-- in that case.
--
iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
iiSubsumes (IIModule m1 :: ModuleName
m1) (IIModule m2 :: ModuleName
m2) = ModuleName
m1ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
==ModuleName
m2
iiSubsumes (IIDecl d1 :: ImportDecl GhcPs
d1) (IIDecl d2 :: ImportDecl GhcPs
d2)      -- A bit crude
  =  Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d1) ModuleName -> ModuleName -> Bool
forall a. Eq a => a -> a -> Bool
== Located ModuleName -> SrcSpanLess (Located ModuleName)
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc (ImportDecl GhcPs -> Located ModuleName
forall pass. ImportDecl pass -> Located ModuleName
ideclName ImportDecl GhcPs
d2)
     Bool -> Bool -> Bool
&& ImportDecl GhcPs -> Maybe (Located ModuleName)
forall pass. ImportDecl pass -> Maybe (Located ModuleName)
ideclAs ImportDecl GhcPs
d1 Maybe (Located ModuleName) -> Maybe (Located ModuleName) -> Bool
forall a. Eq a => a -> a -> Bool
== ImportDecl GhcPs -> Maybe (Located ModuleName)
forall pass. ImportDecl pass -> Maybe (Located ModuleName)
ideclAs ImportDecl GhcPs
d2
     Bool -> Bool -> Bool
&& (Bool -> Bool
not (ImportDecl GhcPs -> Bool
forall pass. ImportDecl pass -> Bool
ideclQualified ImportDecl GhcPs
d1) Bool -> Bool -> Bool
|| ImportDecl GhcPs -> Bool
forall pass. ImportDecl pass -> Bool
ideclQualified ImportDecl GhcPs
d2)
     Bool -> Bool -> Bool
&& (ImportDecl GhcPs -> Maybe (Bool, Located [LIE GhcPs])
forall pass. ImportDecl pass -> Maybe (Bool, Located [LIE pass])
ideclHiding ImportDecl GhcPs
d1 Maybe (Bool, Located [LIE GhcPs])
-> Maybe (Bool, Located [LIE GhcPs]) -> Bool
forall a l.
(Eq a, Eq l) =>
Maybe (Bool, GenLocated l [a])
-> Maybe (Bool, GenLocated l [a]) -> Bool
`hidingSubsumes` ImportDecl GhcPs -> Maybe (Bool, Located [LIE GhcPs])
forall pass. ImportDecl pass -> Maybe (Bool, Located [LIE pass])
ideclHiding ImportDecl GhcPs
d2)
  where
     _                    hidingSubsumes :: Maybe (Bool, GenLocated l [a])
-> Maybe (Bool, GenLocated l [a]) -> Bool
`hidingSubsumes` Just (False,L _ []) = Bool
True
     Just (False, L _ xs :: [a]
xs) `hidingSubsumes` Just (False,L _ ys :: [a]
ys)
                                                           = (a -> Bool) -> [a] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [a]
xs) [a]
ys
     h1 :: Maybe (Bool, GenLocated l [a])
h1                   `hidingSubsumes` h2 :: Maybe (Bool, GenLocated l [a])
h2              = Maybe (Bool, GenLocated l [a])
h1 Maybe (Bool, GenLocated l [a])
-> Maybe (Bool, GenLocated l [a]) -> Bool
forall a. Eq a => a -> a -> Bool
== Maybe (Bool, GenLocated l [a])
h2
iiSubsumes _ _ = Bool
False


----------------------------------------------------------------------------
-- :set

-- set options in the interpreter.  Syntax is exactly the same as the
-- ghc command line, except that certain options aren't available (-C,
-- -E etc.)
--
-- This is pretty fragile: most options won't work as expected.  ToDo:
-- figure out which ones & disallow them.

setCmd :: String -> GHCi ()
setCmd :: String -> GHCi ()
setCmd ""   = Bool -> GHCi ()
showOptions Bool
False
setCmd "-a" = Bool -> GHCi ()
showOptions Bool
True
setCmd str :: String
str
  = case String -> Either String (String, String)
getCmd String
str of
    Right ("args",    rest :: String
rest) ->
        case String -> Either String [String]
toArgs String
rest of
            Left err :: String
err -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err)
            Right args :: [String]
args -> [String] -> GHCi ()
setArgs [String]
args
    Right ("prog",    rest :: String
rest) ->
        case String -> Either String [String]
toArgs String
rest of
            Right [prog :: String
prog] -> String -> GHCi ()
setProg String
prog
            _ -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr "syntax: :set prog <progname>")

    Right ("prompt",           rest :: String
rest) ->
        (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
setPromptString PromptFunction -> GHCi ()
setPrompt ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest)
                        "syntax: set prompt <string>"
    Right ("prompt-function",  rest :: String
rest) ->
        (PromptFunction -> GHCi ()) -> String -> GHCi ()
setPromptFunc PromptFunction -> GHCi ()
setPrompt (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest
    Right ("prompt-cont",          rest :: String
rest) ->
        (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
setPromptString PromptFunction -> GHCi ()
setPromptCont ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest)
                        "syntax: :set prompt-cont <string>"
    Right ("prompt-cont-function", rest :: String
rest) ->
        (PromptFunction -> GHCi ()) -> String -> GHCi ()
setPromptFunc PromptFunction -> GHCi ()
setPromptCont (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest

    Right ("editor",  rest :: String
rest) -> String -> GHCi ()
setEditor  (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest
    Right ("stop",    rest :: String
rest) -> String -> GHCi ()
setStop    (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest
    _ -> case String -> Either String [String]
toArgs String
str of
         Left err :: String
err -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err)
         Right wds :: [String]
wds -> [String] -> GHCi ()
setOptions [String]
wds

setiCmd :: String -> GHCi ()
setiCmd :: String -> GHCi ()
setiCmd ""   = GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> DynFlags -> IO ()
showDynFlags Bool
False
setiCmd "-a" = GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> DynFlags -> IO ()
showDynFlags Bool
True
setiCmd str :: String
str  =
  case String -> Either String [String]
toArgs String
str of
    Left err :: String
err -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err)
    Right wds :: [String]
wds -> Bool -> [String] -> GHCi ()
newDynFlags Bool
True [String]
wds

showOptions :: Bool -> GHCi ()
showOptions :: Bool -> GHCi ()
showOptions show_all :: Bool
show_all
  = do GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
       DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
       let opts :: [GHCiOption]
opts = GHCiState -> [GHCiOption]
options GHCiState
st
       IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (
              String -> MsgDoc
text "options currently set: " MsgDoc -> MsgDoc -> MsgDoc
<>
              if [GHCiOption] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [GHCiOption]
opts
                   then String -> MsgDoc
text "none."
                   else [MsgDoc] -> MsgDoc
hsep ((GHCiOption -> MsgDoc) -> [GHCiOption] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (\o :: GHCiOption
o -> Char -> MsgDoc
char '+' MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text (GHCiOption -> String
optToStr GHCiOption
o)) [GHCiOption]
opts)
           ))
       GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> DynFlags -> IO ()
showDynFlags Bool
show_all


showDynFlags :: Bool -> DynFlags -> IO ()
showDynFlags :: Bool -> DynFlags -> IO ()
showDynFlags show_all :: Bool
show_all dflags :: DynFlags
dflags = do
  Bool -> DynFlags -> IO ()
showLanguages' Bool
show_all DynFlags
dflags
  String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
     String -> MsgDoc
text "GHCi-specific dynamic flag settings:" MsgDoc -> MsgDoc -> MsgDoc
$$
         Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((FlagSpec GeneralFlag -> MsgDoc)
-> [FlagSpec GeneralFlag] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (String
-> String
-> (GeneralFlag -> DynFlags -> Bool)
-> FlagSpec GeneralFlag
-> MsgDoc
forall flag.
String
-> String -> (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting "-f" "-fno-" GeneralFlag -> DynFlags -> Bool
gopt) [FlagSpec GeneralFlag]
ghciFlags))
  String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
     String -> MsgDoc
text "other dynamic, non-language, flag settings:" MsgDoc -> MsgDoc -> MsgDoc
$$
         Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((FlagSpec GeneralFlag -> MsgDoc)
-> [FlagSpec GeneralFlag] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (String
-> String
-> (GeneralFlag -> DynFlags -> Bool)
-> FlagSpec GeneralFlag
-> MsgDoc
forall flag.
String
-> String -> (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting "-f" "-fno-" GeneralFlag -> DynFlags -> Bool
gopt) [FlagSpec GeneralFlag]
others))
  String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
     String -> MsgDoc
text "warning settings:" MsgDoc -> MsgDoc -> MsgDoc
$$
         Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((FlagSpec WarningFlag -> MsgDoc)
-> [FlagSpec WarningFlag] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (String
-> String
-> (WarningFlag -> DynFlags -> Bool)
-> FlagSpec WarningFlag
-> MsgDoc
forall flag.
String
-> String -> (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting "-W" "-Wno-" WarningFlag -> DynFlags -> Bool
wopt) [FlagSpec WarningFlag]
DynFlags.wWarningFlags))
  where
        setting :: String
-> String -> (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting prefix :: String
prefix noPrefix :: String
noPrefix test :: flag -> DynFlags -> Bool
test flag :: FlagSpec flag
flag
          | Bool
quiet     = MsgDoc
empty
          | Bool
is_on     = String -> MsgDoc
text String
prefix MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text String
name
          | Bool
otherwise = String -> MsgDoc
text String
noPrefix MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text String
name
          where name :: String
name = FlagSpec flag -> String
forall flag. FlagSpec flag -> String
flagSpecName FlagSpec flag
flag
                f :: flag
f = FlagSpec flag -> flag
forall flag. FlagSpec flag -> flag
flagSpecFlag FlagSpec flag
flag
                is_on :: Bool
is_on = flag -> DynFlags -> Bool
test flag
f DynFlags
dflags
                quiet :: Bool
quiet = Bool -> Bool
not Bool
show_all Bool -> Bool -> Bool
&& flag -> DynFlags -> Bool
test flag
f DynFlags
default_dflags Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
is_on

        llvmConfig :: (LlvmTargets, LlvmPasses)
llvmConfig = (DynFlags -> LlvmTargets
llvmTargets DynFlags
dflags, DynFlags -> LlvmPasses
llvmPasses DynFlags
dflags)

        default_dflags :: DynFlags
default_dflags = Settings -> (LlvmTargets, LlvmPasses) -> DynFlags
defaultDynFlags (DynFlags -> Settings
settings DynFlags
dflags) (LlvmTargets, LlvmPasses)
llvmConfig

        (ghciFlags :: [FlagSpec GeneralFlag]
ghciFlags,others :: [FlagSpec GeneralFlag]
others)  = (FlagSpec GeneralFlag -> Bool)
-> [FlagSpec GeneralFlag]
-> ([FlagSpec GeneralFlag], [FlagSpec GeneralFlag])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (\f :: FlagSpec GeneralFlag
f -> FlagSpec GeneralFlag -> GeneralFlag
forall flag. FlagSpec flag -> flag
flagSpecFlag FlagSpec GeneralFlag
f GeneralFlag -> [GeneralFlag] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [GeneralFlag]
flgs)
                                        [FlagSpec GeneralFlag]
DynFlags.fFlags
        flgs :: [GeneralFlag]
flgs = [ GeneralFlag
Opt_PrintExplicitForalls
               , GeneralFlag
Opt_PrintExplicitKinds
               , GeneralFlag
Opt_PrintUnicodeSyntax
               , GeneralFlag
Opt_PrintBindResult
               , GeneralFlag
Opt_BreakOnException
               , GeneralFlag
Opt_BreakOnError
               , GeneralFlag
Opt_PrintEvldWithShow
               ]

setArgs, setOptions :: [String] -> GHCi ()
setProg, setEditor, setStop :: String -> GHCi ()

setArgs :: [String] -> GHCi ()
setArgs args :: [String]
args = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  ForeignHValue
wrapper <- String -> [String] -> GHCi ForeignHValue
forall (m :: * -> *).
GhcMonad m =>
String -> [String] -> m ForeignHValue
mkEvalWrapper (GHCiState -> String
progname GHCiState
st) [String]
args
  GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st { args :: [String]
GhciMonad.args = [String]
args, evalWrapper :: ForeignHValue
evalWrapper = ForeignHValue
wrapper }

setProg :: String -> GHCi ()
setProg prog :: String
prog = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  ForeignHValue
wrapper <- String -> [String] -> GHCi ForeignHValue
forall (m :: * -> *).
GhcMonad m =>
String -> [String] -> m ForeignHValue
mkEvalWrapper String
prog (GHCiState -> [String]
GhciMonad.args GHCiState
st)
  GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st { progname :: String
progname = String
prog, evalWrapper :: ForeignHValue
evalWrapper = ForeignHValue
wrapper }

setEditor :: String -> GHCi ()
setEditor cmd :: String
cmd = (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st { editor :: String
editor = String
cmd })

setStop :: String -> GHCi ()
setStop str :: String
str@(c :: Char
c:_) | Char -> Bool
isDigit Char
c
  = do let (nm_str :: String
nm_str,rest :: String
rest) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Bool -> Bool
not(Bool -> Bool) -> (Char -> Bool) -> Char -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
.Char -> Bool
isDigit) String
str
           nm :: Int
nm = String -> Int
forall a. Read a => String -> a
read String
nm_str
       GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
       let old_breaks :: [(Int, BreakLocation)]
old_breaks = GHCiState -> [(Int, BreakLocation)]
breaks GHCiState
st
       if ((Int, BreakLocation) -> Bool) -> [(Int, BreakLocation)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
nm) (Int -> Bool)
-> ((Int, BreakLocation) -> Int) -> (Int, BreakLocation) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, BreakLocation) -> Int
forall a b. (a, b) -> a
fst) [(Int, BreakLocation)]
old_breaks
              then MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (String -> MsgDoc
text "Breakpoint" MsgDoc -> MsgDoc -> MsgDoc
<+> Int -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Int
nm MsgDoc -> MsgDoc -> MsgDoc
<+>
                                 String -> MsgDoc
text "does not exist")
              else do
       let new_breaks :: [(Int, BreakLocation)]
new_breaks = ((Int, BreakLocation) -> (Int, BreakLocation))
-> [(Int, BreakLocation)] -> [(Int, BreakLocation)]
forall a b. (a -> b) -> [a] -> [b]
map (Int, BreakLocation) -> (Int, BreakLocation)
fn [(Int, BreakLocation)]
old_breaks
           fn :: (Int, BreakLocation) -> (Int, BreakLocation)
fn (i :: Int
i,loc :: BreakLocation
loc) | Int
i Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
nm   = (Int
i,BreakLocation
loc { onBreakCmd :: String
onBreakCmd = (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
rest })
                      | Bool
otherwise = (Int
i,BreakLocation
loc)
       GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{ breaks :: [(Int, BreakLocation)]
breaks = [(Int, BreakLocation)]
new_breaks }
setStop cmd :: String
cmd = (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st { stop :: String
stop = String
cmd })

setPrompt :: PromptFunction -> GHCi ()
setPrompt :: PromptFunction -> GHCi ()
setPrompt v :: PromptFunction
v = (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st {prompt :: PromptFunction
prompt = PromptFunction
v})

setPromptCont :: PromptFunction -> GHCi ()
setPromptCont :: PromptFunction -> GHCi ()
setPromptCont v :: PromptFunction
v = (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st {prompt_cont :: PromptFunction
prompt_cont = PromptFunction
v})

setPromptFunc :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
setPromptFunc :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
setPromptFunc fSetPrompt :: PromptFunction -> GHCi ()
fSetPrompt s :: String
s = do
    -- We explicitly annotate the type of the expression to ensure
    -- that unsafeCoerce# is passed the exact type necessary rather
    -- than a more general one
    let exprStr :: String
exprStr = "(" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ ") :: [String] -> Int -> IO String"
    (HValue funValue :: Any
funValue) <- String -> GHCi HValue
forall (m :: * -> *). GhcMonad m => String -> m HValue
GHC.compileExpr String
exprStr
    PromptFunction -> GHCi ()
fSetPrompt (([String] -> Int -> IO String) -> PromptFunction
convertToPromptFunction (([String] -> Int -> IO String) -> PromptFunction)
-> ([String] -> Int -> IO String) -> PromptFunction
forall a b. (a -> b) -> a -> b
$ Any -> [String] -> Int -> IO String
forall a b. a -> b
unsafeCoerce Any
funValue)
    where
      convertToPromptFunction :: ([String] -> Int -> IO String)
                              -> PromptFunction
      convertToPromptFunction :: ([String] -> Int -> IO String) -> PromptFunction
convertToPromptFunction func :: [String] -> Int -> IO String
func = (\mods :: [String]
mods line :: Int
line -> IO MsgDoc -> GHCi MsgDoc
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO MsgDoc -> GHCi MsgDoc) -> IO MsgDoc -> GHCi MsgDoc
forall a b. (a -> b) -> a -> b
$
                                       (String -> MsgDoc) -> IO String -> IO MsgDoc
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM String -> MsgDoc
text ([String] -> Int -> IO String
func [String]
mods Int
line))

setPromptString :: (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
setPromptString :: (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
setPromptString fSetPrompt :: PromptFunction -> GHCi ()
fSetPrompt value :: String
value err :: String
err = do
  if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
value
    then IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStrLn Handle
stderr (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ String
err
    else case String
value of
           ('\"':_) ->
             case ReadS String
forall a. Read a => ReadS a
reads String
value of
               [(value' :: String
value', xs :: String
xs)] | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isSpace String
xs ->
                 (PromptFunction -> GHCi ()) -> String -> GHCi ()
setParsedPromptString PromptFunction -> GHCi ()
fSetPrompt String
value'
               _ -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStrLn Handle
stderr
                             "Can't parse prompt string. Use Haskell syntax."
           _ ->
             (PromptFunction -> GHCi ()) -> String -> GHCi ()
setParsedPromptString PromptFunction -> GHCi ()
fSetPrompt String
value

setParsedPromptString :: (PromptFunction -> GHCi ()) ->  String -> GHCi ()
setParsedPromptString :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
setParsedPromptString fSetPrompt :: PromptFunction -> GHCi ()
fSetPrompt s :: String
s = do
  case (String -> Maybe String
checkPromptStringForErrors String
s) of
    Just err :: String
err ->
      IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStrLn Handle
stderr String
err
    Nothing ->
      PromptFunction -> GHCi ()
fSetPrompt (PromptFunction -> GHCi ()) -> PromptFunction -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> PromptFunction
generatePromptFunctionFromString String
s

setOptions :: [String] -> GHCi ()
setOptions wds :: [String]
wds =
   do -- first, deal with the GHCi opts (+s, +t, etc.)
      let (plus_opts :: [String]
plus_opts, minus_opts :: [String]
minus_opts)  = (String -> Either String String)
-> [String] -> ([String], [String])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith String -> Either String String
isPlus [String]
wds
      (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> GHCi ()
setOpt [String]
plus_opts
      -- then, dynamic flags
      Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
minus_opts)) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> [String] -> GHCi ()
newDynFlags Bool
False [String]
minus_opts

newDynFlags :: Bool -> [String] -> GHCi ()
newDynFlags :: Bool -> [String] -> GHCi ()
newDynFlags interactive_only :: Bool
interactive_only minus_opts :: [String]
minus_opts = do
      let lopts :: [Located String]
lopts = (String -> Located String) -> [String] -> [Located String]
forall a b. (a -> b) -> [a] -> [b]
map String -> Located String
forall a. HasSrcSpan a => SrcSpanLess a -> a
noLoc [String]
minus_opts

      DynFlags
idflags0 <- GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags
      (idflags1 :: DynFlags
idflags1, leftovers :: [Located String]
leftovers, warns :: [Warn]
warns) <- DynFlags
-> [Located String] -> GHCi (DynFlags, [Located String], [Warn])
forall (m :: * -> *).
MonadIO m =>
DynFlags
-> [Located String] -> m (DynFlags, [Located String], [Warn])
GHC.parseDynamicFlags DynFlags
idflags0 [Located String]
lopts

      IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> [Warn] -> IO ()
handleFlagWarnings DynFlags
idflags1 [Warn]
warns
      Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not (Bool -> Bool) -> Bool -> Bool
forall a b. (a -> b) -> a -> b
$ [Located String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Located String]
leftovers)
           (GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> GHCi ())
-> (String -> GhcException) -> String -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> GhcException
CmdLineError
            (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ "Some flags have not been recognized: "
            String -> String -> String
forall a. [a] -> [a] -> [a]
++ ([String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([String] -> String)
-> ([String] -> [String]) -> [String] -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> [String] -> [String]
forall a. a -> [a] -> [a]
intersperse ", " ([String] -> String) -> [String] -> String
forall a b. (a -> b) -> a -> b
$ (Located String -> String) -> [Located String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Located String -> String
forall a. HasSrcSpan a => a -> SrcSpanLess a
unLoc [Located String]
leftovers))

      Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool
interactive_only Bool -> Bool -> Bool
&& DynFlags -> DynFlags -> Bool
packageFlagsChanged DynFlags
idflags1 DynFlags
idflags0) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
          IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Handle -> String -> IO ()
hPutStrLn Handle
stderr "cannot set package flags with :seti; use :set"
      -- Load any new plugins
      HscEnv
hsc_env0 <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
      DynFlags
idflags2 <- IO DynFlags -> GHCi DynFlags
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (HscEnv -> DynFlags -> IO DynFlags
initializePlugins HscEnv
hsc_env0 DynFlags
idflags1)
      DynFlags -> GHCi ()
forall (m :: * -> *). GhcMonad m => DynFlags -> m ()
GHC.setInteractiveDynFlags DynFlags
idflags2
      Maybe String -> Bool -> GHCi ()
installInteractivePrint (DynFlags -> Maybe String
interactivePrint DynFlags
idflags1) Bool
False

      DynFlags
dflags0 <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

      Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
interactive_only) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
        (dflags1 :: DynFlags
dflags1, _, _) <- IO (DynFlags, [Located String], [Warn])
-> GHCi (DynFlags, [Located String], [Warn])
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (DynFlags, [Located String], [Warn])
 -> GHCi (DynFlags, [Located String], [Warn]))
-> IO (DynFlags, [Located String], [Warn])
-> GHCi (DynFlags, [Located String], [Warn])
forall a b. (a -> b) -> a -> b
$ DynFlags
-> [Located String] -> IO (DynFlags, [Located String], [Warn])
forall (m :: * -> *).
MonadIO m =>
DynFlags
-> [Located String] -> m (DynFlags, [Located String], [Warn])
GHC.parseDynamicFlags DynFlags
dflags0 [Located String]
lopts
        [InstalledUnitId]
new_pkgs <- DynFlags -> GHCi [InstalledUnitId]
forall (m :: * -> *). GhcMonad m => DynFlags -> m [InstalledUnitId]
GHC.setProgramDynFlags DynFlags
dflags1

        -- if the package flags changed, reset the context and link
        -- the new packages.
        HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
        let dflags2 :: DynFlags
dflags2 = HscEnv -> DynFlags
hsc_dflags HscEnv
hsc_env
        Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DynFlags -> DynFlags -> Bool
packageFlagsChanged DynFlags
dflags2 DynFlags
dflags0) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
          Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (DynFlags -> Int
verbosity DynFlags
dflags2 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> 0) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$
            IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (String -> IO ()) -> String -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$
              "package flags have changed, resetting and loading new packages..."
          [Target] -> GHCi ()
forall (m :: * -> *). GhcMonad m => [Target] -> m ()
GHC.setTargets []
          SuccessFlag
_ <- LoadHowMuch -> GHCi SuccessFlag
forall (m :: * -> *). GhcMonad m => LoadHowMuch -> m SuccessFlag
GHC.load LoadHowMuch
LoadAllTargets
          IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ HscEnv -> [InstalledUnitId] -> IO ()
linkPackages HscEnv
hsc_env [InstalledUnitId]
new_pkgs
          -- package flags changed, we can't re-use any of the old context
          Bool -> [ModSummary] -> GHCi ()
setContextAfterLoad Bool
False []
          -- and copy the package state to the interactive DynFlags
          DynFlags
idflags <- GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags
          DynFlags -> GHCi ()
forall (m :: * -> *). GhcMonad m => DynFlags -> m ()
GHC.setInteractiveDynFlags
              DynFlags
idflags{ pkgState :: PackageState
pkgState = DynFlags -> PackageState
pkgState DynFlags
dflags2
                     , pkgDatabase :: Maybe
  [(String,
    [InstalledPackageInfo
       ComponentId
       SourcePackageId
       PackageName
       InstalledUnitId
       UnitId
       ModuleName
       Module])]
pkgDatabase = DynFlags
-> Maybe
     [(String,
       [InstalledPackageInfo
          ComponentId
          SourcePackageId
          PackageName
          InstalledUnitId
          UnitId
          ModuleName
          Module])]
pkgDatabase DynFlags
dflags2
                     , packageFlags :: [PackageFlag]
packageFlags = DynFlags -> [PackageFlag]
packageFlags DynFlags
dflags2 }

        let ld0length :: Int
ld0length   = [Option] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([Option] -> Int) -> [Option] -> Int
forall a b. (a -> b) -> a -> b
$ DynFlags -> [Option]
ldInputs DynFlags
dflags0
            fmrk0length :: Int
fmrk0length = [String] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length ([String] -> Int) -> [String] -> Int
forall a b. (a -> b) -> a -> b
$ DynFlags -> [String]
cmdlineFrameworks DynFlags
dflags0

            newLdInputs :: [Option]
newLdInputs     = Int -> [Option] -> [Option]
forall a. Int -> [a] -> [a]
drop Int
ld0length (DynFlags -> [Option]
ldInputs DynFlags
dflags2)
            newCLFrameworks :: [String]
newCLFrameworks = Int -> [String] -> [String]
forall a. Int -> [a] -> [a]
drop Int
fmrk0length (DynFlags -> [String]
cmdlineFrameworks DynFlags
dflags2)

            hsc_env' :: HscEnv
hsc_env' = HscEnv
hsc_env { hsc_dflags :: DynFlags
hsc_dflags =
                         DynFlags
dflags2 { ldInputs :: [Option]
ldInputs = [Option]
newLdInputs
                                 , cmdlineFrameworks :: [String]
cmdlineFrameworks = [String]
newCLFrameworks } }

        Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([Option] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Option]
newLdInputs Bool -> Bool -> Bool
&& [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
newCLFrameworks)) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$
          IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ HscEnv -> IO ()
linkCmdLineLibs HscEnv
hsc_env'

      () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()


unsetOptions :: String -> GHCi ()
unsetOptions :: String -> GHCi ()
unsetOptions str :: String
str
  =   -- first, deal with the GHCi opts (+s, +t, etc.)
     let opts :: [String]
opts = String -> [String]
words String
str
         (minus_opts :: [String]
minus_opts, rest1 :: [String]
rest1) = (String -> Bool) -> [String] -> ([String], [String])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition String -> Bool
isMinus [String]
opts
         (plus_opts :: [String]
plus_opts, rest2 :: [String]
rest2)  = (String -> Either String String)
-> [String] -> ([String], [String])
forall a b c. (a -> Either b c) -> [a] -> ([b], [c])
partitionWith String -> Either String String
isPlus [String]
rest1
         (other_opts :: [String]
other_opts, rest3 :: [String]
rest3) = (String -> Bool) -> [String] -> ([String], [String])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (String -> [String] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` ((String, GHCi ()) -> String) -> [(String, GHCi ())] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String, GHCi ()) -> String
forall a b. (a, b) -> a
fst [(String, GHCi ())]
defaulters) [String]
rest2

         defaulters :: [(String, GHCi ())]
defaulters =
           [ ("args"   , [String] -> GHCi ()
setArgs [String]
default_args)
           , ("prog"   , String -> GHCi ()
setProg String
default_progname)
           , ("prompt"     , PromptFunction -> GHCi ()
setPrompt PromptFunction
default_prompt)
           , ("prompt-cont", PromptFunction -> GHCi ()
setPromptCont PromptFunction
default_prompt_cont)
           , ("editor" , IO String -> GHCi String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO IO String
findEditor GHCi String -> (String -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= String -> GHCi ()
setEditor)
           , ("stop"   , String -> GHCi ()
setStop String
default_stop)
           ]

         no_flag :: String -> m String
no_flag ('-':'f':rest :: String
rest) = String -> m String
forall (m :: * -> *) a. Monad m => a -> m a
return ("-fno-" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
rest)
         no_flag ('-':'X':rest :: String
rest) = String -> m String
forall (m :: * -> *) a. Monad m => a -> m a
return ("-XNo" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
rest)
         no_flag f :: String
f = GhcException -> m String
forall a. GhcException -> a
throwGhcException (String -> GhcException
ProgramError ("don't know how to reverse " String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
f))

     in if (Bool -> Bool
not ([String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
rest3))
           then IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn ("unknown option: '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ [String] -> String
forall a. [a] -> a
head [String]
rest3 String -> String -> String
forall a. [a] -> [a] -> [a]
++ "'"))
           else do
             (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Maybe (GHCi ()) -> GHCi ()
forall a. HasCallStack => Maybe a -> a
fromJust(Maybe (GHCi ()) -> GHCi ())
-> (String -> Maybe (GHCi ())) -> String -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(String -> [(String, GHCi ())] -> Maybe (GHCi ()))
-> [(String, GHCi ())] -> String -> Maybe (GHCi ())
forall a b c. (a -> b -> c) -> b -> a -> c
flip String -> [(String, GHCi ())] -> Maybe (GHCi ())
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup [(String, GHCi ())]
defaulters) [String]
other_opts

             (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> GHCi ()
unsetOpt [String]
plus_opts

             [String]
no_flags <- (String -> GHCi String) -> [String] -> GHCi [String]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM String -> GHCi String
forall (m :: * -> *). Monad m => String -> m String
no_flag [String]
minus_opts
             Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not ([String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
no_flags)) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Bool -> [String] -> GHCi ()
newDynFlags Bool
False [String]
no_flags

isMinus :: String -> Bool
isMinus :: String -> Bool
isMinus ('-':_) = Bool
True
isMinus _ = Bool
False

isPlus :: String -> Either String String
isPlus :: String -> Either String String
isPlus ('+':opt :: String
opt) = String -> Either String String
forall a b. a -> Either a b
Left String
opt
isPlus other :: String
other     = String -> Either String String
forall a b. b -> Either a b
Right String
other

setOpt, unsetOpt :: String -> GHCi ()

setOpt :: String -> GHCi ()
setOpt str :: String
str
  = case String -> Maybe GHCiOption
strToGHCiOpt String
str of
        Nothing -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn ("unknown option: '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
str String -> String -> String
forall a. [a] -> [a] -> [a]
++ "'"))
        Just o :: GHCiOption
o  -> GHCiOption -> GHCi ()
setOption GHCiOption
o

unsetOpt :: String -> GHCi ()
unsetOpt str :: String
str
  = case String -> Maybe GHCiOption
strToGHCiOpt String
str of
        Nothing -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn ("unknown option: '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
str String -> String -> String
forall a. [a] -> [a] -> [a]
++ "'"))
        Just o :: GHCiOption
o  -> GHCiOption -> GHCi ()
unsetOption GHCiOption
o

strToGHCiOpt :: String -> (Maybe GHCiOption)
strToGHCiOpt :: String -> Maybe GHCiOption
strToGHCiOpt "m" = GHCiOption -> Maybe GHCiOption
forall a. a -> Maybe a
Just GHCiOption
Multiline
strToGHCiOpt "s" = GHCiOption -> Maybe GHCiOption
forall a. a -> Maybe a
Just GHCiOption
ShowTiming
strToGHCiOpt "t" = GHCiOption -> Maybe GHCiOption
forall a. a -> Maybe a
Just GHCiOption
ShowType
strToGHCiOpt "r" = GHCiOption -> Maybe GHCiOption
forall a. a -> Maybe a
Just GHCiOption
RevertCAFs
strToGHCiOpt "c" = GHCiOption -> Maybe GHCiOption
forall a. a -> Maybe a
Just GHCiOption
CollectInfo
strToGHCiOpt _   = Maybe GHCiOption
forall a. Maybe a
Nothing

optToStr :: GHCiOption -> String
optToStr :: GHCiOption -> String
optToStr Multiline  = "m"
optToStr ShowTiming = "s"
optToStr ShowType   = "t"
optToStr RevertCAFs = "r"
optToStr CollectInfo = "c"


-- ---------------------------------------------------------------------------
-- :show

showCmd :: String -> GHCi ()
showCmd :: String -> GHCi ()
showCmd ""   = Bool -> GHCi ()
showOptions Bool
False
showCmd "-a" = Bool -> GHCi ()
showOptions Bool
True
showCmd str :: String
str = do
    GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
    DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

    let lookupCmd :: String -> Maybe (GHCi ())
        lookupCmd :: String -> Maybe (GHCi ())
lookupCmd name :: String
name = String -> [(String, GHCi ())] -> Maybe (GHCi ())
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup String
name ([(String, GHCi ())] -> Maybe (GHCi ()))
-> [(String, GHCi ())] -> Maybe (GHCi ())
forall a b. (a -> b) -> a -> b
$ ((Bool, String, GHCi ()) -> (String, GHCi ()))
-> [(Bool, String, GHCi ())] -> [(String, GHCi ())]
forall a b. (a -> b) -> [a] -> [b]
map (\(_,b :: String
b,c :: GHCi ()
c) -> (String
b,GHCi ()
c)) [(Bool, String, GHCi ())]
cmds

        -- (show in help?, command name, action)
        action :: String -> GHCi () -> (Bool, String, GHCi ())
        action :: String -> GHCi () -> (Bool, String, GHCi ())
action name :: String
name m :: GHCi ()
m = (Bool
True, String
name, GHCi ()
m)

        hidden :: String -> GHCi () -> (Bool, String, GHCi ())
        hidden :: String -> GHCi () -> (Bool, String, GHCi ())
hidden name :: String
name m :: GHCi ()
m = (Bool
False, String
name, GHCi ()
m)

        cmds :: [(Bool, String, GHCi ())]
cmds =
            [ String -> GHCi () -> (Bool, String, GHCi ())
action "args"       (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn ([String] -> String
forall a. Show a => a -> String
show (GHCiState -> [String]
GhciMonad.args GHCiState
st))
            , String -> GHCi () -> (Bool, String, GHCi ())
action "prog"       (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> String
forall a. Show a => a -> String
show (GHCiState -> String
progname GHCiState
st))
            , String -> GHCi () -> (Bool, String, GHCi ())
action "editor"     (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> String
forall a. Show a => a -> String
show (GHCiState -> String
editor GHCiState
st))
            , String -> GHCi () -> (Bool, String, GHCi ())
action "stop"       (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> String
forall a. Show a => a -> String
show (GHCiState -> String
stop GHCiState
st))
            , String -> GHCi () -> (Bool, String, GHCi ())
action "imports"    (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showImports
            , String -> GHCi () -> (Bool, String, GHCi ())
action "modules"    (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showModules
            , String -> GHCi () -> (Bool, String, GHCi ())
action "bindings"   (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showBindings
            , String -> GHCi () -> (Bool, String, GHCi ())
action "linker"     (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> IO ()
showLinkerState
            , String -> GHCi () -> (Bool, String, GHCi ())
action "breaks"     (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showBkptTable
            , String -> GHCi () -> (Bool, String, GHCi ())
action "context"    (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showContext
            , String -> GHCi () -> (Bool, String, GHCi ())
action "packages"   (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showPackages
            , String -> GHCi () -> (Bool, String, GHCi ())
action "paths"      (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showPaths
            , String -> GHCi () -> (Bool, String, GHCi ())
action "language"   (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showLanguages
            , String -> GHCi () -> (Bool, String, GHCi ())
hidden "languages"  (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showLanguages -- backwards compat
            , String -> GHCi () -> (Bool, String, GHCi ())
hidden "lang"       (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showLanguages -- useful abbreviation
            , String -> GHCi () -> (Bool, String, GHCi ())
action "targets"    (GHCi () -> (Bool, String, GHCi ()))
-> GHCi () -> (Bool, String, GHCi ())
forall a b. (a -> b) -> a -> b
$ GHCi ()
showTargets
            ]

    case String -> [String]
words String
str of
      [w :: String
w] | Just action :: GHCi ()
action <- String -> Maybe (GHCi ())
lookupCmd String
w -> GHCi ()
action

      _ -> let helpCmds :: [MsgDoc]
helpCmds = [ String -> MsgDoc
text String
name | (True, name :: String
name, _) <- [(Bool, String, GHCi ())]
cmds ]
           in GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (GhcException -> GHCi ()) -> GhcException -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GhcException
CmdLineError (String -> GhcException) -> String -> GhcException
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags
              (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$ MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text "syntax:") 4
              (MsgDoc -> MsgDoc) -> MsgDoc -> MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc -> Int -> MsgDoc -> MsgDoc
hang (String -> MsgDoc
text ":show") 6
              (MsgDoc -> MsgDoc) -> MsgDoc -> MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc -> MsgDoc
brackets ([MsgDoc] -> MsgDoc
fsep ([MsgDoc] -> MsgDoc) -> [MsgDoc] -> MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc -> [MsgDoc] -> [MsgDoc]
punctuate (String -> MsgDoc
text " |") [MsgDoc]
helpCmds)

showiCmd :: String -> GHCi ()
showiCmd :: String -> GHCi ()
showiCmd str :: String
str = do
  case String -> [String]
words String
str of
        ["languages"]  -> GHCi ()
showiLanguages -- backwards compat
        ["language"]   -> GHCi ()
showiLanguages
        ["lang"]       -> GHCi ()
showiLanguages -- useful abbreviation
        _ -> GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError ("syntax:  :showi language"))

showImports :: GHCi ()
showImports :: GHCi ()
showImports = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let rem_ctx :: [InteractiveImport]
rem_ctx   = [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a]
reverse (GHCiState -> [InteractiveImport]
remembered_ctx GHCiState
st)
      trans_ctx :: [InteractiveImport]
trans_ctx = GHCiState -> [InteractiveImport]
transient_ctx GHCiState
st

      show_one :: InteractiveImport -> String
show_one (IIModule star_m :: ModuleName
star_m)
          = ":module +*" String -> String -> String
forall a. [a] -> [a] -> [a]
++ ModuleName -> String
moduleNameString ModuleName
star_m
      show_one (IIDecl imp :: ImportDecl GhcPs
imp) = DynFlags -> ImportDecl GhcPs -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags ImportDecl GhcPs
imp

  [InteractiveImport]
prel_iidecls <- [InteractiveImport] -> GHCi [InteractiveImport]
getImplicitPreludeImports ([InteractiveImport]
rem_ctx [InteractiveImport] -> [InteractiveImport] -> [InteractiveImport]
forall a. [a] -> [a] -> [a]
++ [InteractiveImport]
trans_ctx)

  let show_prel :: InteractiveImport -> String
show_prel p :: InteractiveImport
p = InteractiveImport -> String
show_one InteractiveImport
p String -> String -> String
forall a. [a] -> [a] -> [a]
++ " -- implicit"
      show_extra :: ImportDecl GhcPs -> String
show_extra p :: ImportDecl GhcPs
p = InteractiveImport -> String
show_one (ImportDecl GhcPs -> InteractiveImport
IIDecl ImportDecl GhcPs
p) String -> String -> String
forall a. [a] -> [a] -> [a]
++ " -- fixed"

      trans_comment :: String -> String
trans_comment s :: String
s = String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ " -- added automatically" :: String
  --
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (String -> IO ()) -> [String] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> IO ()
putStrLn ((InteractiveImport -> String) -> [InteractiveImport] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map InteractiveImport -> String
show_one [InteractiveImport]
rem_ctx [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
                           (InteractiveImport -> String) -> [InteractiveImport] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String -> String
trans_comment (String -> String)
-> (InteractiveImport -> String) -> InteractiveImport -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. InteractiveImport -> String
show_one) [InteractiveImport]
trans_ctx [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
                           (InteractiveImport -> String) -> [InteractiveImport] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map InteractiveImport -> String
show_prel [InteractiveImport]
prel_iidecls [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++
                           (ImportDecl GhcPs -> String) -> [ImportDecl GhcPs] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map ImportDecl GhcPs -> String
show_extra (GHCiState -> [ImportDecl GhcPs]
extra_imports GHCiState
st))

showModules :: GHCi ()
showModules :: GHCi ()
showModules = do
  [ModSummary]
loaded_mods <- GHCi [ModSummary]
forall (m :: * -> *). GhcMonad m => m [ModSummary]
getLoadedModules
        -- we want *loaded* modules only, see #1734
  let show_one :: ModSummary -> m ()
show_one ms :: ModSummary
ms = do String
m <- ModSummary -> m String
forall (m :: * -> *). GhcMonad m => ModSummary -> m String
GHC.showModule ModSummary
ms; IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn String
m)
  (ModSummary -> GHCi ()) -> [ModSummary] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ ModSummary -> GHCi ()
forall (m :: * -> *). GhcMonad m => ModSummary -> m ()
show_one [ModSummary]
loaded_mods

getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
getLoadedModules :: m [ModSummary]
getLoadedModules = do
  ModuleGraph
graph <- m ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
  (ModSummary -> m Bool) -> [ModSummary] -> m [ModSummary]
forall (m :: * -> *) a.
Applicative m =>
(a -> m Bool) -> [a] -> m [a]
filterM (ModuleName -> m Bool
forall (m :: * -> *). GhcMonad m => ModuleName -> m Bool
GHC.isLoaded (ModuleName -> m Bool)
-> (ModSummary -> ModuleName) -> ModSummary -> m Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ModSummary -> ModuleName
GHC.ms_mod_name) (ModuleGraph -> [ModSummary]
GHC.mgModSummaries ModuleGraph
graph)

showBindings :: GHCi ()
showBindings :: GHCi ()
showBindings = do
    [TyThing]
bindings <- GHCi [TyThing]
forall (m :: * -> *). GhcMonad m => m [TyThing]
GHC.getBindings
    (insts :: [ClsInst]
insts, finsts :: [FamInst]
finsts) <- GHCi ([ClsInst], [FamInst])
forall (m :: * -> *). GhcMonad m => m ([ClsInst], [FamInst])
GHC.getInsts
    let idocs :: [MsgDoc]
idocs  = (ClsInst -> MsgDoc) -> [ClsInst] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map ClsInst -> MsgDoc
GHC.pprInstanceHdr [ClsInst]
insts
        fidocs :: [MsgDoc]
fidocs = (FamInst -> MsgDoc) -> [FamInst] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map FamInst -> MsgDoc
GHC.pprFamInst [FamInst]
finsts
        binds :: [TyThing]
binds = (TyThing -> Bool) -> [TyThing] -> [TyThing]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (TyThing -> Bool) -> TyThing -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. OccName -> Bool
isDerivedOccName (OccName -> Bool) -> (TyThing -> OccName) -> TyThing -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TyThing -> OccName
forall a. NamedThing a => a -> OccName
getOccName) [TyThing]
bindings -- #12525
        -- See Note [Filter bindings]
    [MsgDoc]
docs <- (TyThing -> GHCi MsgDoc) -> [TyThing] -> GHCi [MsgDoc]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM TyThing -> GHCi MsgDoc
forall (m :: * -> *). GhcMonad m => TyThing -> m MsgDoc
makeDoc ([TyThing] -> [TyThing]
forall a. [a] -> [a]
reverse [TyThing]
binds)
                  -- reverse so the new ones come last
    (MsgDoc -> GHCi ()) -> [MsgDoc] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ MsgDoc -> GHCi ()
printForUserPartWay ([MsgDoc]
docs [MsgDoc] -> [MsgDoc] -> [MsgDoc]
forall a. [a] -> [a] -> [a]
++ [MsgDoc]
idocs [MsgDoc] -> [MsgDoc] -> [MsgDoc]
forall a. [a] -> [a] -> [a]
++ [MsgDoc]
fidocs)
  where
    makeDoc :: TyThing -> m MsgDoc
makeDoc (AnId i :: Id
i) = Id -> m MsgDoc
forall (m :: * -> *). GhcMonad m => Id -> m MsgDoc
pprTypeAndContents Id
i
    makeDoc tt :: TyThing
tt = do
        Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)
mb_stuff <- Bool
-> Name
-> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc))
forall (m :: * -> *).
GhcMonad m =>
Bool
-> Name
-> m (Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc))
GHC.getInfo Bool
False (TyThing -> Name
forall a. NamedThing a => a -> Name
getName TyThing
tt)
        MsgDoc -> m MsgDoc
forall (m :: * -> *) a. Monad m => a -> m a
return (MsgDoc -> m MsgDoc) -> MsgDoc -> m MsgDoc
forall a b. (a -> b) -> a -> b
$ MsgDoc
-> ((TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc)
-> Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)
-> MsgDoc
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (String -> MsgDoc
text "") (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc
pprTT Maybe (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc)
mb_stuff

    pprTT :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
    pprTT :: (TyThing, Fixity, [ClsInst], [FamInst], MsgDoc) -> MsgDoc
pprTT (thing :: TyThing
thing, fixity :: Fixity
fixity, _cls_insts :: [ClsInst]
_cls_insts, _fam_insts :: [FamInst]
_fam_insts, _docs :: MsgDoc
_docs)
      = ShowSub -> TyThing -> MsgDoc
pprTyThing ShowSub
showToHeader TyThing
thing
        MsgDoc -> MsgDoc -> MsgDoc
$$ MsgDoc
show_fixity
      where
        show_fixity :: MsgDoc
show_fixity
            | Fixity
fixity Fixity -> Fixity -> Bool
forall a. Eq a => a -> a -> Bool
== Fixity
GHC.defaultFixity  = MsgDoc
empty
            | Bool
otherwise                    = Fixity -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Fixity
fixity MsgDoc -> MsgDoc -> MsgDoc
<+> Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (TyThing -> Name
forall a. NamedThing a => a -> Name
GHC.getName TyThing
thing)


printTyThing :: TyThing -> GHCi ()
printTyThing :: TyThing -> GHCi ()
printTyThing tyth :: TyThing
tyth = MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (ShowSub -> TyThing -> MsgDoc
pprTyThing ShowSub
showToHeader TyThing
tyth)

{-
Note [Filter bindings]
~~~~~~~~~~~~~~~~~~~~~~

If we don't filter the bindings returned by the function GHC.getBindings,
then the :show bindings command will also show unwanted bound names,
internally generated by GHC, eg:
    $tcFoo :: GHC.Types.TyCon = _
    $trModule :: GHC.Types.Module = _ .

The filter was introduced as a fix for Trac #12525 [1]. Comment:1 [2] to this
ticket contains an analysis of the situation and suggests the solution
implemented above.

The same filter was also implemented to fix Trac #11051 [3]. See the
Note [What to show to users] in compiler/main/InteractiveEval.hs

[1] https://ghc.haskell.org/trac/ghc/ticket/12525
[2] https://ghc.haskell.org/trac/ghc/ticket/12525#comment:1
[3] https://ghc.haskell.org/trac/ghc/ticket/11051
-}


showBkptTable :: GHCi ()
showBkptTable :: GHCi ()
showBkptTable = do
  GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [(Int, BreakLocation)] -> MsgDoc
prettyLocations (GHCiState -> [(Int, BreakLocation)]
breaks GHCiState
st)

showContext :: GHCi ()
showContext :: GHCi ()
showContext = do
   [Resume]
resumes <- GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
   MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat ((Resume -> MsgDoc) -> [Resume] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map Resume -> MsgDoc
pp_resume ([Resume] -> [Resume]
forall a. [a] -> [a]
reverse [Resume]
resumes))
  where
   pp_resume :: Resume -> MsgDoc
pp_resume res :: Resume
res =
        PtrString -> MsgDoc
ptext (String -> PtrString
sLit "--> ") MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text (Resume -> String
GHC.resumeStmt Resume
res)
        MsgDoc -> MsgDoc -> MsgDoc
$$ Int -> MsgDoc -> MsgDoc
nest 2 (Resume -> MsgDoc
pprStopped Resume
res)

pprStopped :: GHC.Resume -> SDoc
pprStopped :: Resume -> MsgDoc
pprStopped res :: Resume
res =
  PtrString -> MsgDoc
ptext (String -> PtrString
sLit "Stopped in")
    MsgDoc -> MsgDoc -> MsgDoc
<+> ((case Maybe ModuleName
mb_mod_name of
           Nothing -> MsgDoc
empty
           Just mod_name :: ModuleName
mod_name -> String -> MsgDoc
text (ModuleName -> String
moduleNameString ModuleName
mod_name) MsgDoc -> MsgDoc -> MsgDoc
<> Char -> MsgDoc
char '.')
         MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text (Resume -> String
GHC.resumeDecl Resume
res))
    MsgDoc -> MsgDoc -> MsgDoc
<> Char -> MsgDoc
char ',' MsgDoc -> MsgDoc -> MsgDoc
<+> SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr (Resume -> SrcSpan
GHC.resumeSpan Resume
res)
 where
  mb_mod_name :: Maybe ModuleName
mb_mod_name = Module -> ModuleName
moduleName (Module -> ModuleName)
-> (BreakInfo -> Module) -> BreakInfo -> ModuleName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> BreakInfo -> Module
GHC.breakInfo_module (BreakInfo -> ModuleName) -> Maybe BreakInfo -> Maybe ModuleName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Resume -> Maybe BreakInfo
GHC.resumeBreakInfo Resume
res

showPackages :: GHCi ()
showPackages :: GHCi ()
showPackages = do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  let pkg_flags :: [PackageFlag]
pkg_flags = DynFlags -> [PackageFlag]
packageFlags DynFlags
dflags
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
    String -> MsgDoc
text ("active package flags:"String -> String -> String
forall a. [a] -> [a] -> [a]
++if [PackageFlag] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PackageFlag]
pkg_flags then " none" else "") MsgDoc -> MsgDoc -> MsgDoc
$$
      Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((PackageFlag -> MsgDoc) -> [PackageFlag] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map PackageFlag -> MsgDoc
pprFlag [PackageFlag]
pkg_flags))

showPaths :: GHCi ()
showPaths :: GHCi ()
showPaths = do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
    String
cwd <- IO String
getCurrentDirectory
    String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
      String -> MsgDoc
text "current working directory: " MsgDoc -> MsgDoc -> MsgDoc
$$
        Int -> MsgDoc -> MsgDoc
nest 2 (String -> MsgDoc
text String
cwd)
    let ipaths :: [String]
ipaths = DynFlags -> [String]
importPaths DynFlags
dflags
    String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$
      String -> MsgDoc
text ("module import search paths:"String -> String -> String
forall a. [a] -> [a] -> [a]
++if [String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
ipaths then " none" else "") MsgDoc -> MsgDoc -> MsgDoc
$$
        Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((String -> MsgDoc) -> [String] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map String -> MsgDoc
text [String]
ipaths))

showLanguages :: GHCi ()
showLanguages :: GHCi ()
showLanguages = GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> DynFlags -> IO ()
showLanguages' Bool
False

showiLanguages :: GHCi ()
showiLanguages :: GHCi ()
showiLanguages = GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getInteractiveDynFlags GHCi DynFlags -> (DynFlags -> GHCi ()) -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (DynFlags -> IO ()) -> DynFlags -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> DynFlags -> IO ()
showLanguages' Bool
False

showLanguages' :: Bool -> DynFlags -> IO ()
showLanguages' :: Bool -> DynFlags -> IO ()
showLanguages' show_all :: Bool
show_all dflags :: DynFlags
dflags =
  String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ DynFlags -> MsgDoc -> String
showSDoc DynFlags
dflags (MsgDoc -> String) -> MsgDoc -> String
forall a b. (a -> b) -> a -> b
$ [MsgDoc] -> MsgDoc
vcat
     [ String -> MsgDoc
text "base language is: " MsgDoc -> MsgDoc -> MsgDoc
<>
         case DynFlags -> Maybe Language
language DynFlags
dflags of
           Nothing          -> String -> MsgDoc
text "Haskell2010"
           Just Haskell98   -> String -> MsgDoc
text "Haskell98"
           Just Haskell2010 -> String -> MsgDoc
text "Haskell2010"
     , (if Bool
show_all then String -> MsgDoc
text "all active language options:"
                    else String -> MsgDoc
text "with the following modifiers:") MsgDoc -> MsgDoc -> MsgDoc
$$
          Int -> MsgDoc -> MsgDoc
nest 2 ([MsgDoc] -> MsgDoc
vcat ((FlagSpec Extension -> MsgDoc) -> [FlagSpec Extension] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map ((Extension -> DynFlags -> Bool) -> FlagSpec Extension -> MsgDoc
forall flag. (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting Extension -> DynFlags -> Bool
xopt) [FlagSpec Extension]
DynFlags.xFlags))
     ]
  where
   setting :: (flag -> DynFlags -> Bool) -> FlagSpec flag -> MsgDoc
setting test :: flag -> DynFlags -> Bool
test flag :: FlagSpec flag
flag
          | Bool
quiet     = MsgDoc
empty
          | Bool
is_on     = String -> MsgDoc
text "-X" MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text String
name
          | Bool
otherwise = String -> MsgDoc
text "-XNo" MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text String
name
          where name :: String
name = FlagSpec flag -> String
forall flag. FlagSpec flag -> String
flagSpecName FlagSpec flag
flag
                f :: flag
f = FlagSpec flag -> flag
forall flag. FlagSpec flag -> flag
flagSpecFlag FlagSpec flag
flag
                is_on :: Bool
is_on = flag -> DynFlags -> Bool
test flag
f DynFlags
dflags
                quiet :: Bool
quiet = Bool -> Bool
not Bool
show_all Bool -> Bool -> Bool
&& flag -> DynFlags -> Bool
test flag
f DynFlags
default_dflags Bool -> Bool -> Bool
forall a. Eq a => a -> a -> Bool
== Bool
is_on

   llvmConfig :: (LlvmTargets, LlvmPasses)
llvmConfig = (DynFlags -> LlvmTargets
llvmTargets DynFlags
dflags, DynFlags -> LlvmPasses
llvmPasses DynFlags
dflags)

   default_dflags :: DynFlags
default_dflags =
       Settings -> (LlvmTargets, LlvmPasses) -> DynFlags
defaultDynFlags (DynFlags -> Settings
settings DynFlags
dflags) (LlvmTargets, LlvmPasses)
llvmConfig DynFlags -> Maybe Language -> DynFlags
`lang_set`
         case DynFlags -> Maybe Language
language DynFlags
dflags of
           Nothing -> Language -> Maybe Language
forall a. a -> Maybe a
Just Language
Haskell2010
           other :: Maybe Language
other   -> Maybe Language
other

showTargets :: GHCi ()
showTargets :: GHCi ()
showTargets = (Target -> GHCi ()) -> [Target] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Target -> GHCi ()
showTarget ([Target] -> GHCi ()) -> GHCi [Target] -> GHCi ()
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< GHCi [Target]
forall (m :: * -> *). GhcMonad m => m [Target]
GHC.getTargets
  where
    showTarget :: Target -> GHCi ()
    showTarget :: Target -> GHCi ()
showTarget (Target (TargetFile f :: String
f _) _ _) = IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn String
f)
    showTarget (Target (TargetModule m :: ModuleName
m) _ _) =
      IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ ModuleName -> String
moduleNameString ModuleName
m)

-- -----------------------------------------------------------------------------
-- Completion

completeCmd :: String -> GHCi ()
completeCmd :: String -> GHCi ()
completeCmd argLine0 :: String
argLine0 = case String -> Maybe (String, (Maybe Int, Maybe Int), String)
parseLine String
argLine0 of
    Just ("repl", resultRange :: (Maybe Int, Maybe Int)
resultRange, left :: String
left) -> do
        (unusedLine :: String
unusedLine,compls :: [Completion]
compls) <- CompletionFunc GHCi
ghciCompleteWord (String -> String
forall a. [a] -> [a]
reverse String
left,"")
        let compls' :: [Completion]
compls' = (Maybe Int, Maybe Int) -> [Completion] -> [Completion]
forall a. (Maybe Int, Maybe Int) -> [a] -> [a]
takeRange (Maybe Int, Maybe Int)
resultRange [Completion]
compls
        IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> (String -> IO ()) -> String -> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO ()
putStrLn (String -> GHCi ()) -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [String] -> String
unwords [ Int -> String
forall a. Show a => a -> String
show ([Completion] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Completion]
compls'), Int -> String
forall a. Show a => a -> String
show ([Completion] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Completion]
compls), String -> String
forall a. Show a => a -> String
show (String -> String
forall a. [a] -> [a]
reverse String
unusedLine) ]
        [Completion] -> (Completion -> GHCi ()) -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
t a -> (a -> m b) -> m ()
forM_ ((Maybe Int, Maybe Int) -> [Completion] -> [Completion]
forall a. (Maybe Int, Maybe Int) -> [a] -> [a]
takeRange (Maybe Int, Maybe Int)
resultRange [Completion]
compls) ((Completion -> GHCi ()) -> GHCi ())
-> (Completion -> GHCi ()) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \(Completion r :: String
r _ _) -> do
            IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
forall a. Show a => a -> IO ()
print String
r
    _ -> GhcException -> GHCi ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
  where
    parseLine :: String -> Maybe (String, (Maybe Int, Maybe Int), String)
parseLine argLine :: String
argLine
        | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
argLine = Maybe (String, (Maybe Int, Maybe Int), String)
forall a. Maybe a
Nothing
        | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
rest1   = Maybe (String, (Maybe Int, Maybe Int), String)
forall a. Maybe a
Nothing
        | Bool
otherwise    = (,,) String
dom ((Maybe Int, Maybe Int)
 -> String -> (String, (Maybe Int, Maybe Int), String))
-> Maybe (Maybe Int, Maybe Int)
-> Maybe (String -> (String, (Maybe Int, Maybe Int), String))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (Maybe Int, Maybe Int)
resRange Maybe (String -> (String, (Maybe Int, Maybe Int), String))
-> Maybe String -> Maybe (String, (Maybe Int, Maybe Int), String)
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Maybe String
s
      where
        (dom :: String
dom, rest1 :: String
rest1) = String -> (String, String)
breakSpace String
argLine
        (rng :: String
rng, rest2 :: String
rest2) = String -> (String, String)
breakSpace String
rest1
        resRange :: Maybe (Maybe Int, Maybe Int)
resRange | String -> Char
forall a. [a] -> a
head String
rest1 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== '"' = String -> Maybe (Maybe Int, Maybe Int)
parseRange ""
                 | Bool
otherwise         = String -> Maybe (Maybe Int, Maybe Int)
parseRange String
rng
        s :: Maybe String
s | String -> Char
forall a. [a] -> a
head String
rest1 Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== '"' = String -> Maybe String
forall a. Read a => String -> Maybe a
readMaybe String
rest1 :: Maybe String
          | Bool
otherwise         = String -> Maybe String
forall a. Read a => String -> Maybe a
readMaybe String
rest2
        breakSpace :: String -> (String, String)
breakSpace = (String -> String) -> (String, String) -> (String, String)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace) ((String, String) -> (String, String))
-> (String -> (String, String)) -> String -> (String, String)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isSpace

    takeRange :: (Maybe Int, Maybe Int) -> [a] -> [a]
takeRange (lb :: Maybe Int
lb,ub :: Maybe Int
ub) = ([a] -> [a]) -> (Int -> [a] -> [a]) -> Maybe Int -> [a] -> [a]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [a] -> [a]
forall a. a -> a
id (Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
drop (Int -> [a] -> [a]) -> (Int -> Int) -> Int -> [a] -> [a]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Int
forall a. Enum a => a -> a
pred) Maybe Int
lb ([a] -> [a]) -> ([a] -> [a]) -> [a] -> [a]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([a] -> [a]) -> (Int -> [a] -> [a]) -> Maybe Int -> [a] -> [a]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [a] -> [a]
forall a. a -> a
id Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
take Maybe Int
ub

    -- syntax: [n-][m] with semantics "drop (n-1) . take m"
    parseRange :: String -> Maybe (Maybe Int,Maybe Int)
    parseRange :: String -> Maybe (Maybe Int, Maybe Int)
parseRange s :: String
s = case (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
span Char -> Bool
isDigit String
s of
                   (_, "") ->
                       -- upper limit only
                       (Maybe Int, Maybe Int) -> Maybe (Maybe Int, Maybe Int)
forall a. a -> Maybe a
Just (Maybe Int
forall a. Maybe a
Nothing, String -> Maybe Int
forall a. Read a => String -> Maybe a
bndRead String
s)
                   (s1 :: String
s1, '-' : s2 :: String
s2)
                    | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
s2 ->
                       (Maybe Int, Maybe Int) -> Maybe (Maybe Int, Maybe Int)
forall a. a -> Maybe a
Just (String -> Maybe Int
forall a. Read a => String -> Maybe a
bndRead String
s1, String -> Maybe Int
forall a. Read a => String -> Maybe a
bndRead String
s2)
                   _ ->
                       Maybe (Maybe Int, Maybe Int)
forall a. Maybe a
Nothing
      where
        bndRead :: String -> Maybe a
bndRead x :: String
x = if String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
x then Maybe a
forall a. Maybe a
Nothing else a -> Maybe a
forall a. a -> Maybe a
Just (String -> a
forall a. Read a => String -> a
read String
x)



completeGhciCommand, completeMacro, completeIdentifier, completeModule,
    completeSetModule, completeSeti, completeShowiOptions,
    completeHomeModule, completeSetOptions, completeShowOptions,
    completeHomeModuleOrFile, completeExpression
    :: CompletionFunc GHCi

-- | Provide completions for last word in a given string.
--
-- Takes a tuple of two strings.  First string is a reversed line to be
-- completed.  Second string is likely unused, 'completeCmd' always passes an
-- empty string as second item in tuple.
ghciCompleteWord :: CompletionFunc GHCi
ghciCompleteWord :: CompletionFunc GHCi
ghciCompleteWord line :: (String, String)
line@(left :: String
left,_) = case String
firstWord of
    -- If given string starts with `:` colon, and there is only one following
    -- word then provide REPL command completions.  If there is more than one
    -- word complete either filename or builtin ghci commands or macros.
    ':':cmd :: String
cmd     | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
rest     -> CompletionFunc GHCi
completeGhciCommand (String, String)
line
                | Bool
otherwise     -> do
                        CompletionFunc GHCi
completion <- String -> GHCi (CompletionFunc GHCi)
lookupCompletion String
cmd
                        CompletionFunc GHCi
completion (String, String)
line
    -- If given string starts with `import` keyword provide module name
    -- completions
    "import"    -> CompletionFunc GHCi
completeModule (String, String)
line
    -- otherwise provide identifier completions
    _           -> CompletionFunc GHCi
completeExpression (String, String)
line
  where
    (firstWord :: String
firstWord,rest :: String
rest) = (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break Char -> Bool
isSpace (String -> (String, String)) -> String -> (String, String)
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace (String -> String) -> String -> String
forall a b. (a -> b) -> a -> b
$ String -> String
forall a. [a] -> [a]
reverse String
left
    lookupCompletion :: String -> GHCi (CompletionFunc GHCi)
lookupCompletion ('!':_) = CompletionFunc GHCi -> GHCi (CompletionFunc GHCi)
forall (m :: * -> *) a. Monad m => a -> m a
return CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename
    lookupCompletion c :: String
c = do
        Maybe Command
maybe_cmd <- String -> GHCi (Maybe Command)
lookupCommand' String
c
        case Maybe Command
maybe_cmd of
            Just cmd :: Command
cmd -> CompletionFunc GHCi -> GHCi (CompletionFunc GHCi)
forall (m :: * -> *) a. Monad m => a -> m a
return (Command -> CompletionFunc GHCi
cmdCompletionFunc Command
cmd)
            Nothing  -> CompletionFunc GHCi -> GHCi (CompletionFunc GHCi)
forall (m :: * -> *) a. Monad m => a -> m a
return CompletionFunc GHCi
forall (m :: * -> *). MonadIO m => CompletionFunc m
completeFilename

completeGhciCommand :: CompletionFunc GHCi
completeGhciCommand = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter " " ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [Command]
macros <- GHCiState -> [Command]
ghci_macros (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  [Command]
cmds   <- GHCiState -> [Command]
ghci_commands (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
`fmap` GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  let macro_names :: [String]
macro_names = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (':'Char -> String -> String
forall a. a -> [a] -> [a]
:) ([String] -> [String])
-> ([Command] -> [String]) -> [Command] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Command -> String) -> [Command] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Command -> String
cmdName ([Command] -> [String]) -> [Command] -> [String]
forall a b. (a -> b) -> a -> b
$ [Command]
macros
  let command_names :: [String]
command_names = (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (':'Char -> String -> String
forall a. a -> [a] -> [a]
:) ([String] -> [String])
-> ([Command] -> [String]) -> [Command] -> [String]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Command -> String) -> [Command] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Command -> String
cmdName ([Command] -> [String]) -> [Command] -> [String]
forall a b. (a -> b) -> a -> b
$ (Command -> Bool) -> [Command] -> [Command]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Command -> Bool) -> Command -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Command -> Bool
cmdHidden) [Command]
cmds
  let{ candidates :: [String]
candidates = case String
w of
      ':' : ':' : _ -> (String -> String) -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (':'Char -> String -> String
forall a. a -> [a] -> [a]
:) [String]
command_names
      _ -> [String] -> [String]
forall a. Eq a => [a] -> [a]
nub ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ [String]
macro_names [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
command_names }
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> GHCi [String]) -> [String] -> GHCi [String]
forall a b. (a -> b) -> a -> b
$ (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
candidates

completeMacro :: CompletionFunc GHCi
completeMacro = (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [Command]
cmds <- GHCiState -> [Command]
ghci_macros (GHCiState -> [Command]) -> GHCi GHCiState -> GHCi [Command]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) ((Command -> String) -> [Command] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Command -> String
cmdName [Command]
cmds))

completeIdentifier :: CompletionFunc GHCi
completeIdentifier line :: (String, String)
line@(left :: String
left, _) =
  -- Note: `left` is a reversed input
  case String
left of
    (x :: Char
x:_) | Char -> Bool
isSymbolChar Char
x -> String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter (String
specials String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
spaces) String -> GHCi [String]
forall (m :: * -> *). GhcMonad m => String -> m [String]
complete (String, String)
line
    _                      -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter String -> GHCi [String]
forall (m :: * -> *). GhcMonad m => String -> m [String]
complete (String, String)
line
  where
    complete :: String -> m [String]
complete w :: String
w = do
      [RdrName]
rdrs <- m [RdrName]
forall (m :: * -> *). GhcMonad m => m [RdrName]
GHC.getRdrNamesInScope
      DynFlags
dflags <- m DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getSessionDynFlags
      [String] -> m [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) ((RdrName -> String) -> [RdrName] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> RdrName -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) [RdrName]
rdrs))

completeModule :: CompletionFunc GHCi
completeModule = (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getSessionDynFlags
  let pkg_mods :: [ModuleName]
pkg_mods = DynFlags -> [ModuleName]
allVisibleModules DynFlags
dflags
  [ModuleName]
loaded_mods <- ([ModSummary] -> [ModuleName])
-> GHCi [ModSummary] -> GHCi [ModuleName]
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((ModSummary -> ModuleName) -> [ModSummary] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map ModSummary -> ModuleName
GHC.ms_mod_name) GHCi [ModSummary]
forall (m :: * -> *). GhcMonad m => m [ModSummary]
getLoadedModules
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> GHCi [String]) -> [String] -> GHCi [String]
forall a b. (a -> b) -> a -> b
$ (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`)
        ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (ModuleName -> String) -> [ModuleName] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> ModuleName -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) ([ModuleName] -> [String]) -> [ModuleName] -> [String]
forall a b. (a -> b) -> a -> b
$ [ModuleName]
loaded_mods [ModuleName] -> [ModuleName] -> [ModuleName]
forall a. [a] -> [a] -> [a]
++ [ModuleName]
pkg_mods

completeSetModule :: CompletionFunc GHCi
completeSetModule = String
-> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier "+-" ((Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi)
-> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \m :: Maybe Char
m w :: String
w -> do
  DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). GhcMonad m => m DynFlags
GHC.getSessionDynFlags
  [ModuleName]
modules <- case Maybe Char
m of
    Just '-' -> do
      [InteractiveImport]
imports <- GHCi [InteractiveImport]
forall (m :: * -> *). GhcMonad m => m [InteractiveImport]
GHC.getContext
      [ModuleName] -> GHCi [ModuleName]
forall (m :: * -> *) a. Monad m => a -> m a
return ([ModuleName] -> GHCi [ModuleName])
-> [ModuleName] -> GHCi [ModuleName]
forall a b. (a -> b) -> a -> b
$ (InteractiveImport -> ModuleName)
-> [InteractiveImport] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map InteractiveImport -> ModuleName
iiModuleName [InteractiveImport]
imports
    _ -> do
      let pkg_mods :: [ModuleName]
pkg_mods = DynFlags -> [ModuleName]
allVisibleModules DynFlags
dflags
      [ModuleName]
loaded_mods <- ([ModSummary] -> [ModuleName])
-> GHCi [ModSummary] -> GHCi [ModuleName]
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM ((ModSummary -> ModuleName) -> [ModSummary] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map ModSummary -> ModuleName
GHC.ms_mod_name) GHCi [ModSummary]
forall (m :: * -> *). GhcMonad m => m [ModSummary]
getLoadedModules
      [ModuleName] -> GHCi [ModuleName]
forall (m :: * -> *) a. Monad m => a -> m a
return ([ModuleName] -> GHCi [ModuleName])
-> [ModuleName] -> GHCi [ModuleName]
forall a b. (a -> b) -> a -> b
$ [ModuleName]
loaded_mods [ModuleName] -> [ModuleName] -> [ModuleName]
forall a. [a] -> [a] -> [a]
++ [ModuleName]
pkg_mods
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> GHCi [String]) -> [String] -> GHCi [String]
forall a b. (a -> b) -> a -> b
$ (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (ModuleName -> String) -> [ModuleName] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> ModuleName -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) [ModuleName]
modules

completeHomeModule :: CompletionFunc GHCi
completeHomeModule = (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter String -> GHCi [String]
listHomeModules

listHomeModules :: String -> GHCi [String]
listHomeModules :: String -> GHCi [String]
listHomeModules w :: String
w = do
    ModuleGraph
g <- GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
    let home_mods :: [ModuleName]
home_mods = (ModSummary -> ModuleName) -> [ModSummary] -> [ModuleName]
forall a b. (a -> b) -> [a] -> [b]
map ModSummary -> ModuleName
GHC.ms_mod_name (ModuleGraph -> [ModSummary]
GHC.mgModSummaries ModuleGraph
g)
    DynFlags
dflags <- GHCi DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
    [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ([String] -> GHCi [String]) -> [String] -> GHCi [String]
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. Ord a => [a] -> [a]
sort ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`)
            ([String] -> [String]) -> [String] -> [String]
forall a b. (a -> b) -> a -> b
$ (ModuleName -> String) -> [ModuleName] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (DynFlags -> ModuleName -> String
forall a. Outputable a => DynFlags -> a -> String
showPpr DynFlags
dflags) [ModuleName]
home_mods

completeSetOptions :: CompletionFunc GHCi
completeSetOptions = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter String
flagWordBreakChars ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
opts)
    where opts :: [String]
opts = "args"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"prog"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"prompt"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"prompt-cont"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"prompt-function"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:
                 "prompt-cont-function"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"editor"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:"stop"String -> [String] -> [String]
forall a. a -> [a] -> [a]
:[String]
flagList
          flagList :: [String]
flagList = ([String] -> String) -> [[String]] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map [String] -> String
forall a. [a] -> a
head ([[String]] -> [String]) -> [[String]] -> [String]
forall a b. (a -> b) -> a -> b
$ [String] -> [[String]]
forall a. Eq a => [a] -> [[a]]
group ([String] -> [[String]]) -> [String] -> [[String]]
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. Ord a => [a] -> [a]
sort [String]
allNonDeprecatedFlags

completeSeti :: CompletionFunc GHCi
completeSeti = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter String
flagWordBreakChars ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
flagList)
    where flagList :: [String]
flagList = ([String] -> String) -> [[String]] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map [String] -> String
forall a. [a] -> a
head ([[String]] -> [String]) -> [[String]] -> [String]
forall a b. (a -> b) -> a -> b
$ [String] -> [[String]]
forall a. Eq a => [a] -> [[a]]
group ([String] -> [[String]]) -> [String] -> [[String]]
forall a b. (a -> b) -> a -> b
$ [String] -> [String]
forall a. Ord a => [a] -> [a]
sort [String]
allNonDeprecatedFlags

completeShowOptions :: CompletionFunc GHCi
completeShowOptions = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter String
flagWordBreakChars ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) [String]
opts)
    where opts :: [String]
opts = ["args", "prog", "editor", "stop",
                     "modules", "bindings", "linker", "breaks",
                     "context", "packages", "paths", "language", "imports"]

completeShowiOptions :: CompletionFunc GHCi
completeShowiOptions = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter String
flagWordBreakChars ((String -> GHCi [String]) -> CompletionFunc GHCi)
-> (String -> GHCi [String]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \w :: String
w -> do
  [String] -> GHCi [String]
forall (m :: * -> *) a. Monad m => a -> m a
return ((String -> Bool) -> [String] -> [String]
forall a. (a -> Bool) -> [a] -> [a]
filter (String
w String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf`) ["language"])

completeHomeModuleOrFile :: CompletionFunc GHCi
completeHomeModuleOrFile = Maybe Char
-> String -> (String -> GHCi [Completion]) -> CompletionFunc GHCi
forall (m :: * -> *).
Monad m =>
Maybe Char
-> String -> (String -> m [Completion]) -> CompletionFunc m
completeWord Maybe Char
forall a. Maybe a
Nothing String
filenameWordBreakChars
                ((String -> GHCi [Completion]) -> CompletionFunc GHCi)
-> (String -> GHCi [Completion]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ (String -> GHCi [Completion])
-> (String -> GHCi [Completion]) -> String -> GHCi [Completion]
forall (m :: * -> *) a b.
Monad m =>
(a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete (([String] -> [Completion]) -> GHCi [String] -> GHCi [Completion]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> Completion) -> [String] -> [Completion]
forall a b. (a -> b) -> [a] -> [b]
map String -> Completion
simpleCompletion) (GHCi [String] -> GHCi [Completion])
-> (String -> GHCi [String]) -> String -> GHCi [Completion]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> GHCi [String]
listHomeModules)
                            String -> GHCi [Completion]
forall (m :: * -> *). MonadIO m => String -> m [Completion]
listFiles

unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete :: (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
unionComplete f1 :: a -> m [b]
f1 f2 :: a -> m [b]
f2 line :: a
line = do
  [b]
cs1 <- a -> m [b]
f1 a
line
  [b]
cs2 <- a -> m [b]
f2 a
line
  [b] -> m [b]
forall (m :: * -> *) a. Monad m => a -> m a
return ([b]
cs1 [b] -> [b] -> [b]
forall a. [a] -> [a] -> [a]
++ [b]
cs2)

wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter breakChars :: String
breakChars fun :: String -> GHCi [String]
fun = Maybe Char
-> String -> (String -> GHCi [Completion]) -> CompletionFunc GHCi
forall (m :: * -> *).
Monad m =>
Maybe Char
-> String -> (String -> m [Completion]) -> CompletionFunc m
completeWord Maybe Char
forall a. Maybe a
Nothing String
breakChars
    ((String -> GHCi [Completion]) -> CompletionFunc GHCi)
-> (String -> GHCi [Completion]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ ([String] -> [Completion]) -> GHCi [String] -> GHCi [Completion]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> Completion) -> [String] -> [Completion]
forall a b. (a -> b) -> [a] -> [b]
map String -> Completion
simpleCompletion ([String] -> [Completion])
-> ([String] -> [String]) -> [String] -> [Completion]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
forall a. Ord a => [a] -> [a]
nubSort) (GHCi [String] -> GHCi [Completion])
-> (String -> GHCi [String]) -> String -> GHCi [Completion]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> GHCi [String]
fun

wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleter = String -> (String -> GHCi [String]) -> CompletionFunc GHCi
wrapCompleter String
word_break_chars

wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier :: String
-> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
wrapIdentCompleterWithModifier modifChars :: String
modifChars fun :: Maybe Char -> String -> GHCi [String]
fun = Maybe Char
-> String
-> (String -> String -> GHCi [Completion])
-> CompletionFunc GHCi
forall (m :: * -> *).
Monad m =>
Maybe Char
-> String
-> (String -> String -> m [Completion])
-> CompletionFunc m
completeWordWithPrev Maybe Char
forall a. Maybe a
Nothing String
word_break_chars
    ((String -> String -> GHCi [Completion]) -> CompletionFunc GHCi)
-> (String -> String -> GHCi [Completion]) -> CompletionFunc GHCi
forall a b. (a -> b) -> a -> b
$ \rest :: String
rest -> ([String] -> [Completion]) -> GHCi [String] -> GHCi [Completion]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ((String -> Completion) -> [String] -> [Completion]
forall a b. (a -> b) -> [a] -> [b]
map String -> Completion
simpleCompletion ([String] -> [Completion])
-> ([String] -> [String]) -> [String] -> [Completion]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
forall a. Ord a => [a] -> [a]
nubSort) (GHCi [String] -> GHCi [Completion])
-> (String -> GHCi [String]) -> String -> GHCi [Completion]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe Char -> String -> GHCi [String]
fun (String -> Maybe Char
getModifier String
rest)
 where
  getModifier :: String -> Maybe Char
getModifier = (Char -> Bool) -> String -> Maybe Char
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Maybe a
find (Char -> String -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` String
modifChars)

-- | Return a list of visible module names for autocompletion.
-- (NB: exposed != visible)
allVisibleModules :: DynFlags -> [ModuleName]
allVisibleModules :: DynFlags -> [ModuleName]
allVisibleModules dflags :: DynFlags
dflags = DynFlags -> [ModuleName]
listVisibleModuleNames DynFlags
dflags

completeExpression :: CompletionFunc GHCi
completeExpression = Maybe Char
-> String
-> (String -> GHCi [Completion])
-> CompletionFunc GHCi
-> CompletionFunc GHCi
forall (m :: * -> *).
Monad m =>
Maybe Char
-> String
-> (String -> m [Completion])
-> CompletionFunc m
-> CompletionFunc m
completeQuotedWord (Char -> Maybe Char
forall a. a -> Maybe a
Just '\\') "\"" String -> GHCi [Completion]
forall (m :: * -> *). MonadIO m => String -> m [Completion]
listFiles
                        CompletionFunc GHCi
completeIdentifier


-- -----------------------------------------------------------------------------
-- commands for debugger

sprintCmd, printCmd, forceCmd :: String -> GHCi ()
sprintCmd :: String -> GHCi ()
sprintCmd = Bool -> Bool -> String -> GHCi ()
pprintCommand Bool
False Bool
False
printCmd :: String -> GHCi ()
printCmd  = Bool -> Bool -> String -> GHCi ()
pprintCommand Bool
True Bool
False
forceCmd :: String -> GHCi ()
forceCmd  = Bool -> Bool -> String -> GHCi ()
pprintCommand Bool
False Bool
True

pprintCommand :: Bool -> Bool -> String -> GHCi ()
pprintCommand :: Bool -> Bool -> String -> GHCi ()
pprintCommand bind :: Bool
bind force :: Bool
force str :: String
str = do
  Bool -> Bool -> String -> GHCi ()
forall (m :: * -> *). GhcMonad m => Bool -> Bool -> String -> m ()
pprintClosureCommand Bool
bind Bool
force String
str

stepCmd :: String -> GHCi ()
stepCmd :: String -> GHCi ()
stepCmd arg :: String
arg = String -> GHCi () -> GHCi ()
withSandboxOnly ":step" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi ()
step String
arg
  where
  step :: String -> GHCi ()
step []         = (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue (Bool -> SrcSpan -> Bool
forall a b. a -> b -> a
const Bool
True) SingleStep
GHC.SingleStep
  step expression :: String
expression = String -> SingleStep -> GHCi (Maybe ExecResult)
runStmt String
expression SingleStep
GHC.SingleStep GHCi (Maybe ExecResult) -> GHCi () -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

stepLocalCmd :: String -> GHCi ()
stepLocalCmd :: String -> GHCi ()
stepLocalCmd arg :: String
arg = String -> GHCi () -> GHCi ()
withSandboxOnly ":steplocal" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi ()
step String
arg
  where
  step :: String -> GHCi ()
step expr :: String
expr
   | Bool -> Bool
not (String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
expr) = String -> GHCi ()
stepCmd String
expr
   | Bool
otherwise = do
      Maybe SrcSpan
mb_span <- GHCi (Maybe SrcSpan)
getCurrentBreakSpan
      case Maybe SrcSpan
mb_span of
        Nothing  -> String -> GHCi ()
stepCmd []
        Just loc :: SrcSpan
loc -> do
           Module
md <- Module -> Maybe Module -> Module
forall a. a -> Maybe a -> a
fromMaybe (String -> Module
forall a. String -> a
panic "stepLocalCmd") (Maybe Module -> Module) -> GHCi (Maybe Module) -> GHCi Module
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> GHCi (Maybe Module)
getCurrentBreakModule
           RealSrcSpan
current_toplevel_decl <- Module -> SrcSpan -> GHCi RealSrcSpan
enclosingTickSpan Module
md SrcSpan
loc
           (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue (SrcSpan -> SrcSpan -> Bool
`isSubspanOf` RealSrcSpan -> SrcSpan
RealSrcSpan RealSrcSpan
current_toplevel_decl) SingleStep
GHC.SingleStep

stepModuleCmd :: String -> GHCi ()
stepModuleCmd :: String -> GHCi ()
stepModuleCmd arg :: String
arg = String -> GHCi () -> GHCi ()
withSandboxOnly ":stepmodule" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi ()
step String
arg
  where
  step :: String -> GHCi ()
step expr :: String
expr
   | Bool -> Bool
not (String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
expr) = String -> GHCi ()
stepCmd String
expr
   | Bool
otherwise = do
      Maybe SrcSpan
mb_span <- GHCi (Maybe SrcSpan)
getCurrentBreakSpan
      case Maybe SrcSpan
mb_span of
        Nothing  -> String -> GHCi ()
stepCmd []
        Just pan :: SrcSpan
pan -> do
           let f :: SrcSpan -> Bool
f some_span :: SrcSpan
some_span = SrcSpan -> Maybe FastString
srcSpanFileName_maybe SrcSpan
pan Maybe FastString -> Maybe FastString -> Bool
forall a. Eq a => a -> a -> Bool
== SrcSpan -> Maybe FastString
srcSpanFileName_maybe SrcSpan
some_span
           (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue SrcSpan -> Bool
f SingleStep
GHC.SingleStep

-- | Returns the span of the largest tick containing the srcspan given
enclosingTickSpan :: Module -> SrcSpan -> GHCi RealSrcSpan
enclosingTickSpan :: Module -> SrcSpan -> GHCi RealSrcSpan
enclosingTickSpan _ (UnhelpfulSpan _) = String -> GHCi RealSrcSpan
forall a. String -> a
panic "enclosingTickSpan UnhelpfulSpan"
enclosingTickSpan md :: Module
md (RealSrcSpan src :: RealSrcSpan
src) = do
  TickArray
ticks <- Module -> GHCi TickArray
getTickArray Module
md
  let line :: Int
line = RealSrcSpan -> Int
srcSpanStartLine RealSrcSpan
src
  ASSERT(inRange (bounds ticks) line) do
  let enclosing_spans = [ pan | (_,pan) <- ticks ! line
                               , realSrcSpanEnd pan >= realSrcSpanEnd src]
  return . head . sortBy leftmostLargestRealSrcSpan $ enclosing_spans
 where

leftmostLargestRealSrcSpan :: RealSrcSpan -> RealSrcSpan -> Ordering
leftmostLargestRealSrcSpan :: RealSrcSpan -> RealSrcSpan -> Ordering
leftmostLargestRealSrcSpan a :: RealSrcSpan
a b :: RealSrcSpan
b =
  (RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
a RealSrcLoc -> RealSrcLoc -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
b)
     Ordering -> Ordering -> Ordering
`thenCmp`
  (RealSrcSpan -> RealSrcLoc
realSrcSpanEnd RealSrcSpan
b RealSrcLoc -> RealSrcLoc -> Ordering
forall a. Ord a => a -> a -> Ordering
`compare` RealSrcSpan -> RealSrcLoc
realSrcSpanEnd RealSrcSpan
a)

traceCmd :: String -> GHCi ()
traceCmd :: String -> GHCi ()
traceCmd arg :: String
arg
  = String -> GHCi () -> GHCi ()
withSandboxOnly ":trace" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi ()
tr String
arg
  where
  tr :: String -> GHCi ()
tr []         = (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue (Bool -> SrcSpan -> Bool
forall a b. a -> b -> a
const Bool
True) SingleStep
GHC.RunAndLogSteps
  tr expression :: String
expression = String -> SingleStep -> GHCi (Maybe ExecResult)
runStmt String
expression SingleStep
GHC.RunAndLogSteps GHCi (Maybe ExecResult) -> GHCi () -> GHCi ()
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

continueCmd :: String -> GHCi ()
continueCmd :: String -> GHCi ()
continueCmd = GHCi () -> String -> GHCi ()
noArgs (GHCi () -> String -> GHCi ()) -> GHCi () -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi () -> GHCi ()
withSandboxOnly ":continue" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue (Bool -> SrcSpan -> Bool
forall a b. a -> b -> a
const Bool
True) SingleStep
GHC.RunToCompletion

-- doContinue :: SingleStep -> GHCi ()
doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
doContinue pre :: SrcSpan -> Bool
pre step :: SingleStep
step = do
  ExecResult
runResult <- (SrcSpan -> Bool) -> SingleStep -> GHCi ExecResult
resume SrcSpan -> Bool
pre SingleStep
step
  ExecResult
_ <- (SrcSpan -> Bool) -> ExecResult -> GHCi ExecResult
afterRunStmt SrcSpan -> Bool
pre ExecResult
runResult
  () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

abandonCmd :: String -> GHCi ()
abandonCmd :: String -> GHCi ()
abandonCmd = GHCi () -> String -> GHCi ()
noArgs (GHCi () -> String -> GHCi ()) -> GHCi () -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> GHCi () -> GHCi ()
withSandboxOnly ":abandon" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
  Bool
b <- GHCi Bool
forall (m :: * -> *). GhcMonad m => m Bool
GHC.abandon -- the prompt will change to indicate the new context
  Bool -> GHCi () -> GHCi ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
b) (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "There is no computation running."

deleteCmd :: String -> GHCi ()
deleteCmd :: String -> GHCi ()
deleteCmd argLine :: String
argLine = String -> GHCi () -> GHCi ()
withSandboxOnly ":delete" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
   [String] -> GHCi ()
deleteSwitch ([String] -> GHCi ()) -> [String] -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> [String]
words String
argLine
   where
   deleteSwitch :: [String] -> GHCi ()
   deleteSwitch :: [String] -> GHCi ()
deleteSwitch [] =
      IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "The delete command requires at least one argument."
   -- delete all break points
   deleteSwitch ("*":_rest :: [String]
_rest) = GHCi ()
discardActiveBreakPoints
   deleteSwitch idents :: [String]
idents = do
      (String -> GHCi ()) -> [String] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ String -> GHCi ()
deleteOneBreak [String]
idents
      where
      deleteOneBreak :: String -> GHCi ()
      deleteOneBreak :: String -> GHCi ()
deleteOneBreak str :: String
str
         | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
str = Int -> GHCi ()
deleteBreak (String -> Int
forall a. Read a => String -> a
read String
str)
         | Bool
otherwise = () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()

historyCmd :: String -> GHCi ()
historyCmd :: String -> GHCi ()
historyCmd arg :: String
arg
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
arg        = Int -> GHCi ()
forall (m :: * -> *). GhcMonad m => Int -> m ()
history 20
  | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg = Int -> GHCi ()
forall (m :: * -> *). GhcMonad m => Int -> m ()
history (String -> Int
forall a. Read a => String -> a
read String
arg)
  | Bool
otherwise       = IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Syntax:  :history [num]"
  where
  history :: Int -> m ()
history num :: Int
num = do
    [Resume]
resumes <- m [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
    case [Resume]
resumes of
      [] -> IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Not stopped at a breakpoint"
      (r :: Resume
r:_) -> do
        let hist :: [History]
hist = Resume -> [History]
GHC.resumeHistory Resume
r
            (took :: [History]
took,rest :: [History]
rest) = Int -> [History] -> ([History], [History])
forall a. Int -> [a] -> ([a], [a])
splitAt Int
num [History]
hist
        case [History]
hist of
          [] -> IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$
                   "Empty history. Perhaps you forgot to use :trace?"
          _  -> do
                 [SrcSpan]
pans <- (History -> m SrcSpan) -> [History] -> m [SrcSpan]
forall (t :: * -> *) (m :: * -> *) a b.
(Traversable t, Monad m) =>
(a -> m b) -> t a -> m (t b)
mapM History -> m SrcSpan
forall (m :: * -> *). GhcMonad m => History -> m SrcSpan
GHC.getHistorySpan [History]
took
                 let nums :: [String]
nums  = (Int -> String) -> [Int] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String -> Int -> String
forall r. PrintfType r => String -> r
printf "-%-3d:") [(1::Int)..]
                     names :: [[String]]
names = (History -> [String]) -> [History] -> [[String]]
forall a b. (a -> b) -> [a] -> [b]
map History -> [String]
GHC.historyEnclosingDecls [History]
took
                 MsgDoc -> m ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser ([MsgDoc] -> MsgDoc
vcat((MsgDoc -> MsgDoc -> MsgDoc -> MsgDoc)
-> [MsgDoc] -> [MsgDoc] -> [MsgDoc] -> [MsgDoc]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3
                                 (\x :: MsgDoc
x y :: MsgDoc
y z :: MsgDoc
z -> MsgDoc
x MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
y MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
z)
                                 ((String -> MsgDoc) -> [String] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map String -> MsgDoc
text [String]
nums)
                                 (([String] -> MsgDoc) -> [[String]] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (MsgDoc -> MsgDoc
bold (MsgDoc -> MsgDoc) -> ([String] -> MsgDoc) -> [String] -> MsgDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [MsgDoc] -> MsgDoc
hcat ([MsgDoc] -> MsgDoc)
-> ([String] -> [MsgDoc]) -> [String] -> MsgDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. MsgDoc -> [MsgDoc] -> [MsgDoc]
punctuate MsgDoc
colon ([MsgDoc] -> [MsgDoc])
-> ([String] -> [MsgDoc]) -> [String] -> [MsgDoc]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> MsgDoc) -> [String] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map String -> MsgDoc
text) [[String]]
names)
                                 ((SrcSpan -> MsgDoc) -> [SrcSpan] -> [MsgDoc]
forall a b. (a -> b) -> [a] -> [b]
map (MsgDoc -> MsgDoc
parens (MsgDoc -> MsgDoc) -> (SrcSpan -> MsgDoc) -> SrcSpan -> MsgDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr) [SrcSpan]
pans)))
                 IO () -> m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> m ()) -> IO () -> m ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ if [History] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [History]
rest then "<end of history>" else "..."

bold :: SDoc -> SDoc
bold :: MsgDoc -> MsgDoc
bold c :: MsgDoc
c | Bool
do_bold   = String -> MsgDoc
text String
start_bold MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
c MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text String
end_bold
       | Bool
otherwise = MsgDoc
c

backCmd :: String -> GHCi ()
backCmd :: String -> GHCi ()
backCmd arg :: String
arg
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
arg        = Int -> GHCi ()
back 1
  | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg = Int -> GHCi ()
back (String -> Int
forall a. Read a => String -> a
read String
arg)
  | Bool
otherwise       = IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Syntax:  :back [num]"
  where
  back :: Int -> GHCi ()
back num :: Int
num = String -> GHCi () -> GHCi ()
withSandboxOnly ":back" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
      (names :: [Name]
names, _, pan :: SrcSpan
pan, _) <- Int -> GHCi ([Name], Int, SrcSpan, String)
forall (m :: * -> *).
GhcMonad m =>
Int -> m ([Name], Int, SrcSpan, String)
GHC.back Int
num
      MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ PtrString -> MsgDoc
ptext (String -> PtrString
sLit "Logged breakpoint at") MsgDoc -> MsgDoc -> MsgDoc
<+> SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcSpan
pan
      [Name] -> GHCi ()
printTypeOfNames [Name]
names
       -- run the command set with ":set stop <cmd>"
      GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      [String] -> GHCi ()
enqueueCommands [GHCiState -> String
stop GHCiState
st]

forwardCmd :: String -> GHCi ()
forwardCmd :: String -> GHCi ()
forwardCmd arg :: String
arg
  | String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
arg        = Int -> GHCi ()
forward 1
  | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg = Int -> GHCi ()
forward (String -> Int
forall a. Read a => String -> a
read String
arg)
  | Bool
otherwise       = IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "Syntax:  :back [num]"
  where
  forward :: Int -> GHCi ()
forward num :: Int
num = String -> GHCi () -> GHCi ()
withSandboxOnly ":forward" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
      (names :: [Name]
names, ix :: Int
ix, pan :: SrcSpan
pan, _) <- Int -> GHCi ([Name], Int, SrcSpan, String)
forall (m :: * -> *).
GhcMonad m =>
Int -> m ([Name], Int, SrcSpan, String)
GHC.forward Int
num
      MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$ (if (Int
ix Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 0)
                        then PtrString -> MsgDoc
ptext (String -> PtrString
sLit "Stopped at")
                        else PtrString -> MsgDoc
ptext (String -> PtrString
sLit "Logged breakpoint at")) MsgDoc -> MsgDoc -> MsgDoc
<+> SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcSpan
pan
      [Name] -> GHCi ()
printTypeOfNames [Name]
names
       -- run the command set with ":set stop <cmd>"
      GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
      [String] -> GHCi ()
enqueueCommands [GHCiState -> String
stop GHCiState
st]

-- handle the "break" command
breakCmd :: String -> GHCi ()
breakCmd :: String -> GHCi ()
breakCmd argLine :: String
argLine = String -> GHCi () -> GHCi ()
withSandboxOnly ":break" (GHCi () -> GHCi ()) -> GHCi () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ [String] -> GHCi ()
breakSwitch ([String] -> GHCi ()) -> [String] -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> [String]
words String
argLine

breakSwitch :: [String] -> GHCi ()
breakSwitch :: [String] -> GHCi ()
breakSwitch [] = do
   IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "The break command requires at least one argument."
breakSwitch (arg1 :: String
arg1:rest :: [String]
rest)
   | String -> Bool
looksLikeModuleName String
arg1 Bool -> Bool -> Bool
&& Bool -> Bool
not ([String] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [String]
rest) = do
        Module
md <- String -> GHCi Module
forall (m :: * -> *). GhcMonad m => String -> m Module
wantInterpretedModule String
arg1
        Module -> [String] -> GHCi ()
breakByModule Module
md [String]
rest
   | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg1 = do
        [InteractiveImport]
imports <- GHCi [InteractiveImport]
forall (m :: * -> *). GhcMonad m => m [InteractiveImport]
GHC.getContext
        case [InteractiveImport] -> [ModuleName]
iiModules [InteractiveImport]
imports of
           (mn :: ModuleName
mn : _) -> do
              Module
md <- ModuleName -> GHCi Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
lookupModuleName ModuleName
mn
              Module -> Int -> [String] -> GHCi ()
breakByModuleLine Module
md (String -> Int
forall a. Read a => String -> a
read String
arg1) [String]
rest
           [] -> do
              IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "No modules are loaded with debugging support."
   | Bool
otherwise = do -- try parsing it as an identifier
        (Name -> MsgDoc -> GHCi ())
-> String -> (Name -> GHCi ()) -> GHCi ()
forall (m :: * -> *).
GhcMonad m =>
(Name -> MsgDoc -> m ()) -> String -> (Name -> m ()) -> m ()
wantNameFromInterpretedModule Name -> MsgDoc -> GHCi ()
forall (m :: * -> *) a.
(GhcMonad m, Outputable a) =>
a -> MsgDoc -> m ()
noCanDo String
arg1 ((Name -> GHCi ()) -> GHCi ()) -> (Name -> GHCi ()) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ \name :: Name
name -> do
        Maybe ModuleInfo
maybe_info <- Module -> GHCi (Maybe ModuleInfo)
forall (m :: * -> *). GhcMonad m => Module -> m (Maybe ModuleInfo)
GHC.getModuleInfo (HasDebugCallStack => Name -> Module
Name -> Module
GHC.nameModule Name
name)
        case Maybe ModuleInfo
maybe_info of
          Nothing -> Name -> MsgDoc -> GHCi ()
forall (m :: * -> *) a.
(GhcMonad m, Outputable a) =>
a -> MsgDoc -> m ()
noCanDo Name
name (PtrString -> MsgDoc
ptext (String -> PtrString
sLit "cannot get module info"))
          Just minf :: ModuleInfo
minf ->
               ASSERT( isExternalName name )
                    Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet (HasDebugCallStack => Name -> Module
Name -> Module
GHC.nameModule Name
name) ((TickArray -> [(Int, RealSrcSpan)]) -> GHCi ())
-> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
forall a b. (a -> b) -> a -> b
$
                       Name -> ModBreaks -> TickArray -> [(Int, RealSrcSpan)]
findBreakForBind Name
name (ModuleInfo -> ModBreaks
GHC.modInfoModBreaks ModuleInfo
minf)
       where
          noCanDo :: a -> MsgDoc -> m ()
noCanDo n :: a
n why :: MsgDoc
why = MsgDoc -> m ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> m ()) -> MsgDoc -> m ()
forall a b. (a -> b) -> a -> b
$
                String -> MsgDoc
text "cannot set breakpoint on " MsgDoc -> MsgDoc -> MsgDoc
<> a -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr a
n MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text ": " MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
why

breakByModule :: Module -> [String] -> GHCi ()
breakByModule :: Module -> [String] -> GHCi ()
breakByModule md :: Module
md (arg1 :: String
arg1:rest :: [String]
rest)
   | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg1 = do  -- looks like a line number
        Module -> Int -> [String] -> GHCi ()
breakByModuleLine Module
md (String -> Int
forall a. Read a => String -> a
read String
arg1) [String]
rest
breakByModule _ _
   = GHCi ()
forall a. a
breakSyntax

breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
breakByModuleLine md :: Module
md line :: Int
line args :: [String]
args
   | [] <- [String]
args = Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet Module
md ((TickArray -> [(Int, RealSrcSpan)]) -> GHCi ())
-> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Maybe (Int, RealSrcSpan) -> [(Int, RealSrcSpan)]
forall a. Maybe a -> [a]
maybeToList (Maybe (Int, RealSrcSpan) -> [(Int, RealSrcSpan)])
-> (TickArray -> Maybe (Int, RealSrcSpan))
-> TickArray
-> [(Int, RealSrcSpan)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> TickArray -> Maybe (Int, RealSrcSpan)
findBreakByLine Int
line
   | [col :: String
col] <- [String]
args, (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
col =
        Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet Module
md ((TickArray -> [(Int, RealSrcSpan)]) -> GHCi ())
-> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
forall a b. (a -> b) -> a -> b
$ Maybe (Int, RealSrcSpan) -> [(Int, RealSrcSpan)]
forall a. Maybe a -> [a]
maybeToList (Maybe (Int, RealSrcSpan) -> [(Int, RealSrcSpan)])
-> (TickArray -> Maybe (Int, RealSrcSpan))
-> TickArray
-> [(Int, RealSrcSpan)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe FastString
-> (Int, Int) -> TickArray -> Maybe (Int, RealSrcSpan)
findBreakByCoord Maybe FastString
forall a. Maybe a
Nothing (Int
line, String -> Int
forall a. Read a => String -> a
read String
col)
   | Bool
otherwise = GHCi ()
forall a. a
breakSyntax

breakSyntax :: a
breakSyntax :: a
breakSyntax = GhcException -> a
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError "Syntax: :break [<mod>] <line> [<column>]")

findBreakAndSet :: Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet :: Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
findBreakAndSet md :: Module
md lookupTickTree :: TickArray -> [(Int, RealSrcSpan)]
lookupTickTree = do
   TickArray
tickArray <- Module -> GHCi TickArray
getTickArray Module
md
   (breakArray :: ForeignRef BreakArray
breakArray, _) <- Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak Module
md
   case TickArray -> [(Int, RealSrcSpan)]
lookupTickTree TickArray
tickArray of
      []  -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn (String -> IO ()) -> String -> IO ()
forall a b. (a -> b) -> a -> b
$ "No breakpoints found at that location."
      some :: [(Int, RealSrcSpan)]
some -> ((Int, RealSrcSpan) -> GHCi ()) -> [(Int, RealSrcSpan)] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (ForeignRef BreakArray -> (Int, RealSrcSpan) -> GHCi ()
breakAt ForeignRef BreakArray
breakArray) [(Int, RealSrcSpan)]
some
 where
   breakAt :: ForeignRef BreakArray -> (Int, RealSrcSpan) -> GHCi ()
breakAt breakArray :: ForeignRef BreakArray
breakArray (tick :: Int
tick, pan :: RealSrcSpan
pan) = do
         Bool -> ForeignRef BreakArray -> Int -> GHCi ()
setBreakFlag Bool
True ForeignRef BreakArray
breakArray Int
tick
         (alreadySet :: Bool
alreadySet, nm :: Int
nm) <-
               BreakLocation -> GHCi (Bool, Int)
recordBreak (BreakLocation -> GHCi (Bool, Int))
-> BreakLocation -> GHCi (Bool, Int)
forall a b. (a -> b) -> a -> b
$ $WBreakLocation :: Module -> SrcSpan -> Int -> String -> BreakLocation
BreakLocation
                       { breakModule :: Module
breakModule = Module
md
                       , breakLoc :: SrcSpan
breakLoc = RealSrcSpan -> SrcSpan
RealSrcSpan RealSrcSpan
pan
                       , breakTick :: Int
breakTick = Int
tick
                       , onBreakCmd :: String
onBreakCmd = ""
                       }
         MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> GHCi ()) -> MsgDoc -> GHCi ()
forall a b. (a -> b) -> a -> b
$
            String -> MsgDoc
text "Breakpoint " MsgDoc -> MsgDoc -> MsgDoc
<> Int -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Int
nm MsgDoc -> MsgDoc -> MsgDoc
<>
            if Bool
alreadySet
               then String -> MsgDoc
text " was already set at " MsgDoc -> MsgDoc -> MsgDoc
<> RealSrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr RealSrcSpan
pan
               else String -> MsgDoc
text " activated at " MsgDoc -> MsgDoc -> MsgDoc
<> RealSrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr RealSrcSpan
pan

-- When a line number is specified, the current policy for choosing
-- the best breakpoint is this:
--    - the leftmost complete subexpression on the specified line, or
--    - the leftmost subexpression starting on the specified line, or
--    - the rightmost subexpression enclosing the specified line
--
findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,RealSrcSpan)
findBreakByLine :: Int -> TickArray -> Maybe (Int, RealSrcSpan)
findBreakByLine line :: Int
line arr :: TickArray
arr
  | Bool -> Bool
not ((Int, Int) -> Int -> Bool
forall a. Ix a => (a, a) -> a -> Bool
inRange (TickArray -> (Int, Int)
forall i e. Array i e -> (i, i)
bounds TickArray
arr) Int
line) = Maybe (Int, RealSrcSpan)
forall a. Maybe a
Nothing
  | Bool
otherwise =
    [(Int, RealSrcSpan)] -> Maybe (Int, RealSrcSpan)
forall a. [a] -> Maybe a
listToMaybe (((Int, RealSrcSpan) -> (Int, RealSrcSpan) -> Ordering)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (RealSrcSpan -> RealSrcSpan -> Ordering
leftmostLargestRealSrcSpan (RealSrcSpan -> RealSrcSpan -> Ordering)
-> ((Int, RealSrcSpan) -> RealSrcSpan)
-> (Int, RealSrcSpan)
-> (Int, RealSrcSpan)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Int, RealSrcSpan) -> RealSrcSpan
forall a b. (a, b) -> b
snd)  [(Int, RealSrcSpan)]
comp)   Maybe (Int, RealSrcSpan)
-> Maybe (Int, RealSrcSpan) -> Maybe (Int, RealSrcSpan)
forall (m :: * -> *) a. MonadPlus m => m a -> m a -> m a
`mplus`
    [(Int, RealSrcSpan)] -> Maybe (Int, RealSrcSpan)
forall a. [a] -> Maybe a
listToMaybe (((Int, RealSrcSpan) -> (Int, RealSrcSpan) -> Ordering)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (RealSrcSpan -> RealSrcSpan -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (RealSrcSpan -> RealSrcSpan -> Ordering)
-> ((Int, RealSrcSpan) -> RealSrcSpan)
-> (Int, RealSrcSpan)
-> (Int, RealSrcSpan)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Int, RealSrcSpan) -> RealSrcSpan
forall a b. (a, b) -> b
snd) [(Int, RealSrcSpan)]
incomp) Maybe (Int, RealSrcSpan)
-> Maybe (Int, RealSrcSpan) -> Maybe (Int, RealSrcSpan)
forall (m :: * -> *) a. MonadPlus m => m a -> m a -> m a
`mplus`
    [(Int, RealSrcSpan)] -> Maybe (Int, RealSrcSpan)
forall a. [a] -> Maybe a
listToMaybe (((Int, RealSrcSpan) -> (Int, RealSrcSpan) -> Ordering)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((RealSrcSpan -> RealSrcSpan -> Ordering)
-> RealSrcSpan -> RealSrcSpan -> Ordering
forall a b c. (a -> b -> c) -> b -> a -> c
flip RealSrcSpan -> RealSrcSpan -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (RealSrcSpan -> RealSrcSpan -> Ordering)
-> ((Int, RealSrcSpan) -> RealSrcSpan)
-> (Int, RealSrcSpan)
-> (Int, RealSrcSpan)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Int, RealSrcSpan) -> RealSrcSpan
forall a b. (a, b) -> b
snd) [(Int, RealSrcSpan)]
ticks)
  where
        ticks :: [(Int, RealSrcSpan)]
ticks = TickArray
arr TickArray -> Int -> [(Int, RealSrcSpan)]
forall i e. Ix i => Array i e -> i -> e
! Int
line

        starts_here :: [(Int, RealSrcSpan)]
starts_here = [ (Int
ix,RealSrcSpan
pan) | (ix :: Int
ix, pan :: RealSrcSpan
pan) <- [(Int, RealSrcSpan)]
ticks,
                        RealSrcSpan -> Int
GHC.srcSpanStartLine RealSrcSpan
pan Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line ]

        (comp :: [(Int, RealSrcSpan)]
comp, incomp :: [(Int, RealSrcSpan)]
incomp) = ((Int, RealSrcSpan) -> Bool)
-> [(Int, RealSrcSpan)]
-> ([(Int, RealSrcSpan)], [(Int, RealSrcSpan)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (Int, RealSrcSpan) -> Bool
forall a. (a, RealSrcSpan) -> Bool
ends_here [(Int, RealSrcSpan)]
starts_here
            where ends_here :: (a, RealSrcSpan) -> Bool
ends_here (_,pan :: RealSrcSpan
pan) = RealSrcSpan -> Int
GHC.srcSpanEndLine RealSrcSpan
pan Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line

-- The aim is to find the breakpoints for all the RHSs of the
-- equations corresponding to a binding.  So we find all breakpoints
-- for
--   (a) this binder only (not a nested declaration)
--   (b) that do not have an enclosing breakpoint
findBreakForBind :: Name -> GHC.ModBreaks -> TickArray
                 -> [(BreakIndex,RealSrcSpan)]
findBreakForBind :: Name -> ModBreaks -> TickArray -> [(Int, RealSrcSpan)]
findBreakForBind name :: Name
name modbreaks :: ModBreaks
modbreaks _ = ((Int, RealSrcSpan) -> Bool)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool)
-> ((Int, RealSrcSpan) -> Bool) -> (Int, RealSrcSpan) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Int, RealSrcSpan) -> Bool
forall a. (a, RealSrcSpan) -> Bool
enclosed) [(Int, RealSrcSpan)]
ticks
  where
    ticks :: [(Int, RealSrcSpan)]
ticks = [ (Int
index, RealSrcSpan
span)
            | (index :: Int
index, [n :: String
n]) <- Array Int [String] -> [(Int, [String])]
forall i e. Ix i => Array i e -> [(i, e)]
assocs (ModBreaks -> Array Int [String]
GHC.modBreaks_decls ModBreaks
modbreaks),
              String
n String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== OccName -> String
occNameString (Name -> OccName
nameOccName Name
name),
              RealSrcSpan span :: RealSrcSpan
span <- [ModBreaks -> Array Int SrcSpan
GHC.modBreaks_locs ModBreaks
modbreaks Array Int SrcSpan -> Int -> SrcSpan
forall i e. Ix i => Array i e -> i -> e
! Int
index] ]
    enclosed :: (a, RealSrcSpan) -> Bool
enclosed (_,sp0 :: RealSrcSpan
sp0) = ((Int, RealSrcSpan) -> Bool) -> [(Int, RealSrcSpan)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Int, RealSrcSpan) -> Bool
forall a. (a, RealSrcSpan) -> Bool
subspan [(Int, RealSrcSpan)]
ticks
      where subspan :: (a, RealSrcSpan) -> Bool
subspan (_,sp :: RealSrcSpan
sp) = RealSrcSpan
sp RealSrcSpan -> RealSrcSpan -> Bool
forall a. Eq a => a -> a -> Bool
/= RealSrcSpan
sp0 Bool -> Bool -> Bool
&&
                         RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
sp RealSrcLoc -> RealSrcLoc -> Bool
forall a. Ord a => a -> a -> Bool
<= RealSrcSpan -> RealSrcLoc
realSrcSpanStart RealSrcSpan
sp0 Bool -> Bool -> Bool
&&
                         RealSrcSpan -> RealSrcLoc
realSrcSpanEnd RealSrcSpan
sp0 RealSrcLoc -> RealSrcLoc -> Bool
forall a. Ord a => a -> a -> Bool
<= RealSrcSpan -> RealSrcLoc
realSrcSpanEnd RealSrcSpan
sp

findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
                 -> Maybe (BreakIndex,RealSrcSpan)
findBreakByCoord :: Maybe FastString
-> (Int, Int) -> TickArray -> Maybe (Int, RealSrcSpan)
findBreakByCoord mb_file :: Maybe FastString
mb_file (line :: Int
line, col :: Int
col) arr :: TickArray
arr
  | Bool -> Bool
not ((Int, Int) -> Int -> Bool
forall a. Ix a => (a, a) -> a -> Bool
inRange (TickArray -> (Int, Int)
forall i e. Array i e -> (i, i)
bounds TickArray
arr) Int
line) = Maybe (Int, RealSrcSpan)
forall a. Maybe a
Nothing
  | Bool
otherwise =
    [(Int, RealSrcSpan)] -> Maybe (Int, RealSrcSpan)
forall a. [a] -> Maybe a
listToMaybe (((Int, RealSrcSpan) -> (Int, RealSrcSpan) -> Ordering)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy ((RealSrcSpan -> RealSrcSpan -> Ordering)
-> RealSrcSpan -> RealSrcSpan -> Ordering
forall a b c. (a -> b -> c) -> b -> a -> c
flip RealSrcSpan -> RealSrcSpan -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (RealSrcSpan -> RealSrcSpan -> Ordering)
-> ((Int, RealSrcSpan) -> RealSrcSpan)
-> (Int, RealSrcSpan)
-> (Int, RealSrcSpan)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Int, RealSrcSpan) -> RealSrcSpan
forall a b. (a, b) -> b
snd) [(Int, RealSrcSpan)]
contains [(Int, RealSrcSpan)]
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. [a] -> [a] -> [a]
++
                 ((Int, RealSrcSpan) -> (Int, RealSrcSpan) -> Ordering)
-> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)]
forall a. (a -> a -> Ordering) -> [a] -> [a]
sortBy (RealSrcSpan -> RealSrcSpan -> Ordering
forall a. Ord a => a -> a -> Ordering
compare (RealSrcSpan -> RealSrcSpan -> Ordering)
-> ((Int, RealSrcSpan) -> RealSrcSpan)
-> (Int, RealSrcSpan)
-> (Int, RealSrcSpan)
-> Ordering
forall b c a. (b -> b -> c) -> (a -> b) -> a -> a -> c
`on` (Int, RealSrcSpan) -> RealSrcSpan
forall a b. (a, b) -> b
snd) [(Int, RealSrcSpan)]
after_here)
  where
        ticks :: [(Int, RealSrcSpan)]
ticks = TickArray
arr TickArray -> Int -> [(Int, RealSrcSpan)]
forall i e. Ix i => Array i e -> i -> e
! Int
line

        -- the ticks that span this coordinate
        contains :: [(Int, RealSrcSpan)]
contains = [ (Int, RealSrcSpan)
tick | tick :: (Int, RealSrcSpan)
tick@(_,pan :: RealSrcSpan
pan) <- [(Int, RealSrcSpan)]
ticks, RealSrcSpan -> SrcSpan
RealSrcSpan RealSrcSpan
pan SrcSpan -> (Int, Int) -> Bool
`spans` (Int
line,Int
col),
                            RealSrcSpan -> Bool
is_correct_file RealSrcSpan
pan ]

        is_correct_file :: RealSrcSpan -> Bool
is_correct_file pan :: RealSrcSpan
pan
                 | Just f :: FastString
f <- Maybe FastString
mb_file = RealSrcSpan -> FastString
GHC.srcSpanFile RealSrcSpan
pan FastString -> FastString -> Bool
forall a. Eq a => a -> a -> Bool
== FastString
f
                 | Bool
otherwise         = Bool
True

        after_here :: [(Int, RealSrcSpan)]
after_here = [ (Int, RealSrcSpan)
tick | tick :: (Int, RealSrcSpan)
tick@(_,pan :: RealSrcSpan
pan) <- [(Int, RealSrcSpan)]
ticks,
                              RealSrcSpan -> Int
GHC.srcSpanStartLine RealSrcSpan
pan Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line,
                              RealSrcSpan -> Int
GHC.srcSpanStartCol RealSrcSpan
pan Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
col ]

-- For now, use ANSI bold on terminals that we know support it.
-- Otherwise, we add a line of carets under the active expression instead.
-- In particular, on Windows and when running the testsuite (which sets
-- TERM to vt100 for other reasons) we get carets.
-- We really ought to use a proper termcap/terminfo library.
do_bold :: Bool
do_bold :: Bool
do_bold = (String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` IO String -> String
forall a. IO a -> a
unsafePerformIO IO String
mTerm) (String -> Bool) -> [String] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
`any` ["xterm", "linux"]
    where mTerm :: IO String
mTerm = String -> IO String
System.Environment.getEnv "TERM"
                  IO String -> (IOException -> IO String) -> IO String
forall a. IO a -> (IOException -> IO a) -> IO a
`catchIO` \_ -> String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return "TERM not set"

start_bold :: String
start_bold :: String
start_bold = "\ESC[1m"
end_bold :: String
end_bold :: String
end_bold   = "\ESC[0m"

-----------------------------------------------------------------------------
-- :where

whereCmd :: String -> GHCi ()
whereCmd :: String -> GHCi ()
whereCmd = GHCi () -> String -> GHCi ()
noArgs (GHCi () -> String -> GHCi ()) -> GHCi () -> String -> GHCi ()
forall a b. (a -> b) -> a -> b
$ do
  Maybe [String]
mstrs <- GHCi (Maybe [String])
getCallStackAtCurrentBreakpoint
  case Maybe [String]
mstrs of
    Nothing -> () -> GHCi ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    Just strs :: [String]
strs -> IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn ([String] -> String
renderStack [String]
strs)

-----------------------------------------------------------------------------
-- :list

listCmd :: String -> InputT GHCi ()
listCmd :: String -> InputT GHCi ()
listCmd c :: String
c = String -> InputT GHCi ()
listCmd' String
c

listCmd' :: String -> InputT GHCi ()
listCmd' :: String -> InputT GHCi ()
listCmd' "" = do
   Maybe SrcSpan
mb_span <- GHCi (Maybe SrcSpan) -> InputT GHCi (Maybe SrcSpan)
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift GHCi (Maybe SrcSpan)
getCurrentBreakSpan
   case Maybe SrcSpan
mb_span of
      Nothing ->
          MsgDoc -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> InputT GHCi ()) -> MsgDoc -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text "Not stopped at a breakpoint; nothing to list"
      Just (RealSrcSpan pan :: RealSrcSpan
pan) ->
          RealSrcSpan -> Bool -> InputT GHCi ()
forall (m :: * -> *).
MonadIO m =>
RealSrcSpan -> Bool -> InputT m ()
listAround RealSrcSpan
pan Bool
True
      Just pan :: SrcSpan
pan@(UnhelpfulSpan _) ->
          do [Resume]
resumes <- InputT GHCi [Resume]
forall (m :: * -> *). GhcMonad m => m [Resume]
GHC.getResumeContext
             case [Resume]
resumes of
                 [] -> String -> InputT GHCi ()
forall a. String -> a
panic "No resumes"
                 (r :: Resume
r:_) ->
                     do let traceIt :: MsgDoc
traceIt = case Resume -> [History]
GHC.resumeHistory Resume
r of
                                      [] -> String -> MsgDoc
text "rerunning with :trace,"
                                      _ -> MsgDoc
empty
                            doWhat :: MsgDoc
doWhat = MsgDoc
traceIt MsgDoc -> MsgDoc -> MsgDoc
<+> String -> MsgDoc
text ":back then :list"
                        MsgDoc -> InputT GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (String -> MsgDoc
text "Unable to list source for" MsgDoc -> MsgDoc -> MsgDoc
<+>
                                      SrcSpan -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcSpan
pan
                                   MsgDoc -> MsgDoc -> MsgDoc
$$ String -> MsgDoc
text "Try" MsgDoc -> MsgDoc -> MsgDoc
<+> MsgDoc
doWhat)
listCmd' str :: String
str = [String] -> InputT GHCi ()
list2 (String -> [String]
words String
str)

list2 :: [String] -> InputT GHCi ()
list2 :: [String] -> InputT GHCi ()
list2 [arg :: String
arg] | (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg = do
    [InteractiveImport]
imports <- InputT GHCi [InteractiveImport]
forall (m :: * -> *). GhcMonad m => m [InteractiveImport]
GHC.getContext
    case [InteractiveImport] -> [ModuleName]
iiModules [InteractiveImport]
imports of
        [] -> IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "No module to list"
        (mn :: ModuleName
mn : _) -> do
          Module
md <- GHCi Module -> InputT GHCi Module
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi Module -> InputT GHCi Module)
-> GHCi Module -> InputT GHCi Module
forall a b. (a -> b) -> a -> b
$ ModuleName -> GHCi Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
lookupModuleName ModuleName
mn
          Module -> Int -> InputT GHCi ()
listModuleLine Module
md (String -> Int
forall a. Read a => String -> a
read String
arg)
list2 [arg1 :: String
arg1,arg2 :: String
arg2] | String -> Bool
looksLikeModuleName String
arg1, (Char -> Bool) -> String -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Char -> Bool
isDigit String
arg2 = do
        Module
md <- String -> InputT GHCi Module
forall (m :: * -> *). GhcMonad m => String -> m Module
wantInterpretedModule String
arg1
        Module -> Int -> InputT GHCi ()
listModuleLine Module
md (String -> Int
forall a. Read a => String -> a
read String
arg2)
list2 [arg :: String
arg] = do
        (Name -> MsgDoc -> InputT GHCi ())
-> String -> (Name -> InputT GHCi ()) -> InputT GHCi ()
forall (m :: * -> *).
GhcMonad m =>
(Name -> MsgDoc -> m ()) -> String -> (Name -> m ()) -> m ()
wantNameFromInterpretedModule Name -> MsgDoc -> InputT GHCi ()
forall (m :: * -> *) a.
(GhcMonad m, Outputable a) =>
a -> MsgDoc -> m ()
noCanDo String
arg ((Name -> InputT GHCi ()) -> InputT GHCi ())
-> (Name -> InputT GHCi ()) -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ \name :: Name
name -> do
        let loc :: SrcLoc
loc = SrcSpan -> SrcLoc
GHC.srcSpanStart (Name -> SrcSpan
GHC.nameSrcSpan Name
name)
        case SrcLoc
loc of
            RealSrcLoc l :: RealSrcLoc
l ->
               do TickArray
tickArray <- ASSERT( isExternalName name )
                               GHCi TickArray -> InputT GHCi TickArray
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift (GHCi TickArray -> InputT GHCi TickArray)
-> GHCi TickArray -> InputT GHCi TickArray
forall a b. (a -> b) -> a -> b
$ Module -> GHCi TickArray
getTickArray (HasDebugCallStack => Name -> Module
Name -> Module
GHC.nameModule Name
name)
                  let mb_span :: Maybe (Int, RealSrcSpan)
mb_span = Maybe FastString
-> (Int, Int) -> TickArray -> Maybe (Int, RealSrcSpan)
findBreakByCoord (FastString -> Maybe FastString
forall a. a -> Maybe a
Just (RealSrcLoc -> FastString
GHC.srcLocFile RealSrcLoc
l))
                                        (RealSrcLoc -> Int
GHC.srcLocLine RealSrcLoc
l, RealSrcLoc -> Int
GHC.srcLocCol RealSrcLoc
l)
                                        TickArray
tickArray
                  case Maybe (Int, RealSrcSpan)
mb_span of
                    Nothing       -> RealSrcSpan -> Bool -> InputT GHCi ()
forall (m :: * -> *).
MonadIO m =>
RealSrcSpan -> Bool -> InputT m ()
listAround (RealSrcLoc -> RealSrcSpan
realSrcLocSpan RealSrcLoc
l) Bool
False
                    Just (_, pan :: RealSrcSpan
pan) -> RealSrcSpan -> Bool -> InputT GHCi ()
forall (m :: * -> *).
MonadIO m =>
RealSrcSpan -> Bool -> InputT m ()
listAround RealSrcSpan
pan Bool
False
            UnhelpfulLoc _ ->
                  Name -> MsgDoc -> InputT GHCi ()
forall (m :: * -> *) a.
(GhcMonad m, Outputable a) =>
a -> MsgDoc -> m ()
noCanDo Name
name (MsgDoc -> InputT GHCi ()) -> MsgDoc -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text "can't find its location: " MsgDoc -> MsgDoc -> MsgDoc
<>
                                 SrcLoc -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr SrcLoc
loc
    where
        noCanDo :: a -> MsgDoc -> m ()
noCanDo n :: a
n why :: MsgDoc
why = MsgDoc -> m ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (MsgDoc -> m ()) -> MsgDoc -> m ()
forall a b. (a -> b) -> a -> b
$
            String -> MsgDoc
text "cannot list source code for " MsgDoc -> MsgDoc -> MsgDoc
<> a -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr a
n MsgDoc -> MsgDoc -> MsgDoc
<> String -> MsgDoc
text ": " MsgDoc -> MsgDoc -> MsgDoc
<> MsgDoc
why
list2  _other :: [String]
_other =
        IO () -> InputT GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT GHCi ()) -> IO () -> InputT GHCi ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn "syntax:  :list [<line> | <module> <line> | <identifier>]"

listModuleLine :: Module -> Int -> InputT GHCi ()
listModuleLine :: Module -> Int -> InputT GHCi ()
listModuleLine modl :: Module
modl line :: Int
line = do
   ModuleGraph
graph <- InputT GHCi ModuleGraph
forall (m :: * -> *). GhcMonad m => m ModuleGraph
GHC.getModuleGraph
   let this :: Maybe ModSummary
this = ModuleGraph -> Module -> Maybe ModSummary
GHC.mgLookupModule ModuleGraph
graph Module
modl
   case Maybe ModSummary
this of
     Nothing -> String -> InputT GHCi ()
forall a. String -> a
panic "listModuleLine"
     Just summ :: ModSummary
summ -> do
           let filename :: String
filename = String -> Maybe String -> String
forall a. HasCallStack => String -> Maybe a -> a
expectJust "listModuleLine" (ModLocation -> Maybe String
ml_hs_file (ModSummary -> ModLocation
GHC.ms_location ModSummary
summ))
               loc :: RealSrcLoc
loc = FastString -> Int -> Int -> RealSrcLoc
mkRealSrcLoc (String -> FastString
mkFastString (String
filename)) Int
line 0
           RealSrcSpan -> Bool -> InputT GHCi ()
forall (m :: * -> *).
MonadIO m =>
RealSrcSpan -> Bool -> InputT m ()
listAround (RealSrcLoc -> RealSrcSpan
realSrcLocSpan RealSrcLoc
loc) Bool
False

-- | list a section of a source file around a particular SrcSpan.
-- If the highlight flag is True, also highlight the span using
-- start_bold\/end_bold.

-- GHC files are UTF-8, so we can implement this by:
-- 1) read the file in as a BS and syntax highlight it as before
-- 2) convert the BS to String using utf-string, and write it out.
-- It would be better if we could convert directly between UTF-8 and the
-- console encoding, of course.
listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
listAround :: RealSrcSpan -> Bool -> InputT m ()
listAround pan :: RealSrcSpan
pan do_highlight :: Bool
do_highlight = do
      ByteString
contents <- IO ByteString -> InputT m ByteString
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO ByteString -> InputT m ByteString)
-> IO ByteString -> InputT m ByteString
forall a b. (a -> b) -> a -> b
$ String -> IO ByteString
BS.readFile (FastString -> String
unpackFS FastString
file)
      -- Drop carriage returns to avoid duplicates, see #9367.
      let ls :: [ByteString]
ls  = Char -> ByteString -> [ByteString]
BS.split '\n' (ByteString -> [ByteString]) -> ByteString -> [ByteString]
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> ByteString -> ByteString
BS.filter (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= '\r') ByteString
contents
          ls' :: [ByteString]
ls' = Int -> [ByteString] -> [ByteString]
forall a. Int -> [a] -> [a]
take (Int
line2 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
line1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ 1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
pad_before Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
pad_after) ([ByteString] -> [ByteString]) -> [ByteString] -> [ByteString]
forall a b. (a -> b) -> a -> b
$
                        Int -> [ByteString] -> [ByteString]
forall a. Int -> [a] -> [a]
drop (Int
line1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- 1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
pad_before) ([ByteString] -> [ByteString]) -> [ByteString] -> [ByteString]
forall a b. (a -> b) -> a -> b
$ [ByteString]
ls
          fst_line :: Int
fst_line = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max 1 (Int
line1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
pad_before)
          line_nos :: [Int]
line_nos = [ Int
fst_line .. ]

          highlighted :: [ByteString -> ByteString]
highlighted | Bool
do_highlight = (Int -> ByteString -> ByteString -> ByteString)
-> [Int] -> [ByteString] -> [ByteString -> ByteString]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> ByteString -> ByteString -> ByteString
highlight [Int]
line_nos [ByteString]
ls'
                      | Bool
otherwise    = [\p :: ByteString
p -> [ByteString] -> ByteString
BS.concat[ByteString
p,ByteString
l] | ByteString
l <- [ByteString]
ls']

          bs_line_nos :: [ByteString]
bs_line_nos = [ String -> ByteString
BS.pack (Int -> String
forall a. Show a => a -> String
show Int
l String -> String -> String
forall a. [a] -> [a] -> [a]
++ "  ") | Int
l <- [Int]
line_nos ]
          prefixed :: [ByteString]
prefixed = ((ByteString -> ByteString) -> ByteString -> ByteString)
-> [ByteString -> ByteString] -> [ByteString] -> [ByteString]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith (ByteString -> ByteString) -> ByteString -> ByteString
forall a b. (a -> b) -> a -> b
($) [ByteString -> ByteString]
highlighted [ByteString]
bs_line_nos
          output :: ByteString
output   = ByteString -> [ByteString] -> ByteString
BS.intercalate (String -> ByteString
BS.pack "\n") [ByteString]
prefixed

      let utf8Decoded :: String
utf8Decoded = ByteString -> String
utf8DecodeByteString ByteString
output
      IO () -> InputT m ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> InputT m ()) -> IO () -> InputT m ()
forall a b. (a -> b) -> a -> b
$ String -> IO ()
putStrLn String
utf8Decoded
  where
        file :: FastString
file  = RealSrcSpan -> FastString
GHC.srcSpanFile RealSrcSpan
pan
        line1 :: Int
line1 = RealSrcSpan -> Int
GHC.srcSpanStartLine RealSrcSpan
pan
        col1 :: Int
col1  = RealSrcSpan -> Int
GHC.srcSpanStartCol RealSrcSpan
pan Int -> Int -> Int
forall a. Num a => a -> a -> a
- 1
        line2 :: Int
line2 = RealSrcSpan -> Int
GHC.srcSpanEndLine RealSrcSpan
pan
        col2 :: Int
col2  = RealSrcSpan -> Int
GHC.srcSpanEndCol RealSrcSpan
pan Int -> Int -> Int
forall a. Num a => a -> a -> a
- 1

        pad_before :: Int
pad_before | Int
line1 Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== 1 = 0
                   | Bool
otherwise  = 1
        pad_after :: Int
pad_after = 1

        highlight :: Int -> ByteString -> ByteString -> ByteString
highlight | Bool
do_bold   = Int -> ByteString -> ByteString -> ByteString
highlight_bold
                  | Bool
otherwise = Int -> ByteString -> ByteString -> ByteString
highlight_carets

        highlight_bold :: Int -> ByteString -> ByteString -> ByteString
highlight_bold no :: Int
no line :: ByteString
line prefix :: ByteString
prefix
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line1 Bool -> Bool -> Bool
&& Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line2
          = let (a :: ByteString
a,r :: ByteString
r) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
col1 ByteString
line
                (b :: ByteString
b,c :: ByteString
c) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt (Int
col2Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
col1) ByteString
r
            in
            [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
a,String -> ByteString
BS.pack String
start_bold,ByteString
b,String -> ByteString
BS.pack String
end_bold,ByteString
c]
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line1
          = let (a :: ByteString
a,b :: ByteString
b) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
col1 ByteString
line in
            [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
a, String -> ByteString
BS.pack String
start_bold, ByteString
b]
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line2
          = let (a :: ByteString
a,b :: ByteString
b) = Int -> ByteString -> (ByteString, ByteString)
BS.splitAt Int
col2 ByteString
line in
            [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
a, String -> ByteString
BS.pack String
end_bold, ByteString
b]
          | Bool
otherwise   = [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
line]

        highlight_carets :: Int -> ByteString -> ByteString -> ByteString
highlight_carets no :: Int
no line :: ByteString
line prefix :: ByteString
prefix
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line1 Bool -> Bool -> Bool
&& Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line2
          = [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
line, ByteString
nl, ByteString
indent, Int -> Char -> ByteString
BS.replicate Int
col1 ' ',
                                         Int -> Char -> ByteString
BS.replicate (Int
col2Int -> Int -> Int
forall a. Num a => a -> a -> a
-Int
col1) '^']
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line1
          = [ByteString] -> ByteString
BS.concat [ByteString
indent, Int -> Char -> ByteString
BS.replicate (Int
col1 Int -> Int -> Int
forall a. Num a => a -> a -> a
- 2) ' ', String -> ByteString
BS.pack "vv", ByteString
nl,
                                         ByteString
prefix, ByteString
line]
          | Int
no Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
line2
          = [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
line, ByteString
nl, ByteString
indent, Int -> Char -> ByteString
BS.replicate Int
col2 ' ',
                                         String -> ByteString
BS.pack "^^"]
          | Bool
otherwise   = [ByteString] -> ByteString
BS.concat [ByteString
prefix, ByteString
line]
         where
           indent :: ByteString
indent = String -> ByteString
BS.pack ("  " String -> String -> String
forall a. [a] -> [a] -> [a]
++ Int -> Char -> String
forall a. Int -> a -> [a]
replicate (String -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (Int -> String
forall a. Show a => a -> String
show Int
no)) ' ')
           nl :: ByteString
nl = Char -> ByteString
BS.singleton '\n'


-- --------------------------------------------------------------------------
-- Tick arrays

getTickArray :: Module -> GHCi TickArray
getTickArray :: Module -> GHCi TickArray
getTickArray modl :: Module
modl = do
   GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
   let arrmap :: ModuleEnv TickArray
arrmap = GHCiState -> ModuleEnv TickArray
tickarrays GHCiState
st
   case ModuleEnv TickArray -> Module -> Maybe TickArray
forall a. ModuleEnv a -> Module -> Maybe a
lookupModuleEnv ModuleEnv TickArray
arrmap Module
modl of
      Just arr :: TickArray
arr -> TickArray -> GHCi TickArray
forall (m :: * -> *) a. Monad m => a -> m a
return TickArray
arr
      Nothing  -> do
        (_breakArray :: ForeignRef BreakArray
_breakArray, ticks :: Array Int SrcSpan
ticks) <- Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak Module
modl
        let arr :: TickArray
arr = [(Int, SrcSpan)] -> TickArray
mkTickArray (Array Int SrcSpan -> [(Int, SrcSpan)]
forall i e. Ix i => Array i e -> [(i, e)]
assocs Array Int SrcSpan
ticks)
        GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState GHCiState
st{tickarrays :: ModuleEnv TickArray
tickarrays = ModuleEnv TickArray -> Module -> TickArray -> ModuleEnv TickArray
forall a. ModuleEnv a -> Module -> a -> ModuleEnv a
extendModuleEnv ModuleEnv TickArray
arrmap Module
modl TickArray
arr}
        TickArray -> GHCi TickArray
forall (m :: * -> *) a. Monad m => a -> m a
return TickArray
arr

discardTickArrays :: GHCi ()
discardTickArrays :: GHCi ()
discardTickArrays = (GHCiState -> GHCiState) -> GHCi ()
forall (m :: * -> *).
HasGhciState m =>
(GHCiState -> GHCiState) -> m ()
modifyGHCiState (\st :: GHCiState
st -> GHCiState
st {tickarrays :: ModuleEnv TickArray
tickarrays = ModuleEnv TickArray
forall a. ModuleEnv a
emptyModuleEnv})

mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
mkTickArray :: [(Int, SrcSpan)] -> TickArray
mkTickArray ticks :: [(Int, SrcSpan)]
ticks
  = ([(Int, RealSrcSpan)]
 -> (Int, RealSrcSpan) -> [(Int, RealSrcSpan)])
-> [(Int, RealSrcSpan)]
-> (Int, Int)
-> [(Int, (Int, RealSrcSpan))]
-> TickArray
forall i e a.
Ix i =>
(e -> a -> e) -> e -> (i, i) -> [(i, a)] -> Array i e
accumArray (((Int, RealSrcSpan)
 -> [(Int, RealSrcSpan)] -> [(Int, RealSrcSpan)])
-> [(Int, RealSrcSpan)]
-> (Int, RealSrcSpan)
-> [(Int, RealSrcSpan)]
forall a b c. (a -> b -> c) -> b -> a -> c
flip (:)) [] (1, Int
max_line)
        [ (Int
line, (Int
nm,RealSrcSpan
pan)) | (nm :: Int
nm,RealSrcSpan pan :: RealSrcSpan
pan) <- [(Int, SrcSpan)]
ticks, Int
line <- RealSrcSpan -> [Int]
srcSpanLines RealSrcSpan
pan ]
    where
        max_line :: Int
max_line = (Int -> Int -> Int) -> Int -> [Int] -> Int
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr Int -> Int -> Int
forall a. Ord a => a -> a -> a
max 0 [ RealSrcSpan -> Int
GHC.srcSpanEndLine RealSrcSpan
sp | (_, RealSrcSpan sp :: RealSrcSpan
sp) <- [(Int, SrcSpan)]
ticks ]
        srcSpanLines :: RealSrcSpan -> [Int]
srcSpanLines pan :: RealSrcSpan
pan = [ RealSrcSpan -> Int
GHC.srcSpanStartLine RealSrcSpan
pan ..  RealSrcSpan -> Int
GHC.srcSpanEndLine RealSrcSpan
pan ]

-- don't reset the counter back to zero?
discardActiveBreakPoints :: GHCi ()
discardActiveBreakPoints :: GHCi ()
discardActiveBreakPoints = do
   GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
   ((Int, BreakLocation) -> GHCi ())
-> [(Int, BreakLocation)] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (BreakLocation -> GHCi ()
turnOffBreak(BreakLocation -> GHCi ())
-> ((Int, BreakLocation) -> BreakLocation)
-> (Int, BreakLocation)
-> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Int, BreakLocation) -> BreakLocation
forall a b. (a, b) -> b
snd) (GHCiState -> [(Int, BreakLocation)]
breaks GHCiState
st)
   GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState (GHCiState -> GHCi ()) -> GHCiState -> GHCi ()
forall a b. (a -> b) -> a -> b
$ GHCiState
st { breaks :: [(Int, BreakLocation)]
breaks = [] }

deleteBreak :: Int -> GHCi ()
deleteBreak :: Int -> GHCi ()
deleteBreak identity :: Int
identity = do
   GHCiState
st <- GHCi GHCiState
forall (m :: * -> *). HasGhciState m => m GHCiState
getGHCiState
   let oldLocations :: [(Int, BreakLocation)]
oldLocations    = GHCiState -> [(Int, BreakLocation)]
breaks GHCiState
st
       (this :: [(Int, BreakLocation)]
this,rest :: [(Int, BreakLocation)]
rest)     = ((Int, BreakLocation) -> Bool)
-> [(Int, BreakLocation)]
-> ([(Int, BreakLocation)], [(Int, BreakLocation)])
forall a. (a -> Bool) -> [a] -> ([a], [a])
partition (\loc :: (Int, BreakLocation)
loc -> (Int, BreakLocation) -> Int
forall a b. (a, b) -> a
fst (Int, BreakLocation)
loc Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== Int
identity) [(Int, BreakLocation)]
oldLocations
   if [(Int, BreakLocation)] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(Int, BreakLocation)]
this
      then MsgDoc -> GHCi ()
forall (m :: * -> *). GhcMonad m => MsgDoc -> m ()
printForUser (String -> MsgDoc
text "Breakpoint" MsgDoc -> MsgDoc -> MsgDoc
<+> Int -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Int
identity MsgDoc -> MsgDoc -> MsgDoc
<+>
                         String -> MsgDoc
text "does not exist")
      else do
           ((Int, BreakLocation) -> GHCi ())
-> [(Int, BreakLocation)] -> GHCi ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (BreakLocation -> GHCi ()
turnOffBreak(BreakLocation -> GHCi ())
-> ((Int, BreakLocation) -> BreakLocation)
-> (Int, BreakLocation)
-> GHCi ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
.(Int, BreakLocation) -> BreakLocation
forall a b. (a, b) -> b
snd) [(Int, BreakLocation)]
this
           GHCiState -> GHCi ()
forall (m :: * -> *). HasGhciState m => GHCiState -> m ()
setGHCiState (GHCiState -> GHCi ()) -> GHCiState -> GHCi ()
forall a b. (a -> b) -> a -> b
$ GHCiState
st { breaks :: [(Int, BreakLocation)]
breaks = [(Int, BreakLocation)]
rest }

turnOffBreak :: BreakLocation -> GHCi ()
turnOffBreak :: BreakLocation -> GHCi ()
turnOffBreak loc :: BreakLocation
loc = do
  (arr :: ForeignRef BreakArray
arr, _) <- Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak (BreakLocation -> Module
breakModule BreakLocation
loc)
  HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ HscEnv -> ForeignRef BreakArray -> Int -> Bool -> IO ()
enableBreakpoint HscEnv
hsc_env ForeignRef BreakArray
arr (BreakLocation -> Int
breakTick BreakLocation
loc) Bool
False

getModBreak :: Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak :: Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
getModBreak m :: Module
m = do
   ModuleInfo
mod_info      <- ModuleInfo -> Maybe ModuleInfo -> ModuleInfo
forall a. a -> Maybe a -> a
fromMaybe (String -> ModuleInfo
forall a. String -> a
panic "getModBreak") (Maybe ModuleInfo -> ModuleInfo)
-> GHCi (Maybe ModuleInfo) -> GHCi ModuleInfo
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Module -> GHCi (Maybe ModuleInfo)
forall (m :: * -> *). GhcMonad m => Module -> m (Maybe ModuleInfo)
GHC.getModuleInfo Module
m
   let modBreaks :: ModBreaks
modBreaks  = ModuleInfo -> ModBreaks
GHC.modInfoModBreaks ModuleInfo
mod_info
   let arr :: ForeignRef BreakArray
arr        = ModBreaks -> ForeignRef BreakArray
GHC.modBreaks_flags ModBreaks
modBreaks
   let ticks :: Array Int SrcSpan
ticks      = ModBreaks -> Array Int SrcSpan
GHC.modBreaks_locs  ModBreaks
modBreaks
   (ForeignRef BreakArray, Array Int SrcSpan)
-> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
forall (m :: * -> *) a. Monad m => a -> m a
return (ForeignRef BreakArray
arr, Array Int SrcSpan
ticks)

setBreakFlag :: Bool -> ForeignRef BreakArray -> Int -> GHCi ()
setBreakFlag :: Bool -> ForeignRef BreakArray -> Int -> GHCi ()
setBreakFlag toggle :: Bool
toggle arr :: ForeignRef BreakArray
arr i :: Int
i = do
  HscEnv
hsc_env <- GHCi HscEnv
forall (m :: * -> *). GhcMonad m => m HscEnv
GHC.getSession
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ HscEnv -> ForeignRef BreakArray -> Int -> Bool -> IO ()
enableBreakpoint HscEnv
hsc_env ForeignRef BreakArray
arr Int
i Bool
toggle

-- ---------------------------------------------------------------------------
-- User code exception handling

-- This is the exception handler for exceptions generated by the
-- user's code and exceptions coming from children sessions;
-- it normally just prints out the exception.  The
-- handler must be recursive, in case showing the exception causes
-- more exceptions to be raised.
--
-- Bugfix: if the user closed stdout or stderr, the flushing will fail,
-- raising another exception.  We therefore don't put the recursive
-- handler arond the flushing operation, so if stderr is closed
-- GHCi will just die gracefully rather than going into an infinite loop.
handler :: SomeException -> GHCi Bool

handler :: SomeException -> GHCi Bool
handler exception :: SomeException
exception = do
  GHCi ()
flushInterpBuffers
  GHCi Bool -> GHCi Bool
forall (m :: * -> *) a. (ExceptionMonad m, MonadIO m) => m a -> m a
withSignalHandlers (GHCi Bool -> GHCi Bool) -> GHCi Bool -> GHCi Bool
forall a b. (a -> b) -> a -> b
$
     (SomeException -> GHCi Bool) -> GHCi Bool -> GHCi Bool
forall (m :: * -> *) a.
(HasDynFlags m, ExceptionMonad m) =>
(SomeException -> m a) -> m a -> m a
ghciHandle SomeException -> GHCi Bool
handler (SomeException -> GHCi ()
showException SomeException
exception GHCi () -> GHCi Bool -> GHCi Bool
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False)

showException :: SomeException -> GHCi ()
showException :: SomeException -> GHCi ()
showException se :: SomeException
se =
  IO () -> GHCi ()
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> GHCi ()) -> IO () -> GHCi ()
forall a b. (a -> b) -> a -> b
$ case SomeException -> Maybe GhcException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
se of
           -- omit the location for CmdLineError:
           Just (CmdLineError s :: String
s)    -> String -> IO ()
putException String
s
           -- ditto:
           Just other_ghc_ex :: GhcException
other_ghc_ex        -> String -> IO ()
putException (GhcException -> String
forall a. Show a => a -> String
show GhcException
other_ghc_ex)
           Nothing                  ->
               case SomeException -> Maybe AsyncException
forall e. Exception e => SomeException -> Maybe e
fromException SomeException
se of
               Just UserInterrupt -> String -> IO ()
putException "Interrupted."
               _                  -> String -> IO ()
putException ("*** Exception: " String -> String -> String
forall a. [a] -> [a] -> [a]
++ SomeException -> String
forall a. Show a => a -> String
show SomeException
se)
  where
    putException :: String -> IO ()
putException = Handle -> String -> IO ()
hPutStrLn Handle
stderr


-----------------------------------------------------------------------------
-- recursive exception handlers

-- Don't forget to unblock async exceptions in the handler, or if we're
-- in an exception loop (eg. let a = error a in a) the ^C exception
-- may never be delivered.  Thanks to Marcin for pointing out the bug.

ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
ghciHandle :: (SomeException -> m a) -> m a -> m a
ghciHandle h :: SomeException -> m a
h m :: m a
m = ((m a -> m a) -> m a) -> m a
forall (m :: * -> *) a b.
ExceptionMonad m =>
((m a -> m a) -> m b) -> m b
gmask (((m a -> m a) -> m a) -> m a) -> ((m a -> m a) -> m a) -> m a
forall a b. (a -> b) -> a -> b
$ \restore :: m a -> m a
restore -> do
                 -- Force dflags to avoid leaking the associated HscEnv
                 !DynFlags
dflags <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
                 m a -> (SomeException -> m a) -> m a
forall (m :: * -> *) e a.
(ExceptionMonad m, Exception e) =>
m a -> (e -> m a) -> m a
gcatch (m a -> m a
restore (DynFlags -> m a -> m a
forall (m :: * -> *) a. ExceptionMonad m => DynFlags -> m a -> m a
GHC.prettyPrintGhcErrors DynFlags
dflags m a
m)) ((SomeException -> m a) -> m a) -> (SomeException -> m a) -> m a
forall a b. (a -> b) -> a -> b
$ \e :: SomeException
e -> m a -> m a
restore (SomeException -> m a
h SomeException
e)

ghciTry :: GHCi a -> GHCi (Either SomeException a)
ghciTry :: GHCi a -> GHCi (Either SomeException a)
ghciTry (GHCi m :: IORef GHCiState -> Ghc a
m) = (IORef GHCiState -> Ghc (Either SomeException a))
-> GHCi (Either SomeException a)
forall a. (IORef GHCiState -> Ghc a) -> GHCi a
GHCi ((IORef GHCiState -> Ghc (Either SomeException a))
 -> GHCi (Either SomeException a))
-> (IORef GHCiState -> Ghc (Either SomeException a))
-> GHCi (Either SomeException a)
forall a b. (a -> b) -> a -> b
$ \s :: IORef GHCiState
s -> Ghc a -> Ghc (Either SomeException a)
forall (m :: * -> *) e a.
(ExceptionMonad m, Exception e) =>
m a -> m (Either e a)
gtry (IORef GHCiState -> Ghc a
m IORef GHCiState
s)

tryBool :: GHCi a -> GHCi Bool
tryBool :: GHCi a -> GHCi Bool
tryBool m :: GHCi a
m = do
    Either SomeException a
r <- GHCi a -> GHCi (Either SomeException a)
forall a. GHCi a -> GHCi (Either SomeException a)
ghciTry GHCi a
m
    case Either SomeException a
r of
      Left _  -> Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
      Right _ -> Bool -> GHCi Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
True

-- ----------------------------------------------------------------------------
-- Utils

lookupModule :: GHC.GhcMonad m => String -> m Module
lookupModule :: String -> m Module
lookupModule mName :: String
mName = ModuleName -> m Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
lookupModuleName (String -> ModuleName
GHC.mkModuleName String
mName)

lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
lookupModuleName :: ModuleName -> m Module
lookupModuleName mName :: ModuleName
mName = ModuleName -> Maybe FastString -> m Module
forall (m :: * -> *).
GhcMonad m =>
ModuleName -> Maybe FastString -> m Module
GHC.lookupModule ModuleName
mName Maybe FastString
forall a. Maybe a
Nothing

isHomeModule :: Module -> Bool
isHomeModule :: Module -> Bool
isHomeModule m :: Module
m = Module -> UnitId
GHC.moduleUnitId Module
m UnitId -> UnitId -> Bool
forall a. Eq a => a -> a -> Bool
== UnitId
mainUnitId

-- TODO: won't work if home dir is encoded.
-- (changeDirectory may not work either in that case.)
expandPath :: MonadIO m => String -> InputT m String
expandPath :: String -> InputT m String
expandPath = IO String -> InputT m String
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO String -> InputT m String)
-> (String -> IO String) -> String -> InputT m String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> IO String
expandPathIO

expandPathIO :: String -> IO String
expandPathIO :: String -> IO String
expandPathIO p :: String
p =
  case (Char -> Bool) -> String -> String
forall a. (a -> Bool) -> [a] -> [a]
dropWhile Char -> Bool
isSpace String
p of
   ('~':d :: String
d) -> do
        String
tilde <- IO String
getHomeDirectory -- will fail if HOME not defined
        String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return (String
tilde String -> String -> String
forall a. [a] -> [a] -> [a]
++ '/'Char -> String -> String
forall a. a -> [a] -> [a]
:String
d)
   other :: String
other ->
        String -> IO String
forall (m :: * -> *) a. Monad m => a -> m a
return String
other

wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
wantInterpretedModule :: String -> m Module
wantInterpretedModule str :: String
str = ModuleName -> m Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName (String -> ModuleName
GHC.mkModuleName String
str)

wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
wantInterpretedModuleName :: ModuleName -> m Module
wantInterpretedModuleName modname :: ModuleName
modname = do
   Module
modl <- ModuleName -> m Module
forall (m :: * -> *). GhcMonad m => ModuleName -> m Module
lookupModuleName ModuleName
modname
   let str :: String
str = ModuleName -> String
moduleNameString ModuleName
modname
   DynFlags
dflags <- m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags
   Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Module -> UnitId
GHC.moduleUnitId Module
modl UnitId -> UnitId -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> UnitId
thisPackage DynFlags
dflags) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
      GhcException -> m ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError ("module '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
str String -> String -> String
forall a. [a] -> [a] -> [a]
++ "' is from another package;\nthis command requires an interpreted module"))
   Bool
is_interpreted <- Module -> m Bool
forall (m :: * -> *). GhcMonad m => Module -> m Bool
GHC.moduleIsInterpreted Module
modl
   Bool -> m () -> m ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (Bool -> Bool
not Bool
is_interpreted) (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$
       GhcException -> m ()
forall a. GhcException -> a
throwGhcException (String -> GhcException
CmdLineError ("module '" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
str String -> String -> String
forall a. [a] -> [a] -> [a]
++ "' is not interpreted; try \':add *" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
str String -> String -> String
forall a. [a] -> [a] -> [a]
++ "' first"))
   Module -> m Module
forall (m :: * -> *) a. Monad m => a -> m a
return Module
modl

wantNameFromInterpretedModule :: GHC.GhcMonad m
                              => (Name -> SDoc -> m ())
                              -> String
                              -> (Name -> m ())
                              -> m ()
wantNameFromInterpretedModule :: (Name -> MsgDoc -> m ()) -> String -> (Name -> m ()) -> m ()
wantNameFromInterpretedModule noCanDo :: Name -> MsgDoc -> m ()
noCanDo str :: String
str and_then :: Name -> m ()
and_then =
  (SourceError -> m ()) -> m () -> m ()
forall (m :: * -> *) a.
ExceptionMonad m =>
(SourceError -> m a) -> m a -> m a
handleSourceError SourceError -> m ()
forall (m :: * -> *). GhcMonad m => SourceError -> m ()
GHC.printException (m () -> m ()) -> m () -> m ()
forall a b. (a -> b) -> a -> b
$ do
   [Name]
names <- String -> m [Name]
forall (m :: * -> *). GhcMonad m => String -> m [Name]
GHC.parseName String
str
   case [Name]
names of
      []    -> () -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ()
      (n :: Name
n:_) -> do
            let modl :: Module
modl = ASSERT( isExternalName n ) GHC.nameModule n
            if Bool -> Bool
not (Name -> Bool
GHC.isExternalName Name
n)
               then Name -> MsgDoc -> m ()
noCanDo Name
n (MsgDoc -> m ()) -> MsgDoc -> m ()
forall a b. (a -> b) -> a -> b
$ Name -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Name
n MsgDoc -> MsgDoc -> MsgDoc
<>
                                String -> MsgDoc
text " is not defined in an interpreted module"
               else do
            Bool
is_interpreted <- Module -> m Bool
forall (m :: * -> *). GhcMonad m => Module -> m Bool
GHC.moduleIsInterpreted Module
modl
            if Bool -> Bool
not Bool
is_interpreted
               then Name -> MsgDoc -> m ()
noCanDo Name
n (MsgDoc -> m ()) -> MsgDoc -> m ()
forall a b. (a -> b) -> a -> b
$ String -> MsgDoc
text "module " MsgDoc -> MsgDoc -> MsgDoc
<> Module -> MsgDoc
forall a. Outputable a => a -> MsgDoc
ppr Module
modl MsgDoc -> MsgDoc -> MsgDoc
<>
                                String -> MsgDoc
text " is not interpreted"
               else Name -> m ()
and_then Name
n