PageRenderTime 81ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 1ms

/ghc/InteractiveUI.hs

https://github.com/crdueck/ghc
Haskell | 3091 lines | 2314 code | 414 blank | 363 comment | 147 complexity | 2e7242efd9db5c4141470da19f285f54 MD5 | raw file
  1. {-# OPTIONS -fno-cse #-}
  2. -- -fno-cse is needed for GLOBAL_VAR's to behave properly
  3. -----------------------------------------------------------------------------
  4. --
  5. -- GHC Interactive User Interface
  6. --
  7. -- (c) The GHC Team 2005-2006
  8. --
  9. -----------------------------------------------------------------------------
  10. module InteractiveUI (
  11. interactiveUI,
  12. GhciSettings(..),
  13. defaultGhciSettings,
  14. ghciCommands,
  15. ghciWelcomeMsg
  16. ) where
  17. #include "HsVersions.h"
  18. -- GHCi
  19. import qualified GhciMonad ( args, runStmt )
  20. import GhciMonad hiding ( args, runStmt )
  21. import GhciTags
  22. import Debugger
  23. -- The GHC interface
  24. import DynFlags
  25. import GhcMonad ( modifySession )
  26. import qualified GHC
  27. import GHC ( LoadHowMuch(..), Target(..), TargetId(..), InteractiveImport(..),
  28. TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
  29. handleSourceError )
  30. import HsImpExp
  31. import HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
  32. setInteractivePrintName )
  33. import Module
  34. import Name
  35. import Packages ( trusted, getPackageDetails, exposed, exposedModules, pkgIdMap )
  36. import PprTyThing
  37. import RdrName ( getGRE_NameQualifier_maybes )
  38. import SrcLoc
  39. import qualified Lexer
  40. import StringBuffer
  41. import UniqFM ( eltsUFM )
  42. import Outputable hiding ( printForUser, printForUserPartWay, bold )
  43. -- Other random utilities
  44. import BasicTypes hiding ( isTopLevel )
  45. import Config
  46. import Digraph
  47. import Encoding
  48. import FastString
  49. import Linker
  50. import Maybes ( orElse, expectJust )
  51. import NameSet
  52. import Panic hiding ( showException )
  53. import Util
  54. -- Haskell Libraries
  55. import System.Console.Haskeline as Haskeline
  56. import Control.Applicative hiding (empty)
  57. import Control.Monad as Monad
  58. import Control.Monad.Trans.Class
  59. import Control.Monad.IO.Class
  60. import Data.Array
  61. import qualified Data.ByteString.Char8 as BS
  62. import Data.Char
  63. import Data.Function
  64. import Data.IORef ( IORef, readIORef, writeIORef )
  65. import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
  66. partition, sort, sortBy )
  67. import Data.Maybe
  68. import Exception hiding (catch)
  69. import Foreign.C
  70. import Foreign.Safe
  71. import System.Directory
  72. import System.Environment
  73. import System.Exit ( exitWith, ExitCode(..) )
  74. import System.FilePath
  75. import System.IO
  76. import System.IO.Error
  77. import System.IO.Unsafe ( unsafePerformIO )
  78. import System.Process
  79. import Text.Printf
  80. import Text.Read ( readMaybe )
  81. #ifndef mingw32_HOST_OS
  82. import System.Posix hiding ( getEnv )
  83. #else
  84. import qualified System.Win32
  85. #endif
  86. import GHC.Exts ( unsafeCoerce# )
  87. import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
  88. import GHC.IO.Handle ( hFlushAll )
  89. import GHC.TopHandler ( topHandler )
  90. -----------------------------------------------------------------------------
  91. data GhciSettings = GhciSettings {
  92. availableCommands :: [Command],
  93. shortHelpText :: String,
  94. fullHelpText :: String,
  95. defPrompt :: String,
  96. defPrompt2 :: String
  97. }
  98. defaultGhciSettings :: GhciSettings
  99. defaultGhciSettings =
  100. GhciSettings {
  101. availableCommands = ghciCommands,
  102. shortHelpText = defShortHelpText,
  103. fullHelpText = defFullHelpText,
  104. defPrompt = default_prompt,
  105. defPrompt2 = default_prompt2
  106. }
  107. ghciWelcomeMsg :: String
  108. ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
  109. ": http://www.haskell.org/ghc/ :? for help"
  110. cmdName :: Command -> String
  111. cmdName (n,_,_) = n
  112. GLOBAL_VAR(macros_ref, [], [Command])
  113. ghciCommands :: [Command]
  114. ghciCommands = [
  115. -- Hugs users are accustomed to :e, so make sure it doesn't overlap
  116. ("?", keepGoing help, noCompletion),
  117. ("add", keepGoingPaths addModule, completeFilename),
  118. ("abandon", keepGoing abandonCmd, noCompletion),
  119. ("break", keepGoing breakCmd, completeIdentifier),
  120. ("back", keepGoing backCmd, noCompletion),
  121. ("browse", keepGoing' (browseCmd False), completeModule),
  122. ("browse!", keepGoing' (browseCmd True), completeModule),
  123. ("cd", keepGoing' changeDirectory, completeFilename),
  124. ("check", keepGoing' checkModule, completeHomeModule),
  125. ("continue", keepGoing continueCmd, noCompletion),
  126. ("complete", keepGoing completeCmd, noCompletion),
  127. ("cmd", keepGoing cmdCmd, completeExpression),
  128. ("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
  129. ("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
  130. ("def", keepGoing (defineMacro False), completeExpression),
  131. ("def!", keepGoing (defineMacro True), completeExpression),
  132. ("delete", keepGoing deleteCmd, noCompletion),
  133. ("edit", keepGoing' editFile, completeFilename),
  134. ("etags", keepGoing createETagsFileCmd, completeFilename),
  135. ("force", keepGoing forceCmd, completeExpression),
  136. ("forward", keepGoing forwardCmd, noCompletion),
  137. ("help", keepGoing help, noCompletion),
  138. ("history", keepGoing historyCmd, noCompletion),
  139. ("info", keepGoing' (info False), completeIdentifier),
  140. ("info!", keepGoing' (info True), completeIdentifier),
  141. ("issafe", keepGoing' isSafeCmd, completeModule),
  142. ("kind", keepGoing' (kindOfType False), completeIdentifier),
  143. ("kind!", keepGoing' (kindOfType True), completeIdentifier),
  144. ("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
  145. ("list", keepGoing' listCmd, noCompletion),
  146. ("module", keepGoing moduleCmd, completeSetModule),
  147. ("main", keepGoing runMain, completeFilename),
  148. ("print", keepGoing printCmd, completeExpression),
  149. ("quit", quit, noCompletion),
  150. ("reload", keepGoing' reloadModule, noCompletion),
  151. ("run", keepGoing runRun, completeFilename),
  152. ("script", keepGoing' scriptCmd, completeFilename),
  153. ("set", keepGoing setCmd, completeSetOptions),
  154. ("seti", keepGoing setiCmd, completeSeti),
  155. ("show", keepGoing showCmd, completeShowOptions),
  156. ("showi", keepGoing showiCmd, completeShowiOptions),
  157. ("sprint", keepGoing sprintCmd, completeExpression),
  158. ("step", keepGoing stepCmd, completeIdentifier),
  159. ("steplocal", keepGoing stepLocalCmd, completeIdentifier),
  160. ("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
  161. ("type", keepGoing' typeOfExpr, completeExpression),
  162. ("trace", keepGoing traceCmd, completeExpression),
  163. ("undef", keepGoing undefineMacro, completeMacro),
  164. ("unset", keepGoing unsetOptions, completeSetOptions)
  165. ]
  166. -- We initialize readline (in the interactiveUI function) to use
  167. -- word_break_chars as the default set of completion word break characters.
  168. -- This can be overridden for a particular command (for example, filename
  169. -- expansion shouldn't consider '/' to be a word break) by setting the third
  170. -- entry in the Command tuple above.
  171. --
  172. -- NOTE: in order for us to override the default correctly, any custom entry
  173. -- must be a SUBSET of word_break_chars.
  174. word_break_chars :: String
  175. word_break_chars = let symbols = "!#$%&*+/<=>?@\\^|-~"
  176. specials = "(),;[]`{}"
  177. spaces = " \t\n"
  178. in spaces ++ specials ++ symbols
  179. flagWordBreakChars :: String
  180. flagWordBreakChars = " \t\n"
  181. keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
  182. keepGoing a str = keepGoing' (lift . a) str
  183. keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
  184. keepGoing' a str = a str >> return False
  185. keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
  186. keepGoingPaths a str
  187. = do case toArgs str of
  188. Left err -> liftIO $ hPutStrLn stderr err
  189. Right args -> a args
  190. return False
  191. defShortHelpText :: String
  192. defShortHelpText = "use :? for help.\n"
  193. defFullHelpText :: String
  194. defFullHelpText =
  195. " Commands available from the prompt:\n" ++
  196. "\n" ++
  197. " <statement> evaluate/run <statement>\n" ++
  198. " : repeat last command\n" ++
  199. " :{\\n ..lines.. \\n:}\\n multiline command\n" ++
  200. " :add [*]<module> ... add module(s) to the current target set\n" ++
  201. " :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
  202. " (!: more details; *: all top-level names)\n" ++
  203. " :cd <dir> change directory to <dir>\n" ++
  204. " :cmd <expr> run the commands returned by <expr>::IO String\n" ++
  205. " :complete <dom> [<rng>] <s> list completions for partial input string\n" ++
  206. " :ctags[!] [<file>] create tags file for Vi (default: \"tags\")\n" ++
  207. " (!: use regex instead of line number)\n" ++
  208. " :def <cmd> <expr> define command :<cmd> (later defined command has\n" ++
  209. " precedence, ::<cmd> is always a builtin command)\n" ++
  210. " :edit <file> edit file\n" ++
  211. " :edit edit last module\n" ++
  212. " :etags [<file>] create tags file for Emacs (default: \"TAGS\")\n" ++
  213. " :help, :? display this list of commands\n" ++
  214. " :info[!] [<name> ...] display information about the given names\n" ++
  215. " (!: do not filter instances)\n" ++
  216. " :issafe [<mod>] display safe haskell information of module <mod>\n" ++
  217. " :kind <type> show the kind of <type>\n" ++
  218. " :load [*]<module> ... load module(s) and their dependents\n" ++
  219. " :main [<arguments> ...] run the main function with the given arguments\n" ++
  220. " :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
  221. " :quit exit GHCi\n" ++
  222. " :reload reload the current module set\n" ++
  223. " :run function [<arguments> ...] run the function with the given arguments\n" ++
  224. " :script <filename> run the script <filename>\n" ++
  225. " :type <expr> show the type of <expr>\n" ++
  226. " :undef <cmd> undefine user-defined command :<cmd>\n" ++
  227. " :!<command> run the shell command <command>\n" ++
  228. "\n" ++
  229. " -- Commands for debugging:\n" ++
  230. "\n" ++
  231. " :abandon at a breakpoint, abandon current computation\n" ++
  232. " :back go back in the history (after :trace)\n" ++
  233. " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
  234. " :break <name> set a breakpoint on the specified function\n" ++
  235. " :continue resume after a breakpoint\n" ++
  236. " :delete <number> delete the specified breakpoint\n" ++
  237. " :delete * delete all breakpoints\n" ++
  238. " :force <expr> print <expr>, forcing unevaluated parts\n" ++
  239. " :forward go forward in the history (after :back)\n" ++
  240. " :history [<n>] after :trace, show the execution history\n" ++
  241. " :list show the source code around current breakpoint\n" ++
  242. " :list identifier show the source code for <identifier>\n" ++
  243. " :list [<module>] <line> show the source code around line number <line>\n" ++
  244. " :print [<name> ...] prints a value without forcing its computation\n" ++
  245. " :sprint [<name> ...] simplifed version of :print\n" ++
  246. " :step single-step after stopping at a breakpoint\n"++
  247. " :step <expr> single-step into <expr>\n"++
  248. " :steplocal single-step within the current top-level binding\n"++
  249. " :stepmodule single-step restricted to the current module\n"++
  250. " :trace trace after stopping at a breakpoint\n"++
  251. " :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
  252. "\n" ++
  253. " -- Commands for changing settings:\n" ++
  254. "\n" ++
  255. " :set <option> ... set options\n" ++
  256. " :seti <option> ... set options for interactive evaluation only\n" ++
  257. " :set args <arg> ... set the arguments returned by System.getArgs\n" ++
  258. " :set prog <progname> set the value returned by System.getProgName\n" ++
  259. " :set prompt <prompt> set the prompt used in GHCi\n" ++
  260. " :set prompt2 <prompt> set the continuation prompt used in GHCi\n" ++
  261. " :set editor <cmd> set the command used for :edit\n" ++
  262. " :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
  263. " :unset <option> ... unset options\n" ++
  264. "\n" ++
  265. " Options for ':set' and ':unset':\n" ++
  266. "\n" ++
  267. " +m allow multiline commands\n" ++
  268. " +r revert top-level expressions after each evaluation\n" ++
  269. " +s print timing/memory stats after each evaluation\n" ++
  270. " +t print type after evaluation\n" ++
  271. " -<flags> most GHC command line flags can also be set here\n" ++
  272. " (eg. -v2, -fglasgow-exts, etc.)\n" ++
  273. " for GHCi-specific flags, see User's Guide,\n"++
  274. " Flag reference, Interactive-mode options\n" ++
  275. "\n" ++
  276. " -- Commands for displaying information:\n" ++
  277. "\n" ++
  278. " :show bindings show the current bindings made at the prompt\n" ++
  279. " :show breaks show the active breakpoints\n" ++
  280. " :show context show the breakpoint context\n" ++
  281. " :show imports show the current imports\n" ++
  282. " :show linker show current linker state\n" ++
  283. " :show modules show the currently loaded modules\n" ++
  284. " :show packages show the currently active package flags\n" ++
  285. " :show language show the currently active language flags\n" ++
  286. " :show <setting> show value of <setting>, which is one of\n" ++
  287. " [args, prog, prompt, editor, stop]\n" ++
  288. " :showi language show language flags for interactive evaluation\n" ++
  289. "\n"
  290. findEditor :: IO String
  291. findEditor = do
  292. getEnv "EDITOR"
  293. `catchIO` \_ -> do
  294. #if mingw32_HOST_OS
  295. win <- System.Win32.getWindowsDirectory
  296. return (win </> "notepad.exe")
  297. #else
  298. return ""
  299. #endif
  300. foreign import ccall unsafe "rts_isProfiled" isProfiled :: IO CInt
  301. default_progname, default_prompt, default_prompt2, default_stop :: String
  302. default_progname = "<interactive>"
  303. default_prompt = "%s> "
  304. default_prompt2 = "%s| "
  305. default_stop = ""
  306. default_args :: [String]
  307. default_args = []
  308. interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
  309. -> Ghc ()
  310. interactiveUI config srcs maybe_exprs = do
  311. -- although GHCi compiles with -prof, it is not usable: the byte-code
  312. -- compiler and interpreter don't work with profiling. So we check for
  313. -- this up front and emit a helpful error message (#2197)
  314. i <- liftIO $ isProfiled
  315. when (i /= 0) $
  316. throwGhcException (InstallationError "GHCi cannot be used when compiled with -prof")
  317. -- HACK! If we happen to get into an infinite loop (eg the user
  318. -- types 'let x=x in x' at the prompt), then the thread will block
  319. -- on a blackhole, and become unreachable during GC. The GC will
  320. -- detect that it is unreachable and send it the NonTermination
  321. -- exception. However, since the thread is unreachable, everything
  322. -- it refers to might be finalized, including the standard Handles.
  323. -- This sounds like a bug, but we don't have a good solution right
  324. -- now.
  325. _ <- liftIO $ newStablePtr stdin
  326. _ <- liftIO $ newStablePtr stdout
  327. _ <- liftIO $ newStablePtr stderr
  328. -- Initialise buffering for the *interpreted* I/O system
  329. initInterpBuffering
  330. -- The initial set of DynFlags used for interactive evaluation is the same
  331. -- as the global DynFlags, plus -XExtendedDefaultRules and
  332. -- -XNoMonomorphismRestriction.
  333. dflags <- getDynFlags
  334. let dflags' = (`xopt_set` Opt_ExtendedDefaultRules)
  335. . (`xopt_unset` Opt_MonomorphismRestriction)
  336. $ dflags
  337. GHC.setInteractiveDynFlags dflags'
  338. liftIO $ when (isNothing maybe_exprs) $ do
  339. -- Only for GHCi (not runghc and ghc -e):
  340. -- Turn buffering off for the compiled program's stdout/stderr
  341. turnOffBuffering
  342. -- Turn buffering off for GHCi's stdout
  343. hFlush stdout
  344. hSetBuffering stdout NoBuffering
  345. -- We don't want the cmd line to buffer any input that might be
  346. -- intended for the program, so unbuffer stdin.
  347. hSetBuffering stdin NoBuffering
  348. #if defined(mingw32_HOST_OS)
  349. -- On Unix, stdin will use the locale encoding. The IO library
  350. -- doesn't do this on Windows (yet), so for now we use UTF-8,
  351. -- for consistency with GHC 6.10 and to make the tests work.
  352. hSetEncoding stdin utf8
  353. #endif
  354. default_editor <- liftIO $ findEditor
  355. startGHCi (runGHCi srcs maybe_exprs)
  356. GHCiState{ progname = default_progname,
  357. GhciMonad.args = default_args,
  358. prompt = defPrompt config,
  359. prompt2 = defPrompt2 config,
  360. stop = default_stop,
  361. editor = default_editor,
  362. options = [],
  363. line_number = 1,
  364. break_ctr = 0,
  365. breaks = [],
  366. tickarrays = emptyModuleEnv,
  367. ghci_commands = availableCommands config,
  368. last_command = Nothing,
  369. cmdqueue = [],
  370. remembered_ctx = [],
  371. transient_ctx = [],
  372. ghc_e = isJust maybe_exprs,
  373. short_help = shortHelpText config,
  374. long_help = fullHelpText config
  375. }
  376. return ()
  377. withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
  378. withGhcAppData right left = do
  379. either_dir <- tryIO (getAppUserDataDirectory "ghc")
  380. case either_dir of
  381. Right dir ->
  382. do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
  383. right dir
  384. _ -> left
  385. runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
  386. runGHCi paths maybe_exprs = do
  387. dflags <- getDynFlags
  388. let
  389. read_dot_files = not (gopt Opt_IgnoreDotGhci dflags)
  390. current_dir = return (Just ".ghci")
  391. app_user_dir = liftIO $ withGhcAppData
  392. (\dir -> return (Just (dir </> "ghci.conf")))
  393. (return Nothing)
  394. home_dir = do
  395. either_dir <- liftIO $ tryIO (getEnv "HOME")
  396. case either_dir of
  397. Right home -> return (Just (home </> ".ghci"))
  398. _ -> return Nothing
  399. canonicalizePath' :: FilePath -> IO (Maybe FilePath)
  400. canonicalizePath' fp = liftM Just (canonicalizePath fp)
  401. `catchIO` \_ -> return Nothing
  402. sourceConfigFile :: FilePath -> GHCi ()
  403. sourceConfigFile file = do
  404. exists <- liftIO $ doesFileExist file
  405. when exists $ do
  406. dir_ok <- liftIO $ checkPerms (getDirectory file)
  407. file_ok <- liftIO $ checkPerms file
  408. when (dir_ok && file_ok) $ do
  409. either_hdl <- liftIO $ tryIO (openFile file ReadMode)
  410. case either_hdl of
  411. Left _e -> return ()
  412. -- NOTE: this assumes that runInputT won't affect the terminal;
  413. -- can we assume this will always be the case?
  414. -- This would be a good place for runFileInputT.
  415. Right hdl ->
  416. do runInputTWithPrefs defaultPrefs defaultSettings $
  417. runCommands $ fileLoop hdl
  418. liftIO (hClose hdl `catchIO` \_ -> return ())
  419. where
  420. getDirectory f = case takeDirectory f of "" -> "."; d -> d
  421. --
  422. setGHCContextFromGHCiState
  423. when (read_dot_files) $ do
  424. mcfgs0 <- sequence $ [ current_dir, app_user_dir, home_dir ] ++ map (return . Just ) (ghciScripts dflags)
  425. mcfgs <- liftIO $ mapM canonicalizePath' (catMaybes mcfgs0)
  426. mapM_ sourceConfigFile $ nub $ catMaybes mcfgs
  427. -- nub, because we don't want to read .ghci twice if the
  428. -- CWD is $HOME.
  429. -- Perform a :load for files given on the GHCi command line
  430. -- When in -e mode, if the load fails then we want to stop
  431. -- immediately rather than going on to evaluate the expression.
  432. when (not (null paths)) $ do
  433. ok <- ghciHandle (\e -> do showException e; return Failed) $
  434. -- TODO: this is a hack.
  435. runInputTWithPrefs defaultPrefs defaultSettings $
  436. loadModule paths
  437. when (isJust maybe_exprs && failed ok) $
  438. liftIO (exitWith (ExitFailure 1))
  439. installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
  440. -- if verbosity is greater than 0, or we are connected to a
  441. -- terminal, display the prompt in the interactive loop.
  442. is_tty <- liftIO (hIsTerminalDevice stdin)
  443. let show_prompt = verbosity dflags > 0 || is_tty
  444. -- reset line number
  445. getGHCiState >>= \st -> setGHCiState st{line_number=1}
  446. case maybe_exprs of
  447. Nothing ->
  448. do
  449. -- enter the interactive loop
  450. runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
  451. Just exprs -> do
  452. -- just evaluate the expression we were given
  453. enqueueCommands exprs
  454. let hdle e = do st <- getGHCiState
  455. -- flush the interpreter's stdout/stderr on exit (#3890)
  456. flushInterpBuffers
  457. -- Jump through some hoops to get the
  458. -- current progname in the exception text:
  459. -- <progname>: <exception>
  460. liftIO $ withProgName (progname st)
  461. $ topHandler e
  462. -- this used to be topHandlerFastExit, see #2228
  463. runInputTWithPrefs defaultPrefs defaultSettings $ do
  464. runCommands' hdle (return Nothing)
  465. -- and finally, exit
  466. liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
  467. runGHCiInput :: InputT GHCi a -> GHCi a
  468. runGHCiInput f = do
  469. dflags <- getDynFlags
  470. histFile <- if gopt Opt_GhciHistory dflags
  471. then liftIO $ withGhcAppData (\dir -> return (Just (dir </> "ghci_history")))
  472. (return Nothing)
  473. else return Nothing
  474. runInputT
  475. (setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
  476. f
  477. -- | How to get the next input line from the user
  478. nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
  479. nextInputLine show_prompt is_tty
  480. | is_tty = do
  481. prmpt <- if show_prompt then lift mkPrompt else return ""
  482. r <- getInputLine prmpt
  483. incrementLineNo
  484. return r
  485. | otherwise = do
  486. when show_prompt $ lift mkPrompt >>= liftIO . putStr
  487. fileLoop stdin
  488. -- NOTE: We only read .ghci files if they are owned by the current user,
  489. -- and aren't world writable. Otherwise, we could be accidentally
  490. -- running code planted by a malicious third party.
  491. -- Furthermore, We only read ./.ghci if . is owned by the current user
  492. -- and isn't writable by anyone else. I think this is sufficient: we
  493. -- don't need to check .. and ../.. etc. because "." always refers to
  494. -- the same directory while a process is running.
  495. checkPerms :: String -> IO Bool
  496. #ifdef mingw32_HOST_OS
  497. checkPerms _ = return True
  498. #else
  499. checkPerms name =
  500. handleIO (\_ -> return False) $ do
  501. st <- getFileStatus name
  502. me <- getRealUserID
  503. if fileOwner st /= me then do
  504. putStrLn $ "WARNING: " ++ name ++ " is owned by someone else, IGNORING!"
  505. return False
  506. else do
  507. let mode = System.Posix.fileMode st
  508. if (groupWriteMode == (mode `intersectFileModes` groupWriteMode))
  509. || (otherWriteMode == (mode `intersectFileModes` otherWriteMode))
  510. then do
  511. putStrLn $ "*** WARNING: " ++ name ++
  512. " is writable by someone else, IGNORING!"
  513. return False
  514. else return True
  515. #endif
  516. incrementLineNo :: InputT GHCi ()
  517. incrementLineNo = do
  518. st <- lift $ getGHCiState
  519. let ln = 1+(line_number st)
  520. lift $ setGHCiState st{line_number=ln}
  521. fileLoop :: Handle -> InputT GHCi (Maybe String)
  522. fileLoop hdl = do
  523. l <- liftIO $ tryIO $ hGetLine hdl
  524. case l of
  525. Left e | isEOFError e -> return Nothing
  526. | -- as we share stdin with the program, the program
  527. -- might have already closed it, so we might get a
  528. -- handle-closed exception. We therefore catch that
  529. -- too.
  530. isIllegalOperation e -> return Nothing
  531. | InvalidArgument <- etype -> return Nothing
  532. | otherwise -> liftIO $ ioError e
  533. where etype = ioeGetErrorType e
  534. -- treat InvalidArgument in the same way as EOF:
  535. -- this can happen if the user closed stdin, or
  536. -- perhaps did getContents which closes stdin at
  537. -- EOF.
  538. Right l' -> do
  539. incrementLineNo
  540. return (Just l')
  541. mkPrompt :: GHCi String
  542. mkPrompt = do
  543. imports <- GHC.getContext
  544. resumes <- GHC.getResumeContext
  545. context_bit <-
  546. case resumes of
  547. [] -> return empty
  548. r:_ -> do
  549. let ix = GHC.resumeHistoryIx r
  550. if ix == 0
  551. then return (brackets (ppr (GHC.resumeSpan r)) <> space)
  552. else do
  553. let hist = GHC.resumeHistory r !! (ix-1)
  554. pan <- GHC.getHistorySpan hist
  555. return (brackets (ppr (negate ix) <> char ':'
  556. <+> ppr pan) <> space)
  557. let
  558. dots | _:rs <- resumes, not (null rs) = text "... "
  559. | otherwise = empty
  560. rev_imports = reverse imports -- rightmost are the most recent
  561. modules_bit =
  562. hsep [ char '*' <> ppr m | IIModule m <- rev_imports ] <+>
  563. hsep (map ppr [ myIdeclName d | IIDecl d <- rev_imports ])
  564. -- use the 'as' name if there is one
  565. myIdeclName d | Just m <- ideclAs d = m
  566. | otherwise = unLoc (ideclName d)
  567. deflt_prompt = dots <> context_bit <> modules_bit
  568. f ('%':'s':xs) = deflt_prompt <> f xs
  569. f ('%':'%':xs) = char '%' <> f xs
  570. f (x:xs) = char x <> f xs
  571. f [] = empty
  572. st <- getGHCiState
  573. dflags <- getDynFlags
  574. return (showSDoc dflags (f (prompt st)))
  575. queryQueue :: GHCi (Maybe String)
  576. queryQueue = do
  577. st <- getGHCiState
  578. case cmdqueue st of
  579. [] -> return Nothing
  580. c:cs -> do setGHCiState st{ cmdqueue = cs }
  581. return (Just c)
  582. -- Reconfigurable pretty-printing Ticket #5461
  583. installInteractivePrint :: Maybe String -> Bool -> GHCi ()
  584. installInteractivePrint Nothing _ = return ()
  585. installInteractivePrint (Just ipFun) exprmode = do
  586. ok <- trySuccess $ do
  587. (name:_) <- GHC.parseName ipFun
  588. modifySession (\he -> let new_ic = setInteractivePrintName (hsc_IC he) name
  589. in he{hsc_IC = new_ic})
  590. return Succeeded
  591. when (failed ok && exprmode) $ liftIO (exitWith (ExitFailure 1))
  592. -- | The main read-eval-print loop
  593. runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
  594. runCommands = runCommands' handler
  595. runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
  596. -> InputT GHCi (Maybe String) -> InputT GHCi ()
  597. runCommands' eh gCmd = do
  598. b <- ghandle (\e -> case fromException e of
  599. Just UserInterrupt -> return $ Just False
  600. _ -> case fromException e of
  601. Just ghce ->
  602. do liftIO (print (ghce :: GhcException))
  603. return Nothing
  604. _other ->
  605. liftIO (Exception.throwIO e))
  606. (runOneCommand eh gCmd)
  607. case b of
  608. Nothing -> return ()
  609. Just _ -> runCommands' eh gCmd
  610. -- | Evaluate a single line of user input (either :<command> or Haskell code)
  611. runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
  612. -> InputT GHCi (Maybe Bool)
  613. runOneCommand eh gCmd = do
  614. -- run a previously queued command if there is one, otherwise get new
  615. -- input from user
  616. mb_cmd0 <- noSpace (lift queryQueue)
  617. mb_cmd1 <- maybe (noSpace gCmd) (return . Just) mb_cmd0
  618. case mb_cmd1 of
  619. Nothing -> return Nothing
  620. Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
  621. handleSourceError printErrorAndKeepGoing
  622. (doCommand c)
  623. -- source error's are handled by runStmt
  624. -- is the handler necessary here?
  625. where
  626. printErrorAndKeepGoing err = do
  627. GHC.printException err
  628. return $ Just True
  629. noSpace q = q >>= maybe (return Nothing)
  630. (\c -> case removeSpaces c of
  631. "" -> noSpace q
  632. ":{" -> multiLineCmd q
  633. c' -> return (Just c') )
  634. multiLineCmd q = do
  635. st <- lift getGHCiState
  636. let p = prompt st
  637. lift $ setGHCiState st{ prompt = prompt2 st }
  638. mb_cmd <- collectCommand q ""
  639. lift $ getGHCiState >>= \st' -> setGHCiState st'{ prompt = p }
  640. return mb_cmd
  641. -- we can't use removeSpaces for the sublines here, so
  642. -- multiline commands are somewhat more brittle against
  643. -- fileformat errors (such as \r in dos input on unix),
  644. -- we get rid of any extra spaces for the ":}" test;
  645. -- we also avoid silent failure if ":}" is not found;
  646. -- and since there is no (?) valid occurrence of \r (as
  647. -- opposed to its String representation, "\r") inside a
  648. -- ghci command, we replace any such with ' ' (argh:-(
  649. collectCommand q c = q >>=
  650. maybe (liftIO (ioError collectError))
  651. (\l->if removeSpaces l == ":}"
  652. then return (Just $ removeSpaces c)
  653. else collectCommand q (c ++ "\n" ++ map normSpace l))
  654. where normSpace '\r' = ' '
  655. normSpace x = x
  656. -- SDM (2007-11-07): is userError the one to use here?
  657. collectError = userError "unterminated multiline command :{ .. :}"
  658. -- | Handle a line of input
  659. doCommand :: String -> InputT GHCi (Maybe Bool)
  660. -- command
  661. doCommand (':' : cmd) = do
  662. result <- specialCommand cmd
  663. case result of
  664. True -> return Nothing
  665. _ -> return $ Just True
  666. -- haskell
  667. doCommand stmt = do
  668. ml <- lift $ isOptionSet Multiline
  669. if ml
  670. then do
  671. mb_stmt <- checkInputForLayout stmt gCmd
  672. case mb_stmt of
  673. Nothing -> return $ Just True
  674. Just ml_stmt -> do
  675. result <- timeIt $ lift $ runStmt ml_stmt GHC.RunToCompletion
  676. return $ Just result
  677. else do
  678. result <- timeIt $ lift $ runStmt stmt GHC.RunToCompletion
  679. return $ Just result
  680. -- #4316
  681. -- lex the input. If there is an unclosed layout context, request input
  682. checkInputForLayout :: String -> InputT GHCi (Maybe String)
  683. -> InputT GHCi (Maybe String)
  684. checkInputForLayout stmt getStmt = do
  685. dflags' <- lift $ getDynFlags
  686. let dflags = xopt_set dflags' Opt_AlternativeLayoutRule
  687. st0 <- lift $ getGHCiState
  688. let buf' = stringToStringBuffer stmt
  689. loc = mkRealSrcLoc (fsLit (progname st0)) (line_number st0) 1
  690. pstate = Lexer.mkPState dflags buf' loc
  691. case Lexer.unP goToEnd pstate of
  692. (Lexer.POk _ False) -> return $ Just stmt
  693. _other -> do
  694. st1 <- lift getGHCiState
  695. let p = prompt st1
  696. lift $ setGHCiState st1{ prompt = prompt2 st1 }
  697. mb_stmt <- ghciHandle (\ex -> case fromException ex of
  698. Just UserInterrupt -> return Nothing
  699. _ -> case fromException ex of
  700. Just ghce ->
  701. do liftIO (print (ghce :: GhcException))
  702. return Nothing
  703. _other -> liftIO (Exception.throwIO ex))
  704. getStmt
  705. lift $ getGHCiState >>= \st' -> setGHCiState st'{ prompt = p }
  706. -- the recursive call does not recycle parser state
  707. -- as we use a new string buffer
  708. case mb_stmt of
  709. Nothing -> return Nothing
  710. Just str -> if str == ""
  711. then return $ Just stmt
  712. else do
  713. checkInputForLayout (stmt++"\n"++str) getStmt
  714. where goToEnd = do
  715. eof <- Lexer.nextIsEOF
  716. if eof
  717. then Lexer.activeContext
  718. else Lexer.lexer return >> goToEnd
  719. enqueueCommands :: [String] -> GHCi ()
  720. enqueueCommands cmds = do
  721. st <- getGHCiState
  722. setGHCiState st{ cmdqueue = cmds ++ cmdqueue st }
  723. -- | If we one of these strings prefixes a command, then we treat it as a decl
  724. -- rather than a stmt.
  725. declPrefixes :: [String]
  726. declPrefixes = ["class ","data ","newtype ","type ","instance ", "deriving ",
  727. "foreign ", "default ", "default("]
  728. -- | Entry point to execute some haskell code from user
  729. runStmt :: String -> SingleStep -> GHCi Bool
  730. runStmt stmt step
  731. -- empty
  732. | null (filter (not.isSpace) stmt)
  733. = return False
  734. -- import
  735. | "import " `isPrefixOf` stmt
  736. = do addImportToContext stmt; return False
  737. -- data, class, newtype...
  738. | any (flip isPrefixOf stmt) declPrefixes
  739. = do _ <- liftIO $ tryIO $ hFlushAll stdin
  740. result <- GhciMonad.runDecls stmt
  741. afterRunStmt (const True) (GHC.RunOk result)
  742. | otherwise
  743. = do -- In the new IO library, read handles buffer data even if the Handle
  744. -- is set to NoBuffering. This causes problems for GHCi where there
  745. -- are really two stdin Handles. So we flush any bufferred data in
  746. -- GHCi's stdin Handle here (only relevant if stdin is attached to
  747. -- a file, otherwise the read buffer can't be flushed).
  748. _ <- liftIO $ tryIO $ hFlushAll stdin
  749. m_result <- GhciMonad.runStmt stmt step
  750. case m_result of
  751. Nothing -> return False
  752. Just result -> afterRunStmt (const True) result
  753. -- | Clean up the GHCi environment after a statement has run
  754. afterRunStmt :: (SrcSpan -> Bool) -> GHC.RunResult -> GHCi Bool
  755. afterRunStmt _ (GHC.RunException e) = liftIO $ Exception.throwIO e
  756. afterRunStmt step_here run_result = do
  757. resumes <- GHC.getResumeContext
  758. case run_result of
  759. GHC.RunOk names -> do
  760. show_types <- isOptionSet ShowType
  761. when show_types $ printTypeOfNames names
  762. GHC.RunBreak _ names mb_info
  763. | isNothing mb_info ||
  764. step_here (GHC.resumeSpan $ head resumes) -> do
  765. mb_id_loc <- toBreakIdAndLocation mb_info
  766. let bCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
  767. if (null bCmd)
  768. then printStoppedAtBreakInfo (head resumes) names
  769. else enqueueCommands [bCmd]
  770. -- run the command set with ":set stop <cmd>"
  771. st <- getGHCiState
  772. enqueueCommands [stop st]
  773. return ()
  774. | otherwise -> resume step_here GHC.SingleStep >>=
  775. afterRunStmt step_here >> return ()
  776. _ -> return ()
  777. flushInterpBuffers
  778. liftIO installSignalHandlers
  779. b <- isOptionSet RevertCAFs
  780. when b revertCAFs
  781. return (case run_result of GHC.RunOk _ -> True; _ -> False)
  782. toBreakIdAndLocation ::
  783. Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
  784. toBreakIdAndLocation Nothing = return Nothing
  785. toBreakIdAndLocation (Just inf) = do
  786. let md = GHC.breakInfo_module inf
  787. nm = GHC.breakInfo_number inf
  788. st <- getGHCiState
  789. return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
  790. breakModule loc == md,
  791. breakTick loc == nm ]
  792. printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
  793. printStoppedAtBreakInfo res names = do
  794. printForUser $ ptext (sLit "Stopped at") <+>
  795. ppr (GHC.resumeSpan res)
  796. -- printTypeOfNames session names
  797. let namesSorted = sortBy compareNames names
  798. tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
  799. docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
  800. printForUserPartWay $ vcat docs
  801. printTypeOfNames :: [Name] -> GHCi ()
  802. printTypeOfNames names
  803. = mapM_ (printTypeOfName ) $ sortBy compareNames names
  804. compareNames :: Name -> Name -> Ordering
  805. n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
  806. where compareWith n = (getOccString n, getSrcSpan n)
  807. printTypeOfName :: Name -> GHCi ()
  808. printTypeOfName n
  809. = do maybe_tything <- GHC.lookupName n
  810. case maybe_tything of
  811. Nothing -> return ()
  812. Just thing -> printTyThing thing
  813. data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
  814. -- | Entry point for execution a ':<command>' input from user
  815. specialCommand :: String -> InputT GHCi Bool
  816. specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
  817. specialCommand str = do
  818. let (cmd,rest) = break isSpace str
  819. maybe_cmd <- lift $ lookupCommand cmd
  820. htxt <- lift $ short_help `fmap` getGHCiState
  821. case maybe_cmd of
  822. GotCommand (_,f,_) -> f (dropWhile isSpace rest)
  823. BadCommand ->
  824. do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
  825. ++ htxt)
  826. return False
  827. NoLastCommand ->
  828. do liftIO $ hPutStr stdout ("there is no last command to perform\n"
  829. ++ htxt)
  830. return False
  831. shellEscape :: String -> GHCi Bool
  832. shellEscape str = liftIO (system str >> return False)
  833. lookupCommand :: String -> GHCi (MaybeCommand)
  834. lookupCommand "" = do
  835. st <- getGHCiState
  836. case last_command st of
  837. Just c -> return $ GotCommand c
  838. Nothing -> return NoLastCommand
  839. lookupCommand str = do
  840. mc <- lookupCommand' str
  841. st <- getGHCiState
  842. setGHCiState st{ last_command = mc }
  843. return $ case mc of
  844. Just c -> GotCommand c
  845. Nothing -> BadCommand
  846. lookupCommand' :: String -> GHCi (Maybe Command)
  847. lookupCommand' ":" = return Nothing
  848. lookupCommand' str' = do
  849. macros <- liftIO $ readIORef macros_ref
  850. ghci_cmds <- ghci_commands `fmap` getGHCiState
  851. let{ (str, cmds) = case str' of
  852. ':' : rest -> (rest, ghci_cmds) -- "::" selects a builtin command
  853. _ -> (str', ghci_cmds ++ macros) } -- otherwise prefer macros
  854. -- look for exact match first, then the first prefix match
  855. return $ case [ c | c <- cmds, str == cmdName c ] of
  856. c:_ -> Just c
  857. [] -> case [ c | c@(s,_,_) <- cmds, str `isPrefixOf` s ] of
  858. [] -> Nothing
  859. c:_ -> Just c
  860. getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
  861. getCurrentBreakSpan = do
  862. resumes <- GHC.getResumeContext
  863. case resumes of
  864. [] -> return Nothing
  865. (r:_) -> do
  866. let ix = GHC.resumeHistoryIx r
  867. if ix == 0
  868. then return (Just (GHC.resumeSpan r))
  869. else do
  870. let hist = GHC.resumeHistory r !! (ix-1)
  871. pan <- GHC.getHistorySpan hist
  872. return (Just pan)
  873. getCurrentBreakModule :: GHCi (Maybe Module)
  874. getCurrentBreakModule = do
  875. resumes <- GHC.getResumeContext
  876. case resumes of
  877. [] -> return Nothing
  878. (r:_) -> do
  879. let ix = GHC.resumeHistoryIx r
  880. if ix == 0
  881. then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
  882. else do
  883. let hist = GHC.resumeHistory r !! (ix-1)
  884. return $ Just $ GHC.getHistoryModule hist
  885. -----------------------------------------------------------------------------
  886. --
  887. -- Commands
  888. --
  889. -----------------------------------------------------------------------------
  890. noArgs :: GHCi () -> String -> GHCi ()
  891. noArgs m "" = m
  892. noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
  893. withSandboxOnly :: String -> GHCi () -> GHCi ()
  894. withSandboxOnly cmd this = do
  895. dflags <- getDynFlags
  896. if not (gopt Opt_GhciSandbox dflags)
  897. then printForUser (text cmd <+>
  898. ptext (sLit "is not supported with -fno-ghci-sandbox"))
  899. else this
  900. -----------------------------------------------------------------------------
  901. -- :help
  902. help :: String -> GHCi ()
  903. help _ = do
  904. txt <- long_help `fmap` getGHCiState
  905. liftIO $ putStr txt
  906. -----------------------------------------------------------------------------
  907. -- :info
  908. info :: Bool -> String -> InputT GHCi ()
  909. info _ "" = throwGhcException (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
  910. info allInfo s = handleSourceError GHC.printException $ do
  911. unqual <- GHC.getPrintUnqual
  912. dflags <- getDynFlags
  913. sdocs <- mapM (infoThing allInfo) (words s)
  914. mapM_ (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs
  915. infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
  916. infoThing allInfo str = do
  917. dflags <- getDynFlags
  918. let pefas = gopt Opt_PrintExplicitForalls dflags
  919. names <- GHC.parseName str
  920. mb_stuffs <- mapM (GHC.getInfo allInfo) names
  921. let filtered = filterOutChildren (\(t,_f,_ci,_fi) -> t) (catMaybes mb_stuffs)
  922. return $ vcat (intersperse (text "") $ map (pprInfo pefas) filtered)
  923. -- Filter out names whose parent is also there Good
  924. -- example is '[]', which is both a type and data
  925. -- constructor in the same type
  926. filterOutChildren :: (a -> TyThing) -> [a] -> [a]
  927. filterOutChildren get_thing xs
  928. = filterOut has_parent xs
  929. where
  930. all_names = mkNameSet (map (getName . get_thing) xs)
  931. has_parent x = case tyThingParent_maybe (get_thing x) of
  932. Just p -> getName p `elemNameSet` all_names
  933. Nothing -> False
  934. pprInfo :: PrintExplicitForalls
  935. -> (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
  936. pprInfo pefas (thing, fixity, cls_insts, fam_insts)
  937. = pprTyThingInContextLoc pefas thing
  938. $$ show_fixity
  939. $$ vcat (map GHC.pprInstance cls_insts)
  940. $$ vcat (map GHC.pprFamInst fam_insts)
  941. where
  942. show_fixity
  943. | fixity == GHC.defaultFixity = empty
  944. | otherwise = ppr fixity <+> pprInfixName (GHC.getName thing)
  945. -----------------------------------------------------------------------------
  946. -- :main
  947. runMain :: String -> GHCi ()
  948. runMain s = case toArgs s of
  949. Left err -> liftIO (hPutStrLn stderr err)
  950. Right args ->
  951. do dflags <- getDynFlags
  952. case mainFunIs dflags of
  953. Nothing -> doWithArgs args "main"
  954. Just f -> doWithArgs args f
  955. -----------------------------------------------------------------------------
  956. -- :run
  957. runRun :: String -> GHCi ()
  958. runRun s = case toCmdArgs s of
  959. Left err -> liftIO (hPutStrLn stderr err)
  960. Right (cmd, args) -> doWithArgs args cmd
  961. doWithArgs :: [String] -> String -> GHCi ()
  962. doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
  963. show args ++ " (" ++ cmd ++ ")"]
  964. -----------------------------------------------------------------------------
  965. -- :cd
  966. changeDirectory :: String -> InputT GHCi ()
  967. changeDirectory "" = do
  968. -- :cd on its own changes to the user's home directory
  969. either_dir <- liftIO $ tryIO getHomeDirectory
  970. case either_dir of
  971. Left _e -> return ()
  972. Right dir -> changeDirectory dir
  973. changeDirectory dir = do
  974. graph <- GHC.getModuleGraph
  975. when (not (null graph)) $
  976. liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
  977. GHC.setTargets []
  978. _ <- GHC.load LoadAllTargets
  979. lift $ setContextAfterLoad False []
  980. GHC.workingDirectoryChanged
  981. dir' <- expandPath dir
  982. liftIO $ setCurrentDirectory dir'
  983. trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
  984. trySuccess act =
  985. handleSourceError (\e -> do GHC.printException e
  986. return Failed) $ do
  987. act
  988. -----------------------------------------------------------------------------
  989. -- :edit
  990. editFile :: String -> InputT GHCi ()
  991. editFile str =
  992. do file <- if null str then lift chooseEditFile else return str
  993. st <- lift getGHCiState
  994. let cmd = editor st
  995. when (null cmd)
  996. $ throwGhcException (CmdLineError "editor not set, use :set editor")
  997. code <- liftIO $ system (cmd ++ ' ':file)
  998. when (code == ExitSuccess)
  999. $ reloadModule ""
  1000. -- The user didn't specify a file so we pick one for them.
  1001. -- Our strategy is to pick the first module that failed to load,
  1002. -- or otherwise the first target.
  1003. --
  1004. -- XXX: Can we figure out what happened if the depndecy analysis fails
  1005. -- (e.g., because the porgrammeer mistyped the name of a module)?
  1006. -- XXX: Can we figure out the location of an error to pass to the editor?
  1007. -- XXX: if we could figure out the list of errors that occured during the
  1008. -- last load/reaload, then we could start the editor focused on the first
  1009. -- of those.
  1010. chooseEditFile :: GHCi String
  1011. chooseEditFile =
  1012. do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
  1013. graph <- GHC.getModuleGraph
  1014. failed_graph <- filterM hasFailed graph
  1015. let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
  1016. pick xs = case xs of
  1017. x : _ -> GHC.ml_hs_file (GHC.ms_location x)
  1018. _ -> Nothing
  1019. case pick (order failed_graph) of
  1020. Just file -> return file
  1021. Nothing ->
  1022. do targets <- GHC.getTargets
  1023. case msum (map fromTarget targets) of
  1024. Just file -> return file
  1025. Nothing -> throwGhcException (CmdLineError "No files to edit.")
  1026. where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
  1027. fromTarget _ = Nothing -- when would we get a module target?
  1028. -----------------------------------------------------------------------------
  1029. -- :def
  1030. defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
  1031. defineMacro _ (':':_) =
  1032. liftIO $ putStrLn "macro name cannot start with a colon"
  1033. defineMacro overwrite s = do
  1034. let (macro_name, definition) = break isSpace s
  1035. macros <- liftIO (readIORef macros_ref)
  1036. let defined = map cmdName macros
  1037. if (null macro_name)
  1038. then if null defined
  1039. then liftIO $ putStrLn "no macros defined"
  1040. else liftIO $ putStr ("the following macros are defined:\n" ++
  1041. unlines defined)
  1042. else do
  1043. if (not overwrite && macro_name `elem` defined)
  1044. then throwGhcException (CmdLineError
  1045. ("macro '" ++ macro_name ++ "' is already defined"))
  1046. else do
  1047. let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
  1048. -- give the expression a type signature, so we can be sure we're getting
  1049. -- something of the right type.
  1050. let new_expr = '(' : definition ++ ") :: String -> IO String"
  1051. -- compile the expression
  1052. handleSourceError (\e -> GHC.printException e) $
  1053. do
  1054. hv <- GHC.compileExpr new_expr
  1055. liftIO (writeIORef macros_ref -- later defined macros have precedence
  1056. ((macro_name, lift . runMacro hv, noCompletion) : filtered))
  1057. runMacro :: GHC.HValue{-String -> IO String-} -> String -> GHCi Bool
  1058. runMacro fun s = do
  1059. str <- liftIO ((unsafeCoerce# fun :: String -> IO String) s)
  1060. -- make sure we force any exceptions in the result, while we are still
  1061. -- inside the exception handler for commands:
  1062. seqList str (return ())
  1063. enqueueCommands (lines str)
  1064. return False
  1065. -----------------------------------------------------------------------------
  1066. -- :undef
  1067. undefineMacro :: String -> GHCi ()
  1068. undefineMacro str = mapM_ undef (words str)
  1069. where undef macro_name = do
  1070. cmds <- liftIO (readIORef macros_ref)
  1071. if (macro_name `notElem` map cmdName cmds)
  1072. then throwGhcException (CmdLineError
  1073. ("macro '" ++ macro_name ++ "' is not defined"))
  1074. else do
  1075. liftIO (writeIORef macros_ref (filter ((/= macro_name) . cmdName) cmds))
  1076. -----------------------------------------------------------------------------
  1077. -- :cmd
  1078. cmdCmd :: String -> GHCi ()
  1079. cmdCmd str = do
  1080. let expr = '(' : str ++ ") :: IO String"
  1081. handleSourceError (\e -> GHC.printException e) $
  1082. do
  1083. hv <- GHC.compileExpr expr
  1084. cmds <- liftIO $ (unsafeCoerce# hv :: IO String)
  1085. enqueueCommands (lines cmds)
  1086. return ()
  1087. -----------------------------------------------------------------------------
  1088. -- :check
  1089. checkModule :: String -> InputT GHCi ()
  1090. checkModule m = do
  1091. let modl = GHC.mkModuleName m
  1092. ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
  1093. r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
  1094. dflags <- getDynFlags
  1095. liftIO $ putStrLn $ showSDoc dflags $
  1096. case GHC.moduleInfo r of
  1097. cm | Just scope <- GHC.modInfoTopLevelScope cm ->
  1098. let
  1099. (loc, glob) = ASSERT( all isExternalName scope )
  1100. partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
  1101. in
  1102. (text "global names: " <+> ppr glob) $$
  1103. (text "local names: " <+> ppr loc)
  1104. _ -> empty
  1105. return True
  1106. afterLoad (successIf ok) False
  1107. -----------------------------------------------------------------------------
  1108. -- :load, :add, :reload
  1109. loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
  1110. loadModule fs = timeIt (loadModule' fs)
  1111. loadModule_ :: [FilePath] -> InputT GHCi ()
  1112. loadModule_ fs = loadModule (zip fs (repeat Nothing)) >> return ()
  1113. loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
  1114. loadModule' files = do
  1115. let (filenames, phases) = unzip files
  1116. exp_filenames <- mapM expandPath filenames
  1117. let files' = zip exp_filenames phases
  1118. targets <- mapM (uncurry GHC.guessTarget) files'
  1119. -- NOTE: we used to do the dependency anal first, so that if it
  1120. -- fails we didn't throw away the current set of modules. This would
  1121. -- require some re-working of the GHC interface, so we'll leave it
  1122. -- as a ToDo for now.
  1123. -- unload first
  1124. _ <- GHC.abandonAll
  1125. lift discardActiveBreakPoints
  1126. GHC.setTargets []
  1127. _ <- GHC.load LoadAllTargets
  1128. GHC.setTargets targets
  1129. doLoad False LoadAllTargets
  1130. -- :add
  1131. addModule :: [FilePath] -> InputT GHCi ()
  1132. addModule files = do
  1133. lift revertCAFs -- always revert CAFs on load/add.
  1134. files' <- mapM expandPath files
  1135. targets <- mapM (\m -> GHC.guessTarget m Nothing) files'
  1136. -- remove old targets with the same id; e.g. for :add *M
  1137. mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
  1138. mapM_ GHC.addTarget targets
  1139. _ <- doLoad False LoadAllTargets
  1140. return ()
  1141. -- :reload
  1142. reloadModule :: String -> InputT GHCi ()
  1143. reloadModule m = do
  1144. _ <- doLoad True $
  1145. if null m then LoadAllTargets
  1146. else LoadUpTo (GHC.mkModuleName m)
  1147. return ()
  1148. doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
  1149. doLoad retain_context howmuch = do
  1150. -- turn off breakpoints before we load: we can't turn them off later, because
  1151. -- the ModBreaks will have gone away.
  1152. lift discardActiveBreakPoints
  1153. ok <- trySuccess $ GHC.load howmuch
  1154. afterLoad ok retain_context
  1155. return ok
  1156. afterLoad :: SuccessFlag
  1157. -> Bool -- keep the remembered_ctx, as far as possible (:reload)
  1158. -> InputT GHCi ()
  1159. afterLoad ok retain_context = do
  1160. lift revertCAFs -- always revert CAFs on load.
  1161. lift discardTickArrays
  1162. loaded_mod_summaries <- getLoadedModules
  1163. let loaded_mods = map GHC.ms_mod loaded_mod_summaries
  1164. loaded_mod_names = map GHC.moduleName loaded_mods
  1165. modulesLoadedMsg ok loaded_mod_names
  1166. lift $ setContextAfterLoad retain_context loaded_mod_summaries
  1167. setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
  1168. setContextAfterLoad keep_ctxt [] = do
  1169. setContextKeepingPackageModules keep_ctxt []
  1170. setContextAfterLoad keep_ctxt ms = do
  1171. -- load a target if one is available, otherwise load the topmost module.
  1172. targets <- GHC.getTargets
  1173. case [ m | Just m <- map (findTarget ms) targets ] of
  1174. [] ->
  1175. let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
  1176. load_this (last graph')
  1177. (m:_) ->
  1178. load_this m
  1179. where
  1180. findTarget mds t
  1181. = case filter (`matches` t) mds of
  1182. [] -> Nothing
  1183. (m:_) -> Just m
  1184. summary `matches` Target (TargetModule m) _ _
  1185. = GHC.ms_mod_name summary == m
  1186. summary `matches` Target (TargetFile f _) _ _
  1187. | Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
  1188. _ `matches` _
  1189. = False
  1190. load_this summary | m <- GHC.ms_mod summary = do
  1191. is_interp <- GHC.moduleIsInterpreted m
  1192. dflags <- getDynFlags
  1193. let star_ok = is_interp && not (safeLanguageOn dflags)
  1194. -- We import the module with a * iff
  1195. -- - it is interpreted, and
  1196. -- - -XSafe is off (it doesn't allow *-imports)
  1197. let new_ctx | star_ok = [mkIIModule (GHC.moduleName m)]
  1198. | otherwise = [mkIIDecl (GHC.moduleName m)]
  1199. setContextKeepingPackageModules keep_ctxt new_ctx
  1200. -- | Keep any package modules (except Prelude) when changing the context.
  1201. setContextKeepingPackageModules
  1202. :: Bool -- True <=> keep all of remembered_ctx
  1203. -- False <=> just keep package imports
  1204. -> [InteractiveImport] -- new context
  1205. -> GHCi ()
  1206. setContextKeepingPackageModules keep_ctx trans_ctx = do
  1207. st <- getGHCiState
  1208. let rem_ctx = remembered_ctx st
  1209. new_rem_ctx <- if keep_ctx then return rem_ctx
  1210. else keepPackageImports rem_ctx
  1211. setGHCiState st{ remembered_ctx = new_rem_ctx,
  1212. transient_ctx = filterSubsumed new_rem_ctx trans_ctx }
  1213. setGHCContextFromGHCiState
  1214. keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
  1215. keepPackageImports = filterM is_pkg_import
  1216. where
  1217. is_pkg_import :: InteractiveImport -> GHCi Bool
  1218. is_pkg_import (IIModule _) = return False
  1219. is_pkg_import (IIDecl d)
  1220. = do e <- gtry $ GHC.findModule mod_name (ideclPkgQual d)
  1221. case e :: Either SomeException Module of
  1222. Left _ -> return False
  1223. Right m -> return (not (isHomeModule m))
  1224. where
  1225. mod_name = unLoc (ideclName d)
  1226. modulesLoadedMsg :: SuccessFlag -> [ModuleName] -> InputT GHCi ()
  1227. modulesLoadedMsg ok mods = do
  1228. dflags <- getDynFlags
  1229. when (verbosity dflags > 0) $ do
  1230. let mod_commas
  1231. | null mods = text "none."
  1232. | otherwise = hsep (
  1233. punctuate comma (map ppr mods)) <> text "."
  1234. case ok of
  1235. Failed ->
  1236. liftIO $ putStrLn $ showSDoc dflags (text "Failed, modules loaded: " <> mod_commas)
  1237. Succeeded ->
  1238. liftIO $ putStrLn $ showSDoc dflags (text "Ok, modules loaded: " <> mod_commas)
  1239. -----------------------------------------------------------------------------
  1240. -- :type
  1241. typeOfExpr :: String -> InputT GHCi ()
  1242. typeOfExpr str
  1243. = handleSourceError GHC.printException
  1244. $ do
  1245. ty <- GHC.exprType str
  1246. dflags <- getDynFlags
  1247. let pefas = gopt Opt_PrintExplicitForalls dflags
  1248. printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser pefas ty)]
  1249. -----------------------------------------------------------------------------
  1250. -- :kind
  1251. kindOfType :: Bool -> String -> InputT GHCi ()
  1252. kindOfType norm str
  1253. = handleSourceError GHC.printException
  1254. $ do
  1255. (ty, kind) <- GHC.typeKind norm str
  1256. dflags <- getDynFlags
  1257. let pefas = gopt Opt_PrintExplicitForalls dflags
  1258. printForUser $ vcat [ text str <+> dcolon <+> pprTypeForUser pefas kind
  1259. , ppWhen norm $ equals <+> ppr ty ]
  1260. -----------------------------------------------------------------------------
  1261. -- :quit
  1262. quit :: String -> InputT GHCi Bool
  1263. quit _ = return True
  1264. -----------------------------------------------------------------------------
  1265. -- :script
  1266. -- running a script file #1363
  1267. scriptCmd :: String -> InputT GHCi ()
  1268. scriptCmd ws = do
  1269. case words ws of
  1270. [s] -> runScript s
  1271. _ -> throwGhcException (CmdLineError "syntax: :script <filename>")
  1272. runScript :: String -- ^ filename
  1273. -> InputT GHCi ()
  1274. runScript filename = do
  1275. either_script <- liftIO $ tryIO (openFile filename ReadMode)
  1276. case either_script of
  1277. Left _err -> throwGhcException (CmdLineError $ "IO error: \""++filename++"\" "
  1278. ++(ioeGetErrorString _err))
  1279. Right script -> do
  1280. st <- lift $ getGHCiState
  1281. let prog = progname st
  1282. line = line_number st
  1283. lift $ setGHCiState st{progname=filename,line_number=0}
  1284. scriptLoop script
  1285. liftIO $ hClose script
  1286. new_st <- lift $ getGHCiState
  1287. lift $ setGHCiState new_st{progname=prog,line_number=line}
  1288. where scriptLoop script = do
  1289. res <- runOneCommand handler $ fileLoop script
  1290. case res of
  1291. Nothing -> return ()
  1292. Just s -> if s
  1293. then scriptLoop script
  1294. else return ()
  1295. -----------------------------------------------------------------------------
  1296. -- :issafe
  1297. -- Displaying Safe Haskell properties of a module
  1298. isSafeCmd :: String -> InputT GHCi ()
  1299. isSafeCmd m =
  1300. case words m of
  1301. [s] | looksLikeModuleName s -> do
  1302. md <- lift $ lookupModule s
  1303. isSafeModule md
  1304. [] -> do md <- guessCurrentModule "issafe"
  1305. isSafeModule md
  1306. _ -> throwGhcException (CmdLineError "syntax: :issafe <module>")
  1307. isSafeModule :: Module -> InputT GHCi ()
  1308. isSafeModule m = do
  1309. mb_mod_info <- GHC.getModuleInfo m
  1310. when (isNothing mb_mod_info)
  1311. (throwGhcException $ CmdLineError $ "unknown module: " ++ mname)
  1312. dflags <- getDynFlags
  1313. let iface = GHC.modInfoIface $ fromJust mb_mod_info
  1314. when (isNothing iface)
  1315. (throwGhcException $ CmdLineError $ "can't load interface file for module: " ++
  1316. (GHC.moduleNameString $ GHC.moduleName m))
  1317. (msafe, pkgs) <- GHC.moduleTrustReqs m
  1318. let trust = showPpr dflags $ getSafeMode $ GHC.mi_trust $ fromJust iface
  1319. pkg = if packageTrusted dflags m then "trusted" else "untrusted"
  1320. (good, bad) = tallyPkgs dflags pkgs
  1321. -- print info to user...
  1322. liftIO $ putStrLn $ "Trust type is (Module: " ++ trust ++ ", Package: " ++ pkg ++ ")"
  1323. liftIO $ putStrLn $ "Package Trust: " ++ (if packageTrustOn dflags then "On" else "Off")
  1324. when (not $ null good)
  1325. (liftIO $ putStrLn $ "Trusted package dependencies (trusted): " ++
  1326. (intercalate ", " $ map packageIdString good))
  1327. case msafe && null bad of
  1328. True -> liftIO $ putStrLn $ mname ++ " is trusted!"
  1329. False -> do
  1330. when (not $ null bad)
  1331. (liftIO $ putStrLn $ "Trusted package dependencies (untrusted): "
  1332. ++ (intercalate ", " $ map packageIdString bad))
  1333. liftIO $ putStrLn $ mname ++ " is NOT trusted!"
  1334. where
  1335. mname = GHC.moduleNameString $ GHC.moduleName m
  1336. packageTrusted dflags md
  1337. | thisPackage dflags == modulePackageId md = True
  1338. | otherwise = trusted $ getPackageDetails (pkgState dflags) (modulePackageId md)
  1339. tallyPkgs dflags deps | not (packageTrustOn dflags) = ([], [])
  1340. | otherwise = partition part deps
  1341. where state = pkgState dflags
  1342. part pkg = trusted $ getPackageDetails state pkg
  1343. -----------------------------------------------------------------------------
  1344. -- :browse
  1345. -- Browsing a module's contents
  1346. browseCmd :: Bool -> String -> InputT GHCi ()
  1347. browseCmd bang m =
  1348. case words m of
  1349. ['*':s] | looksLikeModuleName s -> do
  1350. md <- lift $ wantInterpretedModule s
  1351. browseModule bang md False
  1352. [s] | looksLikeModuleName s -> do
  1353. md <- lift $ lookupModule s
  1354. browseModule bang md True
  1355. [] -> do md <- guessCurrentModule ("browse" ++ if bang then "!" else "")
  1356. browseModule bang md True
  1357. _ -> throwGhcException (CmdLineError "syntax: :browse <module>")
  1358. guessCurrentModule :: String -> InputT GHCi Module
  1359. -- Guess which module the user wants to browse. Pick
  1360. -- modules that are interpreted first. The most
  1361. -- recently-added module occurs last, it seems.
  1362. guessCurrentModule cmd
  1363. = do imports <- GHC.getContext
  1364. when (null imports) $ throwGhcException $
  1365. CmdLineError (':' : cmd ++ ": no current module")
  1366. case (head imports) of
  1367. IIModule m -> GHC.findModule m Nothing
  1368. IIDecl d -> GHC.findModule (unLoc (ideclName d)) (ideclPkgQual d)
  1369. -- without bang, show items in context of their parents and omit children
  1370. -- with bang, show class methods and data constructors separately, and
  1371. -- indicate import modules, to aid qualifying unqualified names
  1372. -- with sorted, sort items alphabetically
  1373. browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
  1374. browseModule bang modl exports_only = do
  1375. -- :browse reports qualifiers wrt current context
  1376. unqual <- GHC.getPrintUnqual
  1377. mb_mod_info <- GHC.getModuleInfo modl
  1378. case mb_mod_info of
  1379. Nothing -> throwGhcException (CmdLineError ("unknown module: " ++
  1380. GHC.moduleNameString (GHC.moduleName modl)))
  1381. Just mod_info -> do
  1382. dflags <- getDynFlags
  1383. let names
  1384. | exports_only = GHC.modInfoExports mod_info
  1385. | otherwise = GHC.modInfoTopLevelScope mod_info
  1386. `orElse` []
  1387. -- sort alphabetically name, but putting locally-defined
  1388. -- identifiers first. We would like to improve this; see #1799.
  1389. sorted_names = loc_sort local ++ occ_sort external
  1390. where
  1391. (local,external) = ASSERT( all isExternalName names )
  1392. partition ((==modl) . nameModule) names
  1393. occ_sort = sortBy (compare `on` nameOccName)
  1394. -- try to sort by src location. If the first name in our list
  1395. -- has a good source location, then they all should.
  1396. loc_sort ns
  1397. | n:_ <- ns, isGoodSrcSpan (nameSrcSpan n)
  1398. = sortBy (compare `on` nameSrcSpan) ns
  1399. | otherwise
  1400. = occ_sort ns
  1401. mb_things <- mapM GHC.lookupName sorted_names
  1402. let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
  1403. rdr_env <- GHC.getGRE
  1404. let pefas = gopt Opt_PrintExplicitForalls dflags
  1405. things | bang = catMaybes mb_things
  1406. | otherwise = filtered_things
  1407. pretty | bang = pprTyThing
  1408. | otherwise = pprTyThingInContext
  1409. labels [] = text "-- not currently imported"
  1410. labels l = text $ intercalate "\n" $ map qualifier l
  1411. qualifier :: Maybe [ModuleName] -> String
  1412. qualifier = maybe "-- defined locally"
  1413. (("-- imported via "++) . intercalate ", "
  1414. . map GHC.moduleNameString)
  1415. importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
  1416. modNames :: [[Maybe [ModuleName]]]
  1417. modNames = map (importInfo . GHC.getName) things
  1418. -- annotate groups of imports with their import modules
  1419. -- the default ordering is somewhat arbitrary, so we group
  1420. -- by header and sort groups; the names themselves should
  1421. -- really come in order of source appearance.. (trac #1799)
  1422. annotate mts = concatMap (\(m,ts)->labels m:ts)
  1423. $ sortBy cmpQualifiers $ grp mts
  1424. where cmpQualifiers =
  1425. compare `on` (map (fmap (map moduleNameFS)) . fst)
  1426. grp [] = []
  1427. grp mts@((m,_):_) = (m,map snd g) : grp ng
  1428. where (g,ng) = partition ((==m).fst) mts
  1429. let prettyThings, prettyThings' :: [SDoc]
  1430. prettyThings = map (pretty pefas) things
  1431. prettyThings' | bang = annotate $ zip modNames prettyThings
  1432. | otherwise = prettyThings
  1433. liftIO $ putStrLn $ showSDocForUser dflags unqual (vcat prettyThings')
  1434. -- ToDo: modInfoInstances currently throws an exception for
  1435. -- package modules. When it works, we can do this:
  1436. -- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
  1437. -----------------------------------------------------------------------------
  1438. -- :module
  1439. -- Setting the module context. For details on context handling see
  1440. -- "remembered_ctx" and "transient_ctx" in GhciMonad.
  1441. moduleCmd :: String -> GHCi ()
  1442. moduleCmd str
  1443. | all sensible strs = cmd
  1444. | otherwise = throwGhcException (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
  1445. where
  1446. (cmd, strs) =
  1447. case str of
  1448. '+':stuff -> rest addModulesToContext stuff
  1449. '-':stuff -> rest remModulesFromContext stuff
  1450. stuff -> rest setContext stuff
  1451. rest op stuff = (op as bs, stuffs)
  1452. where (as,bs) = partitionWith starred stuffs
  1453. stuffs = words stuff
  1454. sensible ('*':m) = looksLikeModuleName m
  1455. sensible m = looksLikeModuleName m
  1456. starred ('*':m) = Left (GHC.mkModuleName m)
  1457. starred m = Right (GHC.mkModuleName m)
  1458. -- -----------------------------------------------------------------------------
  1459. -- Four ways to manipulate the context:
  1460. -- (a) :module +<stuff>: addModulesToContext
  1461. -- (b) :module -<stuff>: remModulesFromContext
  1462. -- (c) :module <stuff>: setContext
  1463. -- (d) import <module>...: addImportToContext
  1464. addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
  1465. addModulesToContext starred unstarred = restoreContextOnFailure $ do
  1466. addModulesToContext_ starred unstarred
  1467. addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
  1468. addModulesToContext_ starred unstarred = do
  1469. mapM_ addII (map mkIIModule starred ++ map mkIIDecl unstarred)
  1470. setGHCContextFromGHCiState
  1471. remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
  1472. remModulesFromContext starred unstarred = do
  1473. -- we do *not* call restoreContextOnFailure here. If the user
  1474. -- is trying to fix up a context that contains errors by removing
  1475. -- modules, we don't want GHC to silently put them back in again.
  1476. mapM_ rm (starred ++ unstarred)
  1477. setGHCContextFromGHCiState
  1478. where
  1479. rm :: ModuleName -> GHCi ()
  1480. rm str = do
  1481. m <- moduleName <$> lookupModuleName str
  1482. let filt = filter ((/=) m . iiModuleName)
  1483. modifyGHCiState $ \st ->
  1484. st { remembered_ctx = filt (remembered_ctx st)
  1485. , transient_ctx = filt (transient_ctx st) }
  1486. setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
  1487. setContext starred unstarred = restoreContextOnFailure $ do
  1488. modifyGHCiState $ \st -> st { remembered_ctx = [], transient_ctx = [] }
  1489. -- delete the transient context
  1490. addModulesToContext_ starred unstarred
  1491. addImportToContext :: String -> GHCi ()
  1492. addImportToContext str = restoreContextOnFailure $ do
  1493. idecl <- GHC.parseImportDecl str
  1494. addII (IIDecl idecl) -- #5836
  1495. setGHCContextFromGHCiState
  1496. -- Util used by addImportToContext and addModulesToContext
  1497. addII :: InteractiveImport -> GHCi ()
  1498. addII iidecl = do
  1499. checkAdd iidecl
  1500. modifyGHCiState $ \st ->
  1501. st { remembered_ctx = addNotSubsumed iidecl (remembered_ctx st)
  1502. , transient_ctx = filter (not . (iidecl `iiSubsumes`))
  1503. (transient_ctx st)
  1504. }
  1505. -- Sometimes we can't tell whether an import is valid or not until
  1506. -- we finally call 'GHC.setContext'. e.g.
  1507. --
  1508. -- import System.IO (foo)
  1509. --
  1510. -- will fail because System.IO does not export foo. In this case we
  1511. -- don't want to store the import in the context permanently, so we
  1512. -- catch the failure from 'setGHCContextFromGHCiState' and set the
  1513. -- context back to what it was.
  1514. --
  1515. -- See #6007
  1516. --
  1517. restoreContextOnFailure :: GHCi a -> GHCi a
  1518. restoreContextOnFailure do_this = do
  1519. st <- getGHCiState
  1520. let rc = remembered_ctx st; tc = transient_ctx st
  1521. do_this `gonException` (modifyGHCiState $ \st' ->
  1522. st' { remembered_ctx = rc, transient_ctx = tc })
  1523. -- -----------------------------------------------------------------------------
  1524. -- Validate a module that we want to add to the context
  1525. checkAdd :: InteractiveImport -> GHCi ()
  1526. checkAdd ii = do
  1527. dflags <- getDynFlags
  1528. let safe = safeLanguageOn dflags
  1529. case ii of
  1530. IIModule modname
  1531. | safe -> throwGhcException $ CmdLineError "can't use * imports with Safe Haskell"
  1532. | otherwise -> wantInterpretedModuleName modname >> return ()
  1533. IIDecl d -> do
  1534. let modname = unLoc (ideclName d)
  1535. pkgqual = ideclPkgQual d
  1536. m <- GHC.lookupModule modname pkgqual
  1537. when safe $ do
  1538. t <- GHC.isModuleTrusted m
  1539. when (not t) $ throwGhcException $ ProgramError $ ""
  1540. -- -----------------------------------------------------------------------------
  1541. -- Update the GHC API's view of the context
  1542. -- | Sets the GHC context from the GHCi state. The GHC context is
  1543. -- always set this way, we never modify it incrementally.
  1544. --
  1545. -- We ignore any imports for which the ModuleName does not currently
  1546. -- exist. This is so that the remembered_ctx can contain imports for
  1547. -- modules that are not currently loaded, perhaps because we just did
  1548. -- a :reload and encountered errors.
  1549. --
  1550. -- Prelude is added if not already present in the list. Therefore to
  1551. -- override the implicit Prelude import you can say 'import Prelude ()'
  1552. -- at the prompt, just as in Haskell source.
  1553. --
  1554. setGHCContextFromGHCiState :: GHCi ()
  1555. setGHCContextFromGHCiState = do
  1556. st <- getGHCiState
  1557. -- re-use checkAdd to check whether the module is valid. If the
  1558. -- module does not exist, we do *not* want to print an error
  1559. -- here, we just want to silently keep the module in the context
  1560. -- until such time as the module reappears again. So we ignore
  1561. -- the actual exception thrown by checkAdd, using tryBool to
  1562. -- turn it into a Bool.
  1563. iidecls <- filterM (tryBool.checkAdd) (transient_ctx st ++ remembered_ctx st)
  1564. dflags <- GHC.getSessionDynFlags
  1565. GHC.setContext $
  1566. if xopt Opt_ImplicitPrelude dflags && not (any isPreludeImport iidecls)
  1567. then iidecls ++ [implicitPreludeImport]
  1568. else iidecls
  1569. -- XXX put prel at the end, so that guessCurrentModule doesn't pick it up.
  1570. -- -----------------------------------------------------------------------------
  1571. -- Utils on InteractiveImport
  1572. mkIIModule :: ModuleName -> InteractiveImport
  1573. mkIIModule = IIModule
  1574. mkIIDecl :: ModuleName -> InteractiveImport
  1575. mkIIDecl = IIDecl . simpleImportDecl
  1576. iiModules :: [InteractiveImport] -> [ModuleName]
  1577. iiModules is = [m | IIModule m <- is]
  1578. iiModuleName :: InteractiveImport -> ModuleName
  1579. iiModuleName (IIModule m) = m
  1580. iiModuleName (IIDecl d) = unLoc (ideclName d)
  1581. preludeModuleName :: ModuleName
  1582. preludeModuleName = GHC.mkModuleName "Prelude"
  1583. implicitPreludeImport :: InteractiveImport
  1584. implicitPreludeImport = IIDecl (simpleImportDecl preludeModuleName)
  1585. isPreludeImport :: InteractiveImport -> Bool
  1586. isPreludeImport (IIModule {}) = True
  1587. isPreludeImport (IIDecl d) = unLoc (ideclName d) == preludeModuleName
  1588. addNotSubsumed :: InteractiveImport
  1589. -> [InteractiveImport] -> [InteractiveImport]
  1590. addNotSubsumed i is
  1591. | any (`iiSubsumes` i) is = is
  1592. | otherwise = i : filter (not . (i `iiSubsumes`)) is
  1593. -- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
  1594. -- by any of @is@.
  1595. filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
  1596. -> [InteractiveImport]
  1597. filterSubsumed is js = filter (\j -> not (any (`iiSubsumes` j) is)) js
  1598. -- | Returns True if the left import subsumes the right one. Doesn't
  1599. -- need to be 100% accurate, conservatively returning False is fine.
  1600. -- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
  1601. -- plusProv will ensue (#5904))
  1602. --
  1603. -- Note that an IIModule does not necessarily subsume an IIDecl,
  1604. -- because e.g. a module might export a name that is only available
  1605. -- qualified within the module itself.
  1606. --
  1607. -- Note that 'import M' does not necessarily subsume 'import M(foo)',
  1608. -- because M might not export foo and we want an error to be produced
  1609. -- in that case.
  1610. --
  1611. iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
  1612. iiSubsumes (IIModule m1) (IIModule m2) = m1==m2
  1613. iiSubsumes (IIDecl d1) (IIDecl d2) -- A bit crude
  1614. = unLoc (ideclName d1) == unLoc (ideclName d2)
  1615. && ideclAs d1 == ideclAs d2
  1616. && (not (ideclQualified d1) || ideclQualified d2)
  1617. && (ideclHiding d1 `hidingSubsumes` ideclHiding d2)
  1618. where
  1619. _ `hidingSubsumes` Just (False,[]) = True
  1620. Just (False, xs) `hidingSubsumes` Just (False,ys) = all (`elem` xs) ys
  1621. h1 `hidingSubsumes` h2 = h1 == h2
  1622. iiSubsumes _ _ = False
  1623. ----------------------------------------------------------------------------
  1624. -- :set
  1625. -- set options in the interpreter. Syntax is exactly the same as the
  1626. -- ghc command line, except that certain options aren't available (-C,
  1627. -- -E etc.)
  1628. --
  1629. -- This is pretty fragile: most options won't work as expected. ToDo:
  1630. -- figure out which ones & disallow them.
  1631. setCmd :: String -> GHCi ()
  1632. setCmd "" = showOptions False
  1633. setCmd "-a" = showOptions True
  1634. setCmd str
  1635. = case getCmd str of
  1636. Right ("args", rest) ->
  1637. case toArgs rest of
  1638. Left err -> liftIO (hPutStrLn stderr err)
  1639. Right args -> setArgs args
  1640. Right ("prog", rest) ->
  1641. case toArgs rest of
  1642. Right [prog] -> setProg prog
  1643. _ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
  1644. Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
  1645. Right ("prompt2", rest) -> setPrompt2 $ dropWhile isSpace rest
  1646. Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
  1647. Right ("stop", rest) -> setStop $ dropWhile isSpace rest
  1648. _ -> case toArgs str of
  1649. Left err -> liftIO (hPutStrLn stderr err)
  1650. Right wds -> setOptions wds
  1651. setiCmd :: String -> GHCi ()
  1652. setiCmd "" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags False
  1653. setiCmd "-a" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags True
  1654. setiCmd str =
  1655. case toArgs str of
  1656. Left err -> liftIO (hPutStrLn stderr err)
  1657. Right wds -> newDynFlags True wds
  1658. showOptions :: Bool -> GHCi ()
  1659. showOptions show_all
  1660. = do st <- getGHCiState
  1661. dflags <- getDynFlags
  1662. let opts = options st
  1663. liftIO $ putStrLn (showSDoc dflags (
  1664. text "options currently set: " <>
  1665. if null opts
  1666. then text "none."
  1667. else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
  1668. ))
  1669. getDynFlags >>= liftIO . showDynFlags show_all
  1670. showDynFlags :: Bool -> DynFlags -> IO ()
  1671. showDynFlags show_all dflags = do
  1672. showLanguages' show_all dflags
  1673. putStrLn $ showSDoc dflags $
  1674. text "GHCi-specific dynamic flag settings:" $$
  1675. nest 2 (vcat (map (setting gopt) ghciFlags))
  1676. putStrLn $ showSDoc dflags $
  1677. text "other dynamic, non-language, flag settings:" $$
  1678. nest 2 (vcat (map (setting gopt) others))
  1679. putStrLn $ showSDoc dflags $
  1680. text "warning settings:" $$
  1681. nest 2 (vcat (map (setting wopt) DynFlags.fWarningFlags))
  1682. where
  1683. setting test (str, f, _)
  1684. | quiet = empty
  1685. | is_on = fstr str
  1686. | otherwise = fnostr str
  1687. where is_on = test f dflags
  1688. quiet = not show_all && test f default_dflags == is_on
  1689. default_dflags = defaultDynFlags (settings dflags)
  1690. fstr str = text "-f" <> text str
  1691. fnostr str = text "-fno-" <> text str
  1692. (ghciFlags,others) = partition (\(_, f, _) -> f `elem` flgs)
  1693. DynFlags.fFlags
  1694. flgs = [Opt_PrintExplicitForalls
  1695. ,Opt_PrintBindResult
  1696. ,Opt_BreakOnException
  1697. ,Opt_BreakOnError
  1698. ,Opt_PrintEvldWithShow
  1699. ]
  1700. setArgs, setOptions :: [String] -> GHCi ()
  1701. setProg, setEditor, setStop :: String -> GHCi ()
  1702. setArgs args = do
  1703. st <- getGHCiState
  1704. setGHCiState st{ GhciMonad.args = args }
  1705. setProg prog = do
  1706. st <- getGHCiState
  1707. setGHCiState st{ progname = prog }
  1708. setEditor cmd = do
  1709. st <- getGHCiState
  1710. setGHCiState st{ editor = cmd }
  1711. setStop str@(c:_) | isDigit c
  1712. = do let (nm_str,rest) = break (not.isDigit) str
  1713. nm = read nm_str
  1714. st <- getGHCiState
  1715. let old_breaks = breaks st
  1716. if all ((/= nm) . fst) old_breaks
  1717. then printForUser (text "Breakpoint" <+> ppr nm <+>
  1718. text "does not exist")
  1719. else do
  1720. let new_breaks = map fn old_breaks
  1721. fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
  1722. | otherwise = (i,loc)
  1723. setGHCiState st{ breaks = new_breaks }
  1724. setStop cmd = do
  1725. st <- getGHCiState
  1726. setGHCiState st{ stop = cmd }
  1727. setPrompt :: String -> GHCi ()
  1728. setPrompt = setPrompt_ f err
  1729. where
  1730. f v st = st { prompt = v }
  1731. err st = "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
  1732. setPrompt2 :: String -> GHCi ()
  1733. setPrompt2 = setPrompt_ f err
  1734. where
  1735. f v st = st { prompt2 = v }
  1736. err st = "syntax: :set prompt2 <prompt>, currently \"" ++ prompt2 st ++ "\""
  1737. setPrompt_ :: (String -> GHCiState -> GHCiState) -> (GHCiState -> String) -> String -> GHCi ()
  1738. setPrompt_ f err value = do
  1739. st <- getGHCiState
  1740. if null value
  1741. then liftIO $ hPutStrLn stderr $ err st
  1742. else case value of
  1743. '\"' : _ -> case reads value of
  1744. [(value', xs)] | all isSpace xs ->
  1745. setGHCiState $ f value' st
  1746. _ ->
  1747. liftIO $ hPutStrLn stderr "Can't parse prompt string. Use Haskell syntax."
  1748. _ -> setGHCiState $ f value st
  1749. setOptions wds =
  1750. do -- first, deal with the GHCi opts (+s, +t, etc.)
  1751. let (plus_opts, minus_opts) = partitionWith isPlus wds
  1752. mapM_ setOpt plus_opts
  1753. -- then, dynamic flags
  1754. newDynFlags False minus_opts
  1755. newDynFlags :: Bool -> [String] -> GHCi ()
  1756. newDynFlags interactive_only minus_opts = do
  1757. let lopts = map noLoc minus_opts
  1758. idflags0 <- GHC.getInteractiveDynFlags
  1759. (idflags1, leftovers, warns) <- GHC.parseDynamicFlags idflags0 lopts
  1760. liftIO $ handleFlagWarnings idflags1 warns
  1761. when (not $ null leftovers)
  1762. (throwGhcException . CmdLineError
  1763. $ "Some flags have not been recognized: "
  1764. ++ (concat . intersperse ", " $ map unLoc leftovers))
  1765. when (interactive_only &&
  1766. packageFlags idflags1 /= packageFlags idflags0) $ do
  1767. liftIO $ hPutStrLn stderr "cannot set package flags with :seti; use :set"
  1768. GHC.setInteractiveDynFlags idflags1
  1769. installInteractivePrint (interactivePrint idflags1) False
  1770. dflags0 <- getDynFlags
  1771. when (not interactive_only) $ do
  1772. (dflags1, _, _) <- liftIO $ GHC.parseDynamicFlags dflags0 lopts
  1773. new_pkgs <- GHC.setProgramDynFlags dflags1
  1774. -- if the package flags changed, reset the context and link
  1775. -- the new packages.
  1776. dflags2 <- getDynFlags
  1777. when (packageFlags dflags2 /= packageFlags dflags0) $ do
  1778. when (verbosity dflags2 > 0) $
  1779. liftIO . putStrLn $
  1780. "package flags have changed, resetting and loading new packages..."
  1781. GHC.setTargets []
  1782. _ <- GHC.load LoadAllTargets
  1783. liftIO $ linkPackages dflags2 new_pkgs
  1784. -- package flags changed, we can't re-use any of the old context
  1785. setContextAfterLoad False []
  1786. -- and copy the package state to the interactive DynFlags
  1787. idflags <- GHC.getInteractiveDynFlags
  1788. GHC.setInteractiveDynFlags
  1789. idflags{ pkgState = pkgState dflags2
  1790. , pkgDatabase = pkgDatabase dflags2
  1791. , packageFlags = packageFlags dflags2 }
  1792. return ()
  1793. unsetOptions :: String -> GHCi ()
  1794. unsetOptions str
  1795. = -- first, deal with the GHCi opts (+s, +t, etc.)
  1796. let opts = words str
  1797. (minus_opts, rest1) = partition isMinus opts
  1798. (plus_opts, rest2) = partitionWith isPlus rest1
  1799. (other_opts, rest3) = partition (`elem` map fst defaulters) rest2
  1800. defaulters =
  1801. [ ("args" , setArgs default_args)
  1802. , ("prog" , setProg default_progname)
  1803. , ("prompt" , setPrompt default_prompt)
  1804. , ("prompt2", setPrompt2 default_prompt2)
  1805. , ("editor" , liftIO findEditor >>= setEditor)
  1806. , ("stop" , setStop default_stop)
  1807. ]
  1808. no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
  1809. no_flag f = throwGhcException (ProgramError ("don't know how to reverse " ++ f))
  1810. in if (not (null rest3))
  1811. then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
  1812. else do
  1813. mapM_ (fromJust.flip lookup defaulters) other_opts
  1814. mapM_ unsetOpt plus_opts
  1815. no_flags <- mapM no_flag minus_opts
  1816. newDynFlags False no_flags
  1817. isMinus :: String -> Bool
  1818. isMinus ('-':_) = True
  1819. isMinus _ = False
  1820. isPlus :: String -> Either String String
  1821. isPlus ('+':opt) = Left opt
  1822. isPlus other = Right other
  1823. setOpt, unsetOpt :: String -> GHCi ()
  1824. setOpt str
  1825. = case strToGHCiOpt str of
  1826. Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
  1827. Just o -> setOption o
  1828. unsetOpt str
  1829. = case strToGHCiOpt str of
  1830. Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
  1831. Just o -> unsetOption o
  1832. strToGHCiOpt :: String -> (Maybe GHCiOption)
  1833. strToGHCiOpt "m" = Just Multiline
  1834. strToGHCiOpt "s" = Just ShowTiming
  1835. strToGHCiOpt "t" = Just ShowType
  1836. strToGHCiOpt "r" = Just RevertCAFs
  1837. strToGHCiOpt _ = Nothing
  1838. optToStr :: GHCiOption -> String
  1839. optToStr Multiline = "m"
  1840. optToStr ShowTiming = "s"
  1841. optToStr ShowType = "t"
  1842. optToStr RevertCAFs = "r"
  1843. -- ---------------------------------------------------------------------------
  1844. -- :show
  1845. showCmd :: String -> GHCi ()
  1846. showCmd "" = showOptions False
  1847. showCmd "-a" = showOptions True
  1848. showCmd str = do
  1849. st <- getGHCiState
  1850. case words str of
  1851. ["args"] -> liftIO $ putStrLn (show (GhciMonad.args st))
  1852. ["prog"] -> liftIO $ putStrLn (show (progname st))
  1853. ["prompt"] -> liftIO $ putStrLn (show (prompt st))
  1854. ["prompt2"] -> liftIO $ putStrLn (show (prompt2 st))
  1855. ["editor"] -> liftIO $ putStrLn (show (editor st))
  1856. ["stop"] -> liftIO $ putStrLn (show (stop st))
  1857. ["imports"] -> showImports
  1858. ["modules" ] -> showModules
  1859. ["bindings"] -> showBindings
  1860. ["linker"] ->
  1861. do dflags <- getDynFlags
  1862. liftIO $ showLinkerState dflags
  1863. ["breaks"] -> showBkptTable
  1864. ["context"] -> showContext
  1865. ["packages"] -> showPackages
  1866. ["languages"] -> showLanguages -- backwards compat
  1867. ["language"] -> showLanguages
  1868. ["lang"] -> showLanguages -- useful abbreviation
  1869. _ -> throwGhcException (CmdLineError ("syntax: :show [ args | prog | prompt | prompt2 | editor | stop | modules\n" ++
  1870. " | bindings | breaks | context | packages | language ]"))
  1871. showiCmd :: String -> GHCi ()
  1872. showiCmd str = do
  1873. case words str of
  1874. ["languages"] -> showiLanguages -- backwards compat
  1875. ["language"] -> showiLanguages
  1876. ["lang"] -> showiLanguages -- useful abbreviation
  1877. _ -> throwGhcException (CmdLineError ("syntax: :showi language"))
  1878. showImports :: GHCi ()
  1879. showImports = do
  1880. st <- getGHCiState
  1881. dflags <- getDynFlags
  1882. let rem_ctx = reverse (remembered_ctx st)
  1883. trans_ctx = transient_ctx st
  1884. show_one (IIModule star_m)
  1885. = ":module +*" ++ moduleNameString star_m
  1886. show_one (IIDecl imp) = showPpr dflags imp
  1887. prel_imp
  1888. | any isPreludeImport (rem_ctx ++ trans_ctx) = []
  1889. | otherwise = ["import Prelude -- implicit"]
  1890. trans_comment s = s ++ " -- added automatically"
  1891. --
  1892. liftIO $ mapM_ putStrLn (prel_imp ++ map show_one rem_ctx
  1893. ++ map (trans_comment . show_one) trans_ctx)
  1894. showModules :: GHCi ()
  1895. showModules = do
  1896. loaded_mods <- getLoadedModules
  1897. -- we want *loaded* modules only, see #1734
  1898. let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
  1899. mapM_ show_one loaded_mods
  1900. getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
  1901. getLoadedModules = do
  1902. graph <- GHC.getModuleGraph
  1903. filterM (GHC.isLoaded . GHC.ms_mod_name) graph
  1904. showBindings :: GHCi ()
  1905. showBindings = do
  1906. bindings <- GHC.getBindings
  1907. (insts, finsts) <- GHC.getInsts
  1908. docs <- mapM makeDoc (reverse bindings)
  1909. -- reverse so the new ones come last
  1910. let idocs = map GHC.pprInstanceHdr insts
  1911. fidocs = map GHC.pprFamInst finsts
  1912. mapM_ printForUserPartWay (docs ++ idocs ++ fidocs)
  1913. where
  1914. makeDoc (AnId i) = pprTypeAndContents i
  1915. makeDoc tt = do
  1916. dflags <- getDynFlags
  1917. let pefas = gopt Opt_PrintExplicitForalls dflags
  1918. mb_stuff <- GHC.getInfo False (getName tt)
  1919. return $ maybe (text "") (pprTT pefas) mb_stuff
  1920. pprTT :: PrintExplicitForalls
  1921. -> (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst]) -> SDoc
  1922. pprTT pefas (thing, fixity, _cls_insts, _fam_insts) =
  1923. pprTyThing pefas thing
  1924. $$ show_fixity
  1925. where
  1926. show_fixity
  1927. | fixity == GHC.defaultFixity = empty
  1928. | otherwise = ppr fixity <+> ppr (GHC.getName thing)
  1929. printTyThing :: TyThing -> GHCi ()
  1930. printTyThing tyth = do dflags <- getDynFlags
  1931. let pefas = gopt Opt_PrintExplicitForalls dflags
  1932. printForUser (pprTyThing pefas tyth)
  1933. showBkptTable :: GHCi ()
  1934. showBkptTable = do
  1935. st <- getGHCiState
  1936. printForUser $ prettyLocations (breaks st)
  1937. showContext :: GHCi ()
  1938. showContext = do
  1939. resumes <- GHC.getResumeContext
  1940. printForUser $ vcat (map pp_resume (reverse resumes))
  1941. where
  1942. pp_resume res =
  1943. ptext (sLit "--> ") <> text (GHC.resumeStmt res)
  1944. $$ nest 2 (ptext (sLit "Stopped at") <+> ppr (GHC.resumeSpan res))
  1945. showPackages :: GHCi ()
  1946. showPackages = do
  1947. dflags <- getDynFlags
  1948. let pkg_flags = packageFlags dflags
  1949. liftIO $ putStrLn $ showSDoc dflags $ vcat $
  1950. text ("active package flags:"++if null pkg_flags then " none" else "")
  1951. : map showFlag pkg_flags
  1952. where showFlag (ExposePackage p) = text $ " -package " ++ p
  1953. showFlag (HidePackage p) = text $ " -hide-package " ++ p
  1954. showFlag (IgnorePackage p) = text $ " -ignore-package " ++ p
  1955. showFlag (ExposePackageId p) = text $ " -package-id " ++ p
  1956. showFlag (TrustPackage p) = text $ " -trust " ++ p
  1957. showFlag (DistrustPackage p) = text $ " -distrust " ++ p
  1958. showLanguages :: GHCi ()
  1959. showLanguages = getDynFlags >>= liftIO . showLanguages' False
  1960. showiLanguages :: GHCi ()
  1961. showiLanguages = GHC.getInteractiveDynFlags >>= liftIO . showLanguages' False
  1962. showLanguages' :: Bool -> DynFlags -> IO ()
  1963. showLanguages' show_all dflags =
  1964. putStrLn $ showSDoc dflags $ vcat
  1965. [ text "base language is: " <>
  1966. case language dflags of
  1967. Nothing -> text "Haskell2010"
  1968. Just Haskell98 -> text "Haskell98"
  1969. Just Haskell2010 -> text "Haskell2010"
  1970. , (if show_all then text "all active language options:"
  1971. else text "with the following modifiers:") $$
  1972. nest 2 (vcat (map (setting xopt) DynFlags.xFlags))
  1973. ]
  1974. where
  1975. setting test (str, f, _)
  1976. | quiet = empty
  1977. | is_on = text "-X" <> text str
  1978. | otherwise = text "-XNo" <> text str
  1979. where is_on = test f dflags
  1980. quiet = not show_all && test f default_dflags == is_on
  1981. default_dflags =
  1982. defaultDynFlags (settings dflags) `lang_set`
  1983. case language dflags of
  1984. Nothing -> Just Haskell2010
  1985. other -> other
  1986. -- -----------------------------------------------------------------------------
  1987. -- Completion
  1988. completeCmd :: String -> GHCi ()
  1989. completeCmd argLine0 = case parseLine argLine0 of
  1990. Just ("repl", resultRange, left) -> do
  1991. (unusedLine,compls) <- ghciCompleteWord (reverse left,"")
  1992. let compls' = takeRange resultRange compls
  1993. liftIO . putStrLn $ unwords [ show (length compls'), show (length compls), show (reverse unusedLine) ]
  1994. forM_ (takeRange resultRange compls) $ \(Completion r _ _) -> do
  1995. liftIO $ print r
  1996. _ -> throwGhcException (CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
  1997. where
  1998. parseLine argLine
  1999. | null argLine = Nothing
  2000. | null rest1 = Nothing
  2001. | otherwise = (,,) dom <$> resRange <*> s
  2002. where
  2003. (dom, rest1) = breakSpace argLine
  2004. (rng, rest2) = breakSpace rest1
  2005. resRange | head rest1 == '"' = parseRange ""
  2006. | otherwise = parseRange rng
  2007. s | head rest1 == '"' = readMaybe rest1 :: Maybe String
  2008. | otherwise = readMaybe rest2
  2009. breakSpace = fmap (dropWhile isSpace) . break isSpace
  2010. takeRange (lb,ub) = maybe id (drop . pred) lb . maybe id take ub
  2011. -- syntax: [n-][m] with semantics "drop (n-1) . take m"
  2012. parseRange :: String -> Maybe (Maybe Int,Maybe Int)
  2013. parseRange s = case span isDigit s of
  2014. (_, "") ->
  2015. -- upper limit only
  2016. Just (Nothing, bndRead s)
  2017. (s1, '-' : s2)
  2018. | all isDigit s2 ->
  2019. Just (bndRead s1, bndRead s2)
  2020. _ ->
  2021. Nothing
  2022. where
  2023. bndRead x = if null x then Nothing else Just (read x)
  2024. completeGhciCommand, completeMacro, completeIdentifier, completeModule,
  2025. completeSetModule, completeSeti, completeShowiOptions,
  2026. completeHomeModule, completeSetOptions, completeShowOptions,
  2027. completeHomeModuleOrFile, completeExpression
  2028. :: CompletionFunc GHCi
  2029. ghciCompleteWord :: CompletionFunc GHCi
  2030. ghciCompleteWord line@(left,_) = case firstWord of
  2031. ':':cmd | null rest -> completeGhciCommand line
  2032. | otherwise -> do
  2033. completion <- lookupCompletion cmd
  2034. completion line
  2035. "import" -> completeModule line
  2036. _ -> completeExpression line
  2037. where
  2038. (firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
  2039. lookupCompletion ('!':_) = return completeFilename
  2040. lookupCompletion c = do
  2041. maybe_cmd <- lookupCommand' c
  2042. case maybe_cmd of
  2043. Just (_,_,f) -> return f
  2044. Nothing -> return completeFilename
  2045. completeGhciCommand = wrapCompleter " " $ \w -> do
  2046. macros <- liftIO $ readIORef macros_ref
  2047. cmds <- ghci_commands `fmap` getGHCiState
  2048. let macro_names = map (':':) . map cmdName $ macros
  2049. let command_names = map (':':) . map cmdName $ cmds
  2050. let{ candidates = case w of
  2051. ':' : ':' : _ -> map (':':) command_names
  2052. _ -> nub $ macro_names ++ command_names }
  2053. return $ filter (w `isPrefixOf`) candidates
  2054. completeMacro = wrapIdentCompleter $ \w -> do
  2055. cmds <- liftIO $ readIORef macros_ref
  2056. return (filter (w `isPrefixOf`) (map cmdName cmds))
  2057. completeIdentifier = wrapIdentCompleter $ \w -> do
  2058. rdrs <- GHC.getRdrNamesInScope
  2059. dflags <- GHC.getSessionDynFlags
  2060. return (filter (w `isPrefixOf`) (map (showPpr dflags) rdrs))
  2061. completeModule = wrapIdentCompleter $ \w -> do
  2062. dflags <- GHC.getSessionDynFlags
  2063. let pkg_mods = allExposedModules dflags
  2064. loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
  2065. return $ filter (w `isPrefixOf`)
  2066. $ map (showPpr dflags) $ loaded_mods ++ pkg_mods
  2067. completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
  2068. dflags <- GHC.getSessionDynFlags
  2069. modules <- case m of
  2070. Just '-' -> do
  2071. imports <- GHC.getContext
  2072. return $ map iiModuleName imports
  2073. _ -> do
  2074. let pkg_mods = allExposedModules dflags
  2075. loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
  2076. return $ loaded_mods ++ pkg_mods
  2077. return $ filter (w `isPrefixOf`) $ map (showPpr dflags) modules
  2078. completeHomeModule = wrapIdentCompleter listHomeModules
  2079. listHomeModules :: String -> GHCi [String]
  2080. listHomeModules w = do
  2081. g <- GHC.getModuleGraph
  2082. let home_mods = map GHC.ms_mod_name g
  2083. dflags <- getDynFlags
  2084. return $ sort $ filter (w `isPrefixOf`)
  2085. $ map (showPpr dflags) home_mods
  2086. completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
  2087. return (filter (w `isPrefixOf`) opts)
  2088. where opts = "args":"prog":"prompt":"prompt2":"editor":"stop":flagList
  2089. flagList = map head $ group $ sort allFlags
  2090. completeSeti = wrapCompleter flagWordBreakChars $ \w -> do
  2091. return (filter (w `isPrefixOf`) flagList)
  2092. where flagList = map head $ group $ sort allFlags
  2093. completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
  2094. return (filter (w `isPrefixOf`) opts)
  2095. where opts = ["args", "prog", "prompt", "prompt2", "editor", "stop",
  2096. "modules", "bindings", "linker", "breaks",
  2097. "context", "packages", "language", "imports"]
  2098. completeShowiOptions = wrapCompleter flagWordBreakChars $ \w -> do
  2099. return (filter (w `isPrefixOf`) ["language"])
  2100. completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
  2101. $ unionComplete (fmap (map simpleCompletion) . listHomeModules)
  2102. listFiles
  2103. unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
  2104. unionComplete f1 f2 line = do
  2105. cs1 <- f1 line
  2106. cs2 <- f2 line
  2107. return (cs1 ++ cs2)
  2108. wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
  2109. wrapCompleter breakChars fun = completeWord Nothing breakChars
  2110. $ fmap (map simpleCompletion) . fmap sort . fun
  2111. wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
  2112. wrapIdentCompleter = wrapCompleter word_break_chars
  2113. wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
  2114. wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
  2115. $ \rest -> fmap (map simpleCompletion) . fmap sort . fun (getModifier rest)
  2116. where
  2117. getModifier = find (`elem` modifChars)
  2118. allExposedModules :: DynFlags -> [ModuleName]
  2119. allExposedModules dflags
  2120. = concat (map exposedModules (filter exposed (eltsUFM pkg_db)))
  2121. where
  2122. pkg_db = pkgIdMap (pkgState dflags)
  2123. completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
  2124. completeIdentifier
  2125. -- -----------------------------------------------------------------------------
  2126. -- commands for debugger
  2127. sprintCmd, printCmd, forceCmd :: String -> GHCi ()
  2128. sprintCmd = pprintCommand False False
  2129. printCmd = pprintCommand True False
  2130. forceCmd = pprintCommand False True
  2131. pprintCommand :: Bool -> Bool -> String -> GHCi ()
  2132. pprintCommand bind force str = do
  2133. pprintClosureCommand bind force str
  2134. stepCmd :: String -> GHCi ()
  2135. stepCmd arg = withSandboxOnly ":step" $ step arg
  2136. where
  2137. step [] = doContinue (const True) GHC.SingleStep
  2138. step expression = runStmt expression GHC.SingleStep >> return ()
  2139. stepLocalCmd :: String -> GHCi ()
  2140. stepLocalCmd arg = withSandboxOnly ":steplocal" $ step arg
  2141. where
  2142. step expr
  2143. | not (null expr) = stepCmd expr
  2144. | otherwise = do
  2145. mb_span <- getCurrentBreakSpan
  2146. case mb_span of
  2147. Nothing -> stepCmd []
  2148. Just loc -> do
  2149. Just md <- getCurrentBreakModule
  2150. current_toplevel_decl <- enclosingTickSpan md loc
  2151. doContinue (`isSubspanOf` current_toplevel_decl) GHC.SingleStep
  2152. stepModuleCmd :: String -> GHCi ()
  2153. stepModuleCmd arg = withSandboxOnly ":stepmodule" $ step arg
  2154. where
  2155. step expr
  2156. | not (null expr) = stepCmd expr
  2157. | otherwise = do
  2158. mb_span <- getCurrentBreakSpan
  2159. case mb_span of
  2160. Nothing -> stepCmd []
  2161. Just pan -> do
  2162. let f some_span = srcSpanFileName_maybe pan == srcSpanFileName_maybe some_span
  2163. doContinue f GHC.SingleStep
  2164. -- | Returns the span of the largest tick containing the srcspan given
  2165. enclosingTickSpan :: Module -> SrcSpan -> GHCi SrcSpan
  2166. enclosingTickSpan _ (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
  2167. enclosingTickSpan md (RealSrcSpan src) = do
  2168. ticks <- getTickArray md
  2169. let line = srcSpanStartLine src
  2170. ASSERT(inRange (bounds ticks) line) do
  2171. let toRealSrcSpan (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
  2172. toRealSrcSpan (RealSrcSpan s) = s
  2173. enclosing_spans = [ pan | (_,pan) <- ticks ! line
  2174. , realSrcSpanEnd (toRealSrcSpan pan) >= realSrcSpanEnd src]
  2175. return . head . sortBy leftmost_largest $ enclosing_spans
  2176. traceCmd :: String -> GHCi ()
  2177. traceCmd arg
  2178. = withSandboxOnly ":trace" $ tr arg
  2179. where
  2180. tr [] = doContinue (const True) GHC.RunAndLogSteps
  2181. tr expression = runStmt expression GHC.RunAndLogSteps >> return ()
  2182. continueCmd :: String -> GHCi ()
  2183. continueCmd = noArgs $ withSandboxOnly ":continue" $ doContinue (const True) GHC.RunToCompletion
  2184. -- doContinue :: SingleStep -> GHCi ()
  2185. doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
  2186. doContinue pre step = do
  2187. runResult <- resume pre step
  2188. _ <- afterRunStmt pre runResult
  2189. return ()
  2190. abandonCmd :: String -> GHCi ()
  2191. abandonCmd = noArgs $ withSandboxOnly ":abandon" $ do
  2192. b <- GHC.abandon -- the prompt will change to indicate the new context
  2193. when (not b) $ liftIO $ putStrLn "There is no computation running."
  2194. deleteCmd :: String -> GHCi ()
  2195. deleteCmd argLine = withSandboxOnly ":delete" $ do
  2196. deleteSwitch $ words argLine
  2197. where
  2198. deleteSwitch :: [String] -> GHCi ()
  2199. deleteSwitch [] =
  2200. liftIO $ putStrLn "The delete command requires at least one argument."
  2201. -- delete all break points
  2202. deleteSwitch ("*":_rest) = discardActiveBreakPoints
  2203. deleteSwitch idents = do
  2204. mapM_ deleteOneBreak idents
  2205. where
  2206. deleteOneBreak :: String -> GHCi ()
  2207. deleteOneBreak str
  2208. | all isDigit str = deleteBreak (read str)
  2209. | otherwise = return ()
  2210. historyCmd :: String -> GHCi ()
  2211. historyCmd arg
  2212. | null arg = history 20
  2213. | all isDigit arg = history (read arg)
  2214. | otherwise = liftIO $ putStrLn "Syntax: :history [num]"
  2215. where
  2216. history num = do
  2217. resumes <- GHC.getResumeContext
  2218. case resumes of
  2219. [] -> liftIO $ putStrLn "Not stopped at a breakpoint"
  2220. (r:_) -> do
  2221. let hist = GHC.resumeHistory r
  2222. (took,rest) = splitAt num hist
  2223. case hist of
  2224. [] -> liftIO $ putStrLn $
  2225. "Empty history. Perhaps you forgot to use :trace?"
  2226. _ -> do
  2227. pans <- mapM GHC.getHistorySpan took
  2228. let nums = map (printf "-%-3d:") [(1::Int)..]
  2229. names = map GHC.historyEnclosingDecls took
  2230. printForUser (vcat(zipWith3
  2231. (\x y z -> x <+> y <+> z)
  2232. (map text nums)
  2233. (map (bold . hcat . punctuate colon . map text) names)
  2234. (map (parens . ppr) pans)))
  2235. liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
  2236. bold :: SDoc -> SDoc
  2237. bold c | do_bold = text start_bold <> c <> text end_bold
  2238. | otherwise = c
  2239. backCmd :: String -> GHCi ()
  2240. backCmd = noArgs $ withSandboxOnly ":back" $ do
  2241. (names, _, pan) <- GHC.back
  2242. printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr pan
  2243. printTypeOfNames names
  2244. -- run the command set with ":set stop <cmd>"
  2245. st <- getGHCiState
  2246. enqueueCommands [stop st]
  2247. forwardCmd :: String -> GHCi ()
  2248. forwardCmd = noArgs $ withSandboxOnly ":forward" $ do
  2249. (names, ix, pan) <- GHC.forward
  2250. printForUser $ (if (ix == 0)
  2251. then ptext (sLit "Stopped at")
  2252. else ptext (sLit "Logged breakpoint at")) <+> ppr pan
  2253. printTypeOfNames names
  2254. -- run the command set with ":set stop <cmd>"
  2255. st <- getGHCiState
  2256. enqueueCommands [stop st]
  2257. -- handle the "break" command
  2258. breakCmd :: String -> GHCi ()
  2259. breakCmd argLine = withSandboxOnly ":break" $ breakSwitch $ words argLine
  2260. breakSwitch :: [String] -> GHCi ()
  2261. breakSwitch [] = do
  2262. liftIO $ putStrLn "The break command requires at least one argument."
  2263. breakSwitch (arg1:rest)
  2264. | looksLikeModuleName arg1 && not (null rest) = do
  2265. md <- wantInterpretedModule arg1
  2266. breakByModule md rest
  2267. | all isDigit arg1 = do
  2268. imports <- GHC.getContext
  2269. case iiModules imports of
  2270. (mn : _) -> do
  2271. md <- lookupModuleName mn
  2272. breakByModuleLine md (read arg1) rest
  2273. [] -> do
  2274. liftIO $ putStrLn "No modules are loaded with debugging support."
  2275. | otherwise = do -- try parsing it as an identifier
  2276. wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
  2277. let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
  2278. case loc of
  2279. RealSrcLoc l ->
  2280. ASSERT( isExternalName name )
  2281. findBreakAndSet (GHC.nameModule name) $
  2282. findBreakByCoord (Just (GHC.srcLocFile l))
  2283. (GHC.srcLocLine l,
  2284. GHC.srcLocCol l)
  2285. UnhelpfulLoc _ ->
  2286. noCanDo name $ text "can't find its location: " <> ppr loc
  2287. where
  2288. noCanDo n why = printForUser $
  2289. text "cannot set breakpoint on " <> ppr n <> text ": " <> why
  2290. breakByModule :: Module -> [String] -> GHCi ()
  2291. breakByModule md (arg1:rest)
  2292. | all isDigit arg1 = do -- looks like a line number
  2293. breakByModuleLine md (read arg1) rest
  2294. breakByModule _ _
  2295. = breakSyntax
  2296. breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
  2297. breakByModuleLine md line args
  2298. | [] <- args = findBreakAndSet md $ findBreakByLine line
  2299. | [col] <- args, all isDigit col =
  2300. findBreakAndSet md $ findBreakByCoord Nothing (line, read col)
  2301. | otherwise = breakSyntax
  2302. breakSyntax :: a
  2303. breakSyntax = throwGhcException (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
  2304. findBreakAndSet :: Module -> (TickArray -> Maybe (Int, SrcSpan)) -> GHCi ()
  2305. findBreakAndSet md lookupTickTree = do
  2306. dflags <- getDynFlags
  2307. tickArray <- getTickArray md
  2308. (breakArray, _) <- getModBreak md
  2309. case lookupTickTree tickArray of
  2310. Nothing -> liftIO $ putStrLn $ "No breakpoints found at that location."
  2311. Just (tick, pan) -> do
  2312. success <- liftIO $ setBreakFlag dflags True breakArray tick
  2313. if success
  2314. then do
  2315. (alreadySet, nm) <-
  2316. recordBreak $ BreakLocation
  2317. { breakModule = md
  2318. , breakLoc = pan
  2319. , breakTick = tick
  2320. , onBreakCmd = ""
  2321. }
  2322. printForUser $
  2323. text "Breakpoint " <> ppr nm <>
  2324. if alreadySet
  2325. then text " was already set at " <> ppr pan
  2326. else text " activated at " <> ppr pan
  2327. else do
  2328. printForUser $ text "Breakpoint could not be activated at"
  2329. <+> ppr pan
  2330. -- When a line number is specified, the current policy for choosing
  2331. -- the best breakpoint is this:
  2332. -- - the leftmost complete subexpression on the specified line, or
  2333. -- - the leftmost subexpression starting on the specified line, or
  2334. -- - the rightmost subexpression enclosing the specified line
  2335. --
  2336. findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,SrcSpan)
  2337. findBreakByLine line arr
  2338. | not (inRange (bounds arr) line) = Nothing
  2339. | otherwise =
  2340. listToMaybe (sortBy (leftmost_largest `on` snd) comp) `mplus`
  2341. listToMaybe (sortBy (leftmost_smallest `on` snd) incomp) `mplus`
  2342. listToMaybe (sortBy (rightmost `on` snd) ticks)
  2343. where
  2344. ticks = arr ! line
  2345. starts_here = [ tick | tick@(_,pan) <- ticks,
  2346. GHC.srcSpanStartLine (toRealSpan pan) == line ]
  2347. (comp, incomp) = partition ends_here starts_here
  2348. where ends_here (_,pan) = GHC.srcSpanEndLine (toRealSpan pan) == line
  2349. toRealSpan (RealSrcSpan pan) = pan
  2350. toRealSpan (UnhelpfulSpan _) = panic "findBreakByLine UnhelpfulSpan"
  2351. findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
  2352. -> Maybe (BreakIndex,SrcSpan)
  2353. findBreakByCoord mb_file (line, col) arr
  2354. | not (inRange (bounds arr) line) = Nothing
  2355. | otherwise =
  2356. listToMaybe (sortBy (rightmost `on` snd) contains ++
  2357. sortBy (leftmost_smallest `on` snd) after_here)
  2358. where
  2359. ticks = arr ! line
  2360. -- the ticks that span this coordinate
  2361. contains = [ tick | tick@(_,pan) <- ticks, pan `spans` (line,col),
  2362. is_correct_file pan ]
  2363. is_correct_file pan
  2364. | Just f <- mb_file = GHC.srcSpanFile (toRealSpan pan) == f
  2365. | otherwise = True
  2366. after_here = [ tick | tick@(_,pan) <- ticks,
  2367. let pan' = toRealSpan pan,
  2368. GHC.srcSpanStartLine pan' == line,
  2369. GHC.srcSpanStartCol pan' >= col ]
  2370. toRealSpan (RealSrcSpan pan) = pan
  2371. toRealSpan (UnhelpfulSpan _) = panic "findBreakByCoord UnhelpfulSpan"
  2372. -- For now, use ANSI bold on terminals that we know support it.
  2373. -- Otherwise, we add a line of carets under the active expression instead.
  2374. -- In particular, on Windows and when running the testsuite (which sets
  2375. -- TERM to vt100 for other reasons) we get carets.
  2376. -- We really ought to use a proper termcap/terminfo library.
  2377. do_bold :: Bool
  2378. do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
  2379. where mTerm = System.Environment.getEnv "TERM"
  2380. `catchIO` \_ -> return "TERM not set"
  2381. start_bold :: String
  2382. start_bold = "\ESC[1m"
  2383. end_bold :: String
  2384. end_bold = "\ESC[0m"
  2385. -----------------------------------------------------------------------------
  2386. -- :list
  2387. listCmd :: String -> InputT GHCi ()
  2388. listCmd c = listCmd' c
  2389. listCmd' :: String -> InputT GHCi ()
  2390. listCmd' "" = do
  2391. mb_span <- lift getCurrentBreakSpan
  2392. case mb_span of
  2393. Nothing ->
  2394. printForUser $ text "Not stopped at a breakpoint; nothing to list"
  2395. Just (RealSrcSpan pan) ->
  2396. listAround pan True
  2397. Just pan@(UnhelpfulSpan _) ->
  2398. do resumes <- GHC.getResumeContext
  2399. case resumes of
  2400. [] -> panic "No resumes"
  2401. (r:_) ->
  2402. do let traceIt = case GHC.resumeHistory r of
  2403. [] -> text "rerunning with :trace,"
  2404. _ -> empty
  2405. doWhat = traceIt <+> text ":back then :list"
  2406. printForUser (text "Unable to list source for" <+>
  2407. ppr pan
  2408. $$ text "Try" <+> doWhat)
  2409. listCmd' str = list2 (words str)
  2410. list2 :: [String] -> InputT GHCi ()
  2411. list2 [arg] | all isDigit arg = do
  2412. imports <- GHC.getContext
  2413. case iiModules imports of
  2414. [] -> liftIO $ putStrLn "No module to list"
  2415. (mn : _) -> do
  2416. md <- lift $ lookupModuleName mn
  2417. listModuleLine md (read arg)
  2418. list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
  2419. md <- wantInterpretedModule arg1
  2420. listModuleLine md (read arg2)
  2421. list2 [arg] = do
  2422. wantNameFromInterpretedModule noCanDo arg $ \name -> do
  2423. let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
  2424. case loc of
  2425. RealSrcLoc l ->
  2426. do tickArray <- ASSERT( isExternalName name )
  2427. lift $ getTickArray (GHC.nameModule name)
  2428. let mb_span = findBreakByCoord (Just (GHC.srcLocFile l))
  2429. (GHC.srcLocLine l, GHC.srcLocCol l)
  2430. tickArray
  2431. case mb_span of
  2432. Nothing -> listAround (realSrcLocSpan l) False
  2433. Just (_, UnhelpfulSpan _) -> panic "list2 UnhelpfulSpan"
  2434. Just (_, RealSrcSpan pan) -> listAround pan False
  2435. UnhelpfulLoc _ ->
  2436. noCanDo name $ text "can't find its location: " <>
  2437. ppr loc
  2438. where
  2439. noCanDo n why = printForUser $
  2440. text "cannot list source code for " <> ppr n <> text ": " <> why
  2441. list2 _other =
  2442. liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
  2443. listModuleLine :: Module -> Int -> InputT GHCi ()
  2444. listModuleLine modl line = do
  2445. graph <- GHC.getModuleGraph
  2446. let this = filter ((== modl) . GHC.ms_mod) graph
  2447. case this of
  2448. [] -> panic "listModuleLine"
  2449. summ:_ -> do
  2450. let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
  2451. loc = mkRealSrcLoc (mkFastString (filename)) line 0
  2452. listAround (realSrcLocSpan loc) False
  2453. -- | list a section of a source file around a particular SrcSpan.
  2454. -- If the highlight flag is True, also highlight the span using
  2455. -- start_bold\/end_bold.
  2456. -- GHC files are UTF-8, so we can implement this by:
  2457. -- 1) read the file in as a BS and syntax highlight it as before
  2458. -- 2) convert the BS to String using utf-string, and write it out.
  2459. -- It would be better if we could convert directly between UTF-8 and the
  2460. -- console encoding, of course.
  2461. listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
  2462. listAround pan do_highlight = do
  2463. contents <- liftIO $ BS.readFile (unpackFS file)
  2464. let ls = BS.split '\n' contents
  2465. ls' = take (line2 - line1 + 1 + pad_before + pad_after) $
  2466. drop (line1 - 1 - pad_before) $ ls
  2467. fst_line = max 1 (line1 - pad_before)
  2468. line_nos = [ fst_line .. ]
  2469. highlighted | do_highlight = zipWith highlight line_nos ls'
  2470. | otherwise = [\p -> BS.concat[p,l] | l <- ls']
  2471. bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
  2472. prefixed = zipWith ($) highlighted bs_line_nos
  2473. output = BS.intercalate (BS.pack "\n") prefixed
  2474. utf8Decoded <- liftIO $ BS.useAsCStringLen output
  2475. $ \(p,n) -> utf8DecodeString (castPtr p) n
  2476. liftIO $ putStrLn utf8Decoded
  2477. where
  2478. file = GHC.srcSpanFile pan
  2479. line1 = GHC.srcSpanStartLine pan
  2480. col1 = GHC.srcSpanStartCol pan - 1
  2481. line2 = GHC.srcSpanEndLine pan
  2482. col2 = GHC.srcSpanEndCol pan - 1
  2483. pad_before | line1 == 1 = 0
  2484. | otherwise = 1
  2485. pad_after = 1
  2486. highlight | do_bold = highlight_bold
  2487. | otherwise = highlight_carets
  2488. highlight_bold no line prefix
  2489. | no == line1 && no == line2
  2490. = let (a,r) = BS.splitAt col1 line
  2491. (b,c) = BS.splitAt (col2-col1) r
  2492. in
  2493. BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
  2494. | no == line1
  2495. = let (a,b) = BS.splitAt col1 line in
  2496. BS.concat [prefix, a, BS.pack start_bold, b]
  2497. | no == line2
  2498. = let (a,b) = BS.splitAt col2 line in
  2499. BS.concat [prefix, a, BS.pack end_bold, b]
  2500. | otherwise = BS.concat [prefix, line]
  2501. highlight_carets no line prefix
  2502. | no == line1 && no == line2
  2503. = BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
  2504. BS.replicate (col2-col1) '^']
  2505. | no == line1
  2506. = BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
  2507. prefix, line]
  2508. | no == line2
  2509. = BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
  2510. BS.pack "^^"]
  2511. | otherwise = BS.concat [prefix, line]
  2512. where
  2513. indent = BS.pack (" " ++ replicate (length (show no)) ' ')
  2514. nl = BS.singleton '\n'
  2515. -- --------------------------------------------------------------------------
  2516. -- Tick arrays
  2517. getTickArray :: Module -> GHCi TickArray
  2518. getTickArray modl = do
  2519. st <- getGHCiState
  2520. let arrmap = tickarrays st
  2521. case lookupModuleEnv arrmap modl of
  2522. Just arr -> return arr
  2523. Nothing -> do
  2524. (_breakArray, ticks) <- getModBreak modl
  2525. let arr = mkTickArray (assocs ticks)
  2526. setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
  2527. return arr
  2528. discardTickArrays :: GHCi ()
  2529. discardTickArrays = do
  2530. st <- getGHCiState
  2531. setGHCiState st{tickarrays = emptyModuleEnv}
  2532. mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
  2533. mkTickArray ticks
  2534. = accumArray (flip (:)) [] (1, max_line)
  2535. [ (line, (nm,pan)) | (nm,pan) <- ticks,
  2536. let pan' = toRealSpan pan,
  2537. line <- srcSpanLines pan' ]
  2538. where
  2539. max_line = foldr max 0 (map (GHC.srcSpanEndLine . toRealSpan . snd) ticks)
  2540. srcSpanLines pan = [ GHC.srcSpanStartLine pan .. GHC.srcSpanEndLine pan ]
  2541. toRealSpan (RealSrcSpan pan) = pan
  2542. toRealSpan (UnhelpfulSpan _) = panic "mkTickArray UnhelpfulSpan"
  2543. -- don't reset the counter back to zero?
  2544. discardActiveBreakPoints :: GHCi ()
  2545. discardActiveBreakPoints = do
  2546. st <- getGHCiState
  2547. mapM_ (turnOffBreak.snd) (breaks st)
  2548. setGHCiState $ st { breaks = [] }
  2549. deleteBreak :: Int -> GHCi ()
  2550. deleteBreak identity = do
  2551. st <- getGHCiState
  2552. let oldLocations = breaks st
  2553. (this,rest) = partition (\loc -> fst loc == identity) oldLocations
  2554. if null this
  2555. then printForUser (text "Breakpoint" <+> ppr identity <+>
  2556. text "does not exist")
  2557. else do
  2558. mapM_ (turnOffBreak.snd) this
  2559. setGHCiState $ st { breaks = rest }
  2560. turnOffBreak :: BreakLocation -> GHCi Bool
  2561. turnOffBreak loc = do
  2562. dflags <- getDynFlags
  2563. (arr, _) <- getModBreak (breakModule loc)
  2564. liftIO $ setBreakFlag dflags False arr (breakTick loc)
  2565. getModBreak :: Module -> GHCi (GHC.BreakArray, Array Int SrcSpan)
  2566. getModBreak m = do
  2567. Just mod_info <- GHC.getModuleInfo m
  2568. let modBreaks = GHC.modInfoModBreaks mod_info
  2569. let arr = GHC.modBreaks_flags modBreaks
  2570. let ticks = GHC.modBreaks_locs modBreaks
  2571. return (arr, ticks)
  2572. setBreakFlag :: DynFlags -> Bool -> GHC.BreakArray -> Int -> IO Bool
  2573. setBreakFlag dflags toggle arr i
  2574. | toggle = GHC.setBreakOn dflags arr i
  2575. | otherwise = GHC.setBreakOff dflags arr i
  2576. -- ---------------------------------------------------------------------------
  2577. -- User code exception handling
  2578. -- This is the exception handler for exceptions generated by the
  2579. -- user's code and exceptions coming from children sessions;
  2580. -- it normally just prints out the exception. The
  2581. -- handler must be recursive, in case showing the exception causes
  2582. -- more exceptions to be raised.
  2583. --
  2584. -- Bugfix: if the user closed stdout or stderr, the flushing will fail,
  2585. -- raising another exception. We therefore don't put the recursive
  2586. -- handler arond the flushing operation, so if stderr is closed
  2587. -- GHCi will just die gracefully rather than going into an infinite loop.
  2588. handler :: SomeException -> GHCi Bool
  2589. handler exception = do
  2590. flushInterpBuffers
  2591. liftIO installSignalHandlers
  2592. ghciHandle handler (showException exception >> return False)
  2593. showException :: SomeException -> GHCi ()
  2594. showException se =
  2595. liftIO $ case fromException se of
  2596. -- omit the location for CmdLineError:
  2597. Just (CmdLineError s) -> putException s
  2598. -- ditto:
  2599. Just ph@(PhaseFailed {}) -> putException (showGhcException ph "")
  2600. Just other_ghc_ex -> putException (show other_ghc_ex)
  2601. Nothing ->
  2602. case fromException se of
  2603. Just UserInterrupt -> putException "Interrupted."
  2604. _ -> putException ("*** Exception: " ++ show se)
  2605. where
  2606. putException = hPutStrLn stderr
  2607. -----------------------------------------------------------------------------
  2608. -- recursive exception handlers
  2609. -- Don't forget to unblock async exceptions in the handler, or if we're
  2610. -- in an exception loop (eg. let a = error a in a) the ^C exception
  2611. -- may never be delivered. Thanks to Marcin for pointing out the bug.
  2612. ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
  2613. ghciHandle h m = gmask $ \restore -> do
  2614. dflags <- getDynFlags
  2615. gcatch (restore (GHC.prettyPrintGhcErrors dflags m)) $ \e -> restore (h e)
  2616. ghciTry :: GHCi a -> GHCi (Either SomeException a)
  2617. ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
  2618. tryBool :: GHCi a -> GHCi Bool
  2619. tryBool m = do
  2620. r <- ghciTry m
  2621. case r of
  2622. Left _ -> return False
  2623. Right _ -> return True
  2624. -- ----------------------------------------------------------------------------
  2625. -- Utils
  2626. lookupModule :: GHC.GhcMonad m => String -> m Module
  2627. lookupModule mName = lookupModuleName (GHC.mkModuleName mName)
  2628. lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
  2629. lookupModuleName mName = GHC.lookupModule mName Nothing
  2630. isHomeModule :: Module -> Bool
  2631. isHomeModule m = GHC.modulePackageId m == mainPackageId
  2632. -- TODO: won't work if home dir is encoded.
  2633. -- (changeDirectory may not work either in that case.)
  2634. expandPath :: MonadIO m => String -> InputT m String
  2635. expandPath = liftIO . expandPathIO
  2636. expandPathIO :: String -> IO String
  2637. expandPathIO p =
  2638. case dropWhile isSpace p of
  2639. ('~':d) -> do
  2640. tilde <- getHomeDirectory -- will fail if HOME not defined
  2641. return (tilde ++ '/':d)
  2642. other ->
  2643. return other
  2644. wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
  2645. wantInterpretedModule str = wantInterpretedModuleName (GHC.mkModuleName str)
  2646. wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
  2647. wantInterpretedModuleName modname = do
  2648. modl <- lookupModuleName modname
  2649. let str = moduleNameString modname
  2650. dflags <- getDynFlags
  2651. when (GHC.modulePackageId modl /= thisPackage dflags) $
  2652. throwGhcException (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
  2653. is_interpreted <- GHC.moduleIsInterpreted modl
  2654. when (not is_interpreted) $
  2655. throwGhcException (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
  2656. return modl
  2657. wantNameFromInterpretedModule :: GHC.GhcMonad m
  2658. => (Name -> SDoc -> m ())
  2659. -> String
  2660. -> (Name -> m ())
  2661. -> m ()
  2662. wantNameFromInterpretedModule noCanDo str and_then =
  2663. handleSourceError GHC.printException $ do
  2664. names <- GHC.parseName str
  2665. case names of
  2666. [] -> return ()
  2667. (n:_) -> do
  2668. let modl = ASSERT( isExternalName n ) GHC.nameModule n
  2669. if not (GHC.isExternalName n)
  2670. then noCanDo n $ ppr n <>
  2671. text " is not defined in an interpreted module"
  2672. else do
  2673. is_interpreted <- GHC.moduleIsInterpreted modl
  2674. if not is_interpreted
  2675. then noCanDo n $ text "module " <> ppr modl <>
  2676. text " is not interpreted"
  2677. else and_then n