PageRenderTime 79ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc/InteractiveUI.hs

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