PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/ghc-7.0.4/ghc/InteractiveUI.hs

http://picorec.googlecode.com/
Haskell | 1680 lines | 1295 code | 208 blank | 177 comment | 84 complexity | 255d7e3368114dd266f2cf21fb4cb77f MD5 | raw file
Possible License(s): BSD-3-Clause, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. {-# OPTIONS -fno-cse #-}
  2. -- -fno-cse is needed for GLOBAL_VAR's to behave properly
  3. {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
  4. -----------------------------------------------------------------------------
  5. --
  6. -- GHC Interactive User Interface
  7. --
  8. -- (c) The GHC Team 2005-2006
  9. --
  10. -----------------------------------------------------------------------------
  11. module InteractiveUI ( interactiveUI, ghciWelcomeMsg ) where
  12. #include "HsVersions.h"
  13. import qualified GhciMonad
  14. import GhciMonad hiding (runStmt)
  15. import GhciTags
  16. import Debugger
  17. -- The GHC interface
  18. import qualified GHC hiding (resume, runStmt)
  19. import GHC ( LoadHowMuch(..), Target(..), TargetId(..),
  20. TyThing(..), Phase,
  21. BreakIndex, Resume, SingleStep,
  22. Ghc, handleSourceError )
  23. import PprTyThing
  24. import DynFlags
  25. import Packages
  26. -- import PackageConfig
  27. import UniqFM
  28. import HscTypes ( handleFlagWarnings )
  29. import HsImpExp
  30. import qualified RdrName ( getGRE_NameQualifier_maybes ) -- should this come via GHC?
  31. import RdrName (RdrName)
  32. import Outputable hiding (printForUser, printForUserPartWay)
  33. import Module -- for ModuleEnv
  34. import Name
  35. import SrcLoc
  36. -- Other random utilities
  37. import Digraph
  38. import BasicTypes hiding (isTopLevel)
  39. import Panic hiding (showException)
  40. import Config
  41. import StaticFlags
  42. import Linker
  43. import Util
  44. import NameSet
  45. import Maybes ( orElse, expectJust )
  46. import FastString
  47. import Encoding
  48. import Foreign.C
  49. #ifndef mingw32_HOST_OS
  50. import System.Posix hiding (getEnv)
  51. #else
  52. import qualified System.Win32
  53. #endif
  54. import System.Console.Haskeline as Haskeline
  55. import qualified System.Console.Haskeline.Encoding as Encoding
  56. import Control.Monad.Trans
  57. --import SystemExts
  58. import Exception hiding (catch, block, unblock)
  59. -- import Control.Concurrent
  60. import System.FilePath
  61. import qualified Data.ByteString.Char8 as BS
  62. import Data.List
  63. import Data.Maybe
  64. import System.Cmd
  65. import System.Environment
  66. import System.Exit ( exitWith, ExitCode(..) )
  67. import System.Directory
  68. import System.IO
  69. import System.IO.Error as IO
  70. import Data.Char
  71. import Data.Array
  72. import Control.Monad as Monad
  73. import Text.Printf
  74. import Foreign
  75. import GHC.Exts ( unsafeCoerce# )
  76. #if __GLASGOW_HASKELL__ >= 611
  77. import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
  78. import GHC.IO.Handle ( hFlushAll )
  79. #else
  80. import GHC.IOBase ( IOErrorType(InvalidArgument) )
  81. #endif
  82. import GHC.TopHandler
  83. import Data.IORef ( IORef, readIORef, writeIORef )
  84. -----------------------------------------------------------------------------
  85. ghciWelcomeMsg :: String
  86. ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
  87. ": http://www.haskell.org/ghc/ :? for help"
  88. cmdName :: Command -> String
  89. cmdName (n,_,_) = n
  90. GLOBAL_VAR(macros_ref, [], [Command])
  91. builtin_commands :: [Command]
  92. builtin_commands = [
  93. -- Hugs users are accustomed to :e, so make sure it doesn't overlap
  94. ("?", keepGoing help, noCompletion),
  95. ("add", keepGoingPaths addModule, completeFilename),
  96. ("abandon", keepGoing abandonCmd, noCompletion),
  97. ("break", keepGoing breakCmd, completeIdentifier),
  98. ("back", keepGoing backCmd, noCompletion),
  99. ("browse", keepGoing' (browseCmd False), completeModule),
  100. ("browse!", keepGoing' (browseCmd True), completeModule),
  101. ("cd", keepGoing' changeDirectory, completeFilename),
  102. ("check", keepGoing' checkModule, completeHomeModule),
  103. ("continue", keepGoing continueCmd, noCompletion),
  104. ("cmd", keepGoing cmdCmd, completeExpression),
  105. ("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
  106. ("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
  107. ("def", keepGoing (defineMacro False), completeExpression),
  108. ("def!", keepGoing (defineMacro True), completeExpression),
  109. ("delete", keepGoing deleteCmd, noCompletion),
  110. ("edit", keepGoing editFile, completeFilename),
  111. ("etags", keepGoing createETagsFileCmd, completeFilename),
  112. ("force", keepGoing forceCmd, completeExpression),
  113. ("forward", keepGoing forwardCmd, noCompletion),
  114. ("help", keepGoing help, noCompletion),
  115. ("history", keepGoing historyCmd, noCompletion),
  116. ("info", keepGoing' info, completeIdentifier),
  117. ("kind", keepGoing' kindOfType, completeIdentifier),
  118. ("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
  119. ("list", keepGoing' listCmd, noCompletion),
  120. ("module", keepGoing setContext, completeSetModule),
  121. ("main", keepGoing runMain, completeFilename),
  122. ("print", keepGoing printCmd, completeExpression),
  123. ("quit", quit, noCompletion),
  124. ("reload", keepGoing' reloadModule, noCompletion),
  125. ("run", keepGoing runRun, completeFilename),
  126. ("set", keepGoing setCmd, completeSetOptions),
  127. ("show", keepGoing showCmd, completeShowOptions),
  128. ("sprint", keepGoing sprintCmd, completeExpression),
  129. ("step", keepGoing stepCmd, completeIdentifier),
  130. ("steplocal", keepGoing stepLocalCmd, completeIdentifier),
  131. ("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
  132. ("type", keepGoing' typeOfExpr, completeExpression),
  133. ("trace", keepGoing traceCmd, completeExpression),
  134. ("undef", keepGoing undefineMacro, completeMacro),
  135. ("unset", keepGoing unsetOptions, completeSetOptions)
  136. ]
  137. -- We initialize readline (in the interactiveUI function) to use
  138. -- word_break_chars as the default set of completion word break characters.
  139. -- This can be overridden for a particular command (for example, filename
  140. -- expansion shouldn't consider '/' to be a word break) by setting the third
  141. -- entry in the Command tuple above.
  142. --
  143. -- NOTE: in order for us to override the default correctly, any custom entry
  144. -- must be a SUBSET of word_break_chars.
  145. word_break_chars :: String
  146. word_break_chars = let symbols = "!#$%&*+/<=>?@\\^|-~"
  147. specials = "(),;[]`{}"
  148. spaces = " \t\n"
  149. in spaces ++ specials ++ symbols
  150. flagWordBreakChars :: String
  151. flagWordBreakChars = " \t\n"
  152. keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
  153. keepGoing a str = keepGoing' (lift . a) str
  154. keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
  155. keepGoing' a str = a str >> return False
  156. keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
  157. keepGoingPaths a str
  158. = do case toArgs str of
  159. Left err -> Encoding.encode err >>= liftIO . BS.hPutStrLn stderr
  160. Right args -> a args
  161. return False
  162. shortHelpText :: String
  163. shortHelpText = "use :? for help.\n"
  164. helpText :: String
  165. helpText =
  166. " Commands available from the prompt:\n" ++
  167. "\n" ++
  168. " <statement> evaluate/run <statement>\n" ++
  169. " : repeat last command\n" ++
  170. " :{\\n ..lines.. \\n:}\\n multiline command\n" ++
  171. " :add [*]<module> ... add module(s) to the current target set\n" ++
  172. " :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
  173. " (!: more details; *: all top-level names)\n" ++
  174. " :cd <dir> change directory to <dir>\n" ++
  175. " :cmd <expr> run the commands returned by <expr>::IO String\n" ++
  176. " :ctags[!] [<file>] create tags file for Vi (default: \"tags\")\n" ++
  177. " (!: use regex instead of line number)\n" ++
  178. " :def <cmd> <expr> define a command :<cmd>\n" ++
  179. " :edit <file> edit file\n" ++
  180. " :edit edit last module\n" ++
  181. " :etags [<file>] create tags file for Emacs (default: \"TAGS\")\n" ++
  182. " :help, :? display this list of commands\n" ++
  183. " :info [<name> ...] display information about the given names\n" ++
  184. " :kind <type> show the kind of <type>\n" ++
  185. " :load [*]<module> ... load module(s) and their dependents\n" ++
  186. " :main [<arguments> ...] run the main function with the given arguments\n" ++
  187. " :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
  188. " :quit exit GHCi\n" ++
  189. " :reload reload the current module set\n" ++
  190. " :run function [<arguments> ...] run the function with the given arguments\n" ++
  191. " :type <expr> show the type of <expr>\n" ++
  192. " :undef <cmd> undefine user-defined command :<cmd>\n" ++
  193. " :!<command> run the shell command <command>\n" ++
  194. "\n" ++
  195. " -- Commands for debugging:\n" ++
  196. "\n" ++
  197. " :abandon at a breakpoint, abandon current computation\n" ++
  198. " :back go back in the history (after :trace)\n" ++
  199. " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
  200. " :break <name> set a breakpoint on the specified function\n" ++
  201. " :continue resume after a breakpoint\n" ++
  202. " :delete <number> delete the specified breakpoint\n" ++
  203. " :delete * delete all breakpoints\n" ++
  204. " :force <expr> print <expr>, forcing unevaluated parts\n" ++
  205. " :forward go forward in the history (after :back)\n" ++
  206. " :history [<n>] after :trace, show the execution history\n" ++
  207. " :list show the source code around current breakpoint\n" ++
  208. " :list identifier show the source code for <identifier>\n" ++
  209. " :list [<module>] <line> show the source code around line number <line>\n" ++
  210. " :print [<name> ...] prints a value without forcing its computation\n" ++
  211. " :sprint [<name> ...] simplifed version of :print\n" ++
  212. " :step single-step after stopping at a breakpoint\n"++
  213. " :step <expr> single-step into <expr>\n"++
  214. " :steplocal single-step within the current top-level binding\n"++
  215. " :stepmodule single-step restricted to the current module\n"++
  216. " :trace trace after stopping at a breakpoint\n"++
  217. " :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
  218. "\n" ++
  219. " -- Commands for changing settings:\n" ++
  220. "\n" ++
  221. " :set <option> ... set options\n" ++
  222. " :set args <arg> ... set the arguments returned by System.getArgs\n" ++
  223. " :set prog <progname> set the value returned by System.getProgName\n" ++
  224. " :set prompt <prompt> set the prompt used in GHCi\n" ++
  225. " :set editor <cmd> set the command used for :edit\n" ++
  226. " :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
  227. " :unset <option> ... unset options\n" ++
  228. "\n" ++
  229. " Options for ':set' and ':unset':\n" ++
  230. "\n" ++
  231. " +r revert top-level expressions after each evaluation\n" ++
  232. " +s print timing/memory stats after each evaluation\n" ++
  233. " +t print type after evaluation\n" ++
  234. " -<flags> most GHC command line flags can also be set here\n" ++
  235. " (eg. -v2, -fglasgow-exts, etc.)\n" ++
  236. " for GHCi-specific flags, see User's Guide,\n"++
  237. " Flag reference, Interactive-mode options\n" ++
  238. "\n" ++
  239. " -- Commands for displaying information:\n" ++
  240. "\n" ++
  241. " :show bindings show the current bindings made at the prompt\n" ++
  242. " :show breaks show the active breakpoints\n" ++
  243. " :show context show the breakpoint context\n" ++
  244. " :show modules show the currently loaded modules\n" ++
  245. " :show packages show the currently active package flags\n" ++
  246. " :show languages show the currently active language flags\n" ++
  247. " :show <setting> show value of <setting>, which is one of\n" ++
  248. " [args, prog, prompt, editor, stop]\n" ++
  249. "\n"
  250. findEditor :: IO String
  251. findEditor = do
  252. getEnv "EDITOR"
  253. `IO.catch` \_ -> do
  254. #if mingw32_HOST_OS
  255. win <- System.Win32.getWindowsDirectory
  256. return (win </> "notepad.exe")
  257. #else
  258. return ""
  259. #endif
  260. foreign import ccall unsafe "rts_isProfiled" isProfiled :: IO CInt
  261. default_progname, default_prompt, default_stop :: String
  262. default_progname = "<interactive>"
  263. default_prompt = "%s> "
  264. default_stop = ""
  265. default_args :: [String]
  266. default_args = []
  267. interactiveUI :: [(FilePath, Maybe Phase)] -> Maybe [String]
  268. -> Ghc ()
  269. interactiveUI srcs maybe_exprs = do
  270. -- although GHCi compiles with -prof, it is not usable: the byte-code
  271. -- compiler and interpreter don't work with profiling. So we check for
  272. -- this up front and emit a helpful error message (#2197)
  273. i <- liftIO $ isProfiled
  274. when (i /= 0) $
  275. ghcError (InstallationError "GHCi cannot be used when compiled with -prof")
  276. -- HACK! If we happen to get into an infinite loop (eg the user
  277. -- types 'let x=x in x' at the prompt), then the thread will block
  278. -- on a blackhole, and become unreachable during GC. The GC will
  279. -- detect that it is unreachable and send it the NonTermination
  280. -- exception. However, since the thread is unreachable, everything
  281. -- it refers to might be finalized, including the standard Handles.
  282. -- This sounds like a bug, but we don't have a good solution right
  283. -- now.
  284. _ <- liftIO $ newStablePtr stdin
  285. _ <- liftIO $ newStablePtr stdout
  286. _ <- liftIO $ newStablePtr stderr
  287. -- Initialise buffering for the *interpreted* I/O system
  288. initInterpBuffering
  289. liftIO $ when (isNothing maybe_exprs) $ do
  290. -- Only for GHCi (not runghc and ghc -e):
  291. -- Turn buffering off for the compiled program's stdout/stderr
  292. turnOffBuffering
  293. -- Turn buffering off for GHCi's stdout
  294. hFlush stdout
  295. hSetBuffering stdout NoBuffering
  296. -- We don't want the cmd line to buffer any input that might be
  297. -- intended for the program, so unbuffer stdin.
  298. hSetBuffering stdin NoBuffering
  299. #if defined(mingw32_HOST_OS) && __GLASGOW_HASKELL__ >= 611
  300. -- On Unix, stdin will use the locale encoding. The IO library
  301. -- doesn't do this on Windows (yet), so for now we use UTF-8,
  302. -- for consistency with GHC 6.10 and to make the tests work.
  303. hSetEncoding stdin utf8
  304. #endif
  305. -- initial context is just the Prelude
  306. prel_mod <- GHC.lookupModule (GHC.mkModuleName "Prelude") Nothing
  307. GHC.setContext [] [(prel_mod, Nothing)]
  308. default_editor <- liftIO $ findEditor
  309. startGHCi (runGHCi srcs maybe_exprs)
  310. GHCiState{ progname = default_progname,
  311. args = default_args,
  312. prompt = default_prompt,
  313. stop = default_stop,
  314. editor = default_editor,
  315. -- session = session,
  316. options = [],
  317. prelude = prel_mod,
  318. break_ctr = 0,
  319. breaks = [],
  320. tickarrays = emptyModuleEnv,
  321. last_command = Nothing,
  322. cmdqueue = [],
  323. remembered_ctx = [],
  324. ghc_e = isJust maybe_exprs
  325. }
  326. return ()
  327. withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
  328. withGhcAppData right left = do
  329. either_dir <- IO.try (getAppUserDataDirectory "ghc")
  330. case either_dir of
  331. Right dir ->
  332. do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
  333. right dir
  334. _ -> left
  335. runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
  336. runGHCi paths maybe_exprs = do
  337. let
  338. read_dot_files = not opt_IgnoreDotGhci
  339. current_dir = return (Just ".ghci")
  340. app_user_dir = liftIO $ withGhcAppData
  341. (\dir -> return (Just (dir </> "ghci.conf")))
  342. (return Nothing)
  343. home_dir = do
  344. either_dir <- liftIO $ IO.try (getEnv "HOME")
  345. case either_dir of
  346. Right home -> return (Just (home </> ".ghci"))
  347. _ -> return Nothing
  348. canonicalizePath' :: FilePath -> IO (Maybe FilePath)
  349. canonicalizePath' fp = liftM Just (canonicalizePath fp)
  350. `catchIO` \_ -> return Nothing
  351. sourceConfigFile :: FilePath -> GHCi ()
  352. sourceConfigFile file = do
  353. exists <- liftIO $ doesFileExist file
  354. when exists $ do
  355. dir_ok <- liftIO $ checkPerms (getDirectory file)
  356. file_ok <- liftIO $ checkPerms file
  357. when (dir_ok && file_ok) $ do
  358. either_hdl <- liftIO $ IO.try (openFile file ReadMode)
  359. case either_hdl of
  360. Left _e -> return ()
  361. -- NOTE: this assumes that runInputT won't affect the terminal;
  362. -- can we assume this will always be the case?
  363. -- This would be a good place for runFileInputT.
  364. Right hdl ->
  365. do runInputTWithPrefs defaultPrefs defaultSettings $
  366. runCommands $ fileLoop hdl
  367. liftIO (hClose hdl `IO.catch` \_ -> return ())
  368. where
  369. getDirectory f = case takeDirectory f of "" -> "."; d -> d
  370. when (read_dot_files) $ do
  371. mcfgs0 <- sequence [ current_dir, app_user_dir, home_dir ]
  372. mcfgs <- liftIO $ mapM canonicalizePath' (catMaybes mcfgs0)
  373. mapM_ sourceConfigFile $ nub $ catMaybes mcfgs
  374. -- nub, because we don't want to read .ghci twice if the
  375. -- CWD is $HOME.
  376. -- Perform a :load for files given on the GHCi command line
  377. -- When in -e mode, if the load fails then we want to stop
  378. -- immediately rather than going on to evaluate the expression.
  379. when (not (null paths)) $ do
  380. ok <- ghciHandle (\e -> do showException e; return Failed) $
  381. -- TODO: this is a hack.
  382. runInputTWithPrefs defaultPrefs defaultSettings $ do
  383. let (filePaths, phases) = unzip paths
  384. filePaths' <- mapM (Encoding.decode . BS.pack) filePaths
  385. loadModule (zip filePaths' phases)
  386. when (isJust maybe_exprs && failed ok) $
  387. liftIO (exitWith (ExitFailure 1))
  388. -- if verbosity is greater than 0, or we are connected to a
  389. -- terminal, display the prompt in the interactive loop.
  390. is_tty <- liftIO (hIsTerminalDevice stdin)
  391. dflags <- getDynFlags
  392. let show_prompt = verbosity dflags > 0 || is_tty
  393. case maybe_exprs of
  394. Nothing ->
  395. do
  396. -- enter the interactive loop
  397. runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
  398. Just exprs -> do
  399. -- just evaluate the expression we were given
  400. enqueueCommands exprs
  401. let handle e = do st <- getGHCiState
  402. -- flush the interpreter's stdout/stderr on exit (#3890)
  403. flushInterpBuffers
  404. -- Jump through some hoops to get the
  405. -- current progname in the exception text:
  406. -- <progname>: <exception>
  407. liftIO $ withProgName (progname st)
  408. -- this used to be topHandlerFastExit, see #2228
  409. $ topHandler e
  410. runInputTWithPrefs defaultPrefs defaultSettings $ do
  411. runCommands' handle (return Nothing)
  412. -- and finally, exit
  413. liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
  414. runGHCiInput :: InputT GHCi a -> GHCi a
  415. runGHCiInput f = do
  416. histFile <- liftIO $ withGhcAppData (\dir -> return (Just (dir </> "ghci_history")))
  417. (return Nothing)
  418. let settings = setComplete ghciCompleteWord
  419. $ defaultSettings {historyFile = histFile}
  420. runInputT settings f
  421. nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
  422. nextInputLine show_prompt is_tty
  423. | is_tty = do
  424. prompt <- if show_prompt then lift mkPrompt else return ""
  425. getInputLine prompt
  426. | otherwise = do
  427. when show_prompt $ lift mkPrompt >>= liftIO . putStr
  428. fileLoop stdin
  429. -- NOTE: We only read .ghci files if they are owned by the current user,
  430. -- and aren't world writable. Otherwise, we could be accidentally
  431. -- running code planted by a malicious third party.
  432. -- Furthermore, We only read ./.ghci if . is owned by the current user
  433. -- and isn't writable by anyone else. I think this is sufficient: we
  434. -- don't need to check .. and ../.. etc. because "." always refers to
  435. -- the same directory while a process is running.
  436. checkPerms :: String -> IO Bool
  437. #ifdef mingw32_HOST_OS
  438. checkPerms _ =
  439. return True
  440. #else
  441. checkPerms name =
  442. handleIO (\_ -> return False) $ do
  443. st <- getFileStatus name
  444. me <- getRealUserID
  445. if fileOwner st /= me then do
  446. putStrLn $ "WARNING: " ++ name ++ " is owned by someone else, IGNORING!"
  447. return False
  448. else do
  449. let mode = System.Posix.fileMode st
  450. if (groupWriteMode == (mode `intersectFileModes` groupWriteMode))
  451. || (otherWriteMode == (mode `intersectFileModes` otherWriteMode))
  452. then do
  453. putStrLn $ "*** WARNING: " ++ name ++
  454. " is writable by someone else, IGNORING!"
  455. return False
  456. else return True
  457. #endif
  458. fileLoop :: MonadIO m => Handle -> InputT m (Maybe String)
  459. fileLoop hdl = do
  460. l <- liftIO $ IO.try $ hGetLine hdl
  461. case l of
  462. Left e | isEOFError e -> return Nothing
  463. | InvalidArgument <- etype -> return Nothing
  464. | otherwise -> liftIO $ ioError e
  465. where etype = ioeGetErrorType e
  466. -- treat InvalidArgument in the same way as EOF:
  467. -- this can happen if the user closed stdin, or
  468. -- perhaps did getContents which closes stdin at
  469. -- EOF.
  470. Right l -> return (Just l)
  471. mkPrompt :: GHCi String
  472. mkPrompt = do
  473. (toplevs,exports) <- GHC.getContext
  474. resumes <- GHC.getResumeContext
  475. -- st <- getGHCiState
  476. context_bit <-
  477. case resumes of
  478. [] -> return empty
  479. r:_ -> do
  480. let ix = GHC.resumeHistoryIx r
  481. if ix == 0
  482. then return (brackets (ppr (GHC.resumeSpan r)) <> space)
  483. else do
  484. let hist = GHC.resumeHistory r !! (ix-1)
  485. span <- GHC.getHistorySpan hist
  486. return (brackets (ppr (negate ix) <> char ':'
  487. <+> ppr span) <> space)
  488. let
  489. dots | _:rs <- resumes, not (null rs) = text "... "
  490. | otherwise = empty
  491. modules_bit =
  492. -- ToDo: maybe...
  493. -- let (btoplevs, bexports) = fromMaybe ([],[]) (remembered_ctx st) in
  494. -- hsep (map (\m -> text "!*" <> ppr (GHC.moduleName m)) btoplevs) <+>
  495. -- hsep (map (\m -> char '!' <> ppr (GHC.moduleName m)) bexports) <+>
  496. hsep (map (\m -> char '*' <> ppr (GHC.moduleName m)) toplevs) <+>
  497. hsep (map (ppr . GHC.moduleName) (nub (map fst exports)))
  498. deflt_prompt = dots <> context_bit <> modules_bit
  499. f ('%':'s':xs) = deflt_prompt <> f xs
  500. f ('%':'%':xs) = char '%' <> f xs
  501. f (x:xs) = char x <> f xs
  502. f [] = empty
  503. --
  504. st <- getGHCiState
  505. return (showSDoc (f (prompt st)))
  506. queryQueue :: GHCi (Maybe String)
  507. queryQueue = do
  508. st <- getGHCiState
  509. case cmdqueue st of
  510. [] -> return Nothing
  511. c:cs -> do setGHCiState st{ cmdqueue = cs }
  512. return (Just c)
  513. runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
  514. runCommands = runCommands' handler
  515. runCommands' :: (SomeException -> GHCi Bool) -- Exception handler
  516. -> InputT GHCi (Maybe String) -> InputT GHCi ()
  517. runCommands' eh getCmd = do
  518. b <- ghandle (\e -> case fromException e of
  519. Just UserInterrupt -> return False
  520. _ -> case fromException e of
  521. Just ghc_e ->
  522. do liftIO (print (ghc_e :: GhcException))
  523. return True
  524. _other ->
  525. liftIO (Exception.throwIO e))
  526. (runOneCommand eh getCmd)
  527. if b then return () else runCommands' eh getCmd
  528. runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
  529. -> InputT GHCi Bool
  530. runOneCommand eh getCmd = do
  531. mb_cmd <- noSpace (lift queryQueue)
  532. mb_cmd <- maybe (noSpace getCmd) (return . Just) mb_cmd
  533. case mb_cmd of
  534. Nothing -> return True
  535. Just c -> ghciHandle (lift . eh) $
  536. handleSourceError printErrorAndKeepGoing
  537. (doCommand c)
  538. where
  539. printErrorAndKeepGoing err = do
  540. GHC.printExceptionAndWarnings err
  541. return False
  542. noSpace q = q >>= maybe (return Nothing)
  543. (\c->case removeSpaces c of
  544. "" -> noSpace q
  545. ":{" -> multiLineCmd q
  546. c -> return (Just c) )
  547. multiLineCmd q = do
  548. st <- lift getGHCiState
  549. let p = prompt st
  550. lift $ setGHCiState st{ prompt = "%s| " }
  551. mb_cmd <- collectCommand q ""
  552. lift $ getGHCiState >>= \st->setGHCiState st{ prompt = p }
  553. return mb_cmd
  554. -- we can't use removeSpaces for the sublines here, so
  555. -- multiline commands are somewhat more brittle against
  556. -- fileformat errors (such as \r in dos input on unix),
  557. -- we get rid of any extra spaces for the ":}" test;
  558. -- we also avoid silent failure if ":}" is not found;
  559. -- and since there is no (?) valid occurrence of \r (as
  560. -- opposed to its String representation, "\r") inside a
  561. -- ghci command, we replace any such with ' ' (argh:-(
  562. collectCommand q c = q >>=
  563. maybe (liftIO (ioError collectError))
  564. (\l->if removeSpaces l == ":}"
  565. then return (Just $ removeSpaces c)
  566. else collectCommand q (c ++ "\n" ++ map normSpace l))
  567. where normSpace '\r' = ' '
  568. normSpace c = c
  569. -- QUESTION: is userError the one to use here?
  570. collectError = userError "unterminated multiline command :{ .. :}"
  571. doCommand (':' : cmd) = specialCommand cmd
  572. doCommand stmt = do _ <- timeIt $ lift $ runStmt stmt GHC.RunToCompletion
  573. return False
  574. enqueueCommands :: [String] -> GHCi ()
  575. enqueueCommands cmds = do
  576. st <- getGHCiState
  577. setGHCiState st{ cmdqueue = cmds ++ cmdqueue st }
  578. runStmt :: String -> SingleStep -> GHCi Bool
  579. runStmt stmt step
  580. | null (filter (not.isSpace) stmt)
  581. = return False
  582. | "import " `isPrefixOf` stmt
  583. = do newContextCmd (Import stmt); return False
  584. | otherwise
  585. = do
  586. #if __GLASGOW_HASKELL__ >= 611
  587. -- In the new IO library, read handles buffer data even if the Handle
  588. -- is set to NoBuffering. This causes problems for GHCi where there
  589. -- are really two stdin Handles. So we flush any bufferred data in
  590. -- GHCi's stdin Handle here (only relevant if stdin is attached to
  591. -- a file, otherwise the read buffer can't be flushed).
  592. _ <- liftIO $ IO.try $ hFlushAll stdin
  593. #endif
  594. result <- withFlattenedDynflags $ GhciMonad.runStmt stmt step
  595. afterRunStmt (const True) result
  596. --afterRunStmt :: GHC.RunResult -> GHCi Bool
  597. -- False <=> the statement failed to compile
  598. afterRunStmt :: (SrcSpan -> Bool) -> GHC.RunResult -> GHCi Bool
  599. afterRunStmt _ (GHC.RunException e) = throw e
  600. afterRunStmt step_here run_result = do
  601. resumes <- GHC.getResumeContext
  602. case run_result of
  603. GHC.RunOk names -> do
  604. show_types <- isOptionSet ShowType
  605. when show_types $ printTypeOfNames names
  606. GHC.RunBreak _ names mb_info
  607. | isNothing mb_info ||
  608. step_here (GHC.resumeSpan $ head resumes) -> do
  609. mb_id_loc <- toBreakIdAndLocation mb_info
  610. let breakCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
  611. if (null breakCmd)
  612. then printStoppedAtBreakInfo (head resumes) names
  613. else enqueueCommands [breakCmd]
  614. -- run the command set with ":set stop <cmd>"
  615. st <- getGHCiState
  616. enqueueCommands [stop st]
  617. return ()
  618. | otherwise -> resume step_here GHC.SingleStep >>=
  619. afterRunStmt step_here >> return ()
  620. _ -> return ()
  621. flushInterpBuffers
  622. liftIO installSignalHandlers
  623. b <- isOptionSet RevertCAFs
  624. when b revertCAFs
  625. return (case run_result of GHC.RunOk _ -> True; _ -> False)
  626. toBreakIdAndLocation ::
  627. Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
  628. toBreakIdAndLocation Nothing = return Nothing
  629. toBreakIdAndLocation (Just info) = do
  630. let mod = GHC.breakInfo_module info
  631. nm = GHC.breakInfo_number info
  632. st <- getGHCiState
  633. return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
  634. breakModule loc == mod,
  635. breakTick loc == nm ]
  636. printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
  637. printStoppedAtBreakInfo resume names = do
  638. printForUser $ ptext (sLit "Stopped at") <+>
  639. ppr (GHC.resumeSpan resume)
  640. -- printTypeOfNames session names
  641. let namesSorted = sortBy compareNames names
  642. tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
  643. docs <- pprTypeAndContents [id | AnId id <- tythings]
  644. printForUserPartWay docs
  645. printTypeOfNames :: [Name] -> GHCi ()
  646. printTypeOfNames names
  647. = mapM_ (printTypeOfName ) $ sortBy compareNames names
  648. compareNames :: Name -> Name -> Ordering
  649. n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
  650. where compareWith n = (getOccString n, getSrcSpan n)
  651. printTypeOfName :: Name -> GHCi ()
  652. printTypeOfName n
  653. = do maybe_tything <- GHC.lookupName n
  654. case maybe_tything of
  655. Nothing -> return ()
  656. Just thing -> printTyThing thing
  657. data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
  658. specialCommand :: String -> InputT GHCi Bool
  659. specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
  660. specialCommand str = do
  661. let (cmd,rest) = break isSpace str
  662. maybe_cmd <- lift $ lookupCommand cmd
  663. case maybe_cmd of
  664. GotCommand (_,f,_) -> f (dropWhile isSpace rest)
  665. BadCommand ->
  666. do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
  667. ++ shortHelpText)
  668. return False
  669. NoLastCommand ->
  670. do liftIO $ hPutStr stdout ("there is no last command to perform\n"
  671. ++ shortHelpText)
  672. return False
  673. lookupCommand :: String -> GHCi (MaybeCommand)
  674. lookupCommand "" = do
  675. st <- getGHCiState
  676. case last_command st of
  677. Just c -> return $ GotCommand c
  678. Nothing -> return NoLastCommand
  679. lookupCommand str = do
  680. mc <- liftIO $ lookupCommand' str
  681. st <- getGHCiState
  682. setGHCiState st{ last_command = mc }
  683. return $ case mc of
  684. Just c -> GotCommand c
  685. Nothing -> BadCommand
  686. lookupCommand' :: String -> IO (Maybe Command)
  687. lookupCommand' ":" = return Nothing
  688. lookupCommand' str' = do
  689. macros <- readIORef macros_ref
  690. let{ (str, cmds) = case str' of
  691. ':' : rest -> (rest, builtin_commands)
  692. _ -> (str', macros ++ builtin_commands) }
  693. -- look for exact match first, then the first prefix match
  694. return $ case [ c | c <- cmds, str == cmdName c ] of
  695. c:_ -> Just c
  696. [] -> case [ c | c@(s,_,_) <- cmds, str `isPrefixOf` s ] of
  697. [] -> Nothing
  698. c:_ -> Just c
  699. getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
  700. getCurrentBreakSpan = do
  701. resumes <- GHC.getResumeContext
  702. case resumes of
  703. [] -> return Nothing
  704. (r:_) -> do
  705. let ix = GHC.resumeHistoryIx r
  706. if ix == 0
  707. then return (Just (GHC.resumeSpan r))
  708. else do
  709. let hist = GHC.resumeHistory r !! (ix-1)
  710. span <- GHC.getHistorySpan hist
  711. return (Just span)
  712. getCurrentBreakModule :: GHCi (Maybe Module)
  713. getCurrentBreakModule = do
  714. resumes <- GHC.getResumeContext
  715. case resumes of
  716. [] -> return Nothing
  717. (r:_) -> do
  718. let ix = GHC.resumeHistoryIx r
  719. if ix == 0
  720. then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
  721. else do
  722. let hist = GHC.resumeHistory r !! (ix-1)
  723. return $ Just $ GHC.getHistoryModule hist
  724. -----------------------------------------------------------------------------
  725. -- Commands
  726. noArgs :: GHCi () -> String -> GHCi ()
  727. noArgs m "" = m
  728. noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
  729. help :: String -> GHCi ()
  730. help _ = liftIO (putStr helpText)
  731. info :: String -> InputT GHCi ()
  732. info "" = ghcError (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
  733. info s = handleSourceError GHC.printExceptionAndWarnings $
  734. withFlattenedDynflags $ do
  735. { let names = words s
  736. ; dflags <- getDynFlags
  737. ; let pefas = dopt Opt_PrintExplicitForalls dflags
  738. ; mapM_ (infoThing pefas) names }
  739. where
  740. infoThing pefas str = do
  741. names <- GHC.parseName str
  742. mb_stuffs <- mapM GHC.getInfo names
  743. let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
  744. unqual <- GHC.getPrintUnqual
  745. liftIO $ putStrLn $ showSDocForUser unqual $
  746. vcat (intersperse (text "") $
  747. map (pprInfo pefas) filtered)
  748. -- Filter out names whose parent is also there Good
  749. -- example is '[]', which is both a type and data
  750. -- constructor in the same type
  751. filterOutChildren :: (a -> TyThing) -> [a] -> [a]
  752. filterOutChildren get_thing xs
  753. = filterOut has_parent xs
  754. where
  755. all_names = mkNameSet (map (getName . get_thing) xs)
  756. has_parent x = case pprTyThingParent_maybe (get_thing x) of
  757. Just p -> getName p `elemNameSet` all_names
  758. Nothing -> False
  759. pprInfo :: PrintExplicitForalls -> (TyThing, Fixity, [GHC.Instance]) -> SDoc
  760. pprInfo pefas (thing, fixity, insts)
  761. = pprTyThingInContextLoc pefas thing
  762. $$ show_fixity fixity
  763. $$ vcat (map GHC.pprInstance insts)
  764. where
  765. show_fixity fix
  766. | fix == GHC.defaultFixity = empty
  767. | otherwise = ppr fix <+> ppr (GHC.getName thing)
  768. runMain :: String -> GHCi ()
  769. runMain s = case toArgs s of
  770. Left err -> liftIO (hPutStrLn stderr err)
  771. Right args ->
  772. withFlattenedDynflags $ do
  773. dflags <- getDynFlags
  774. case mainFunIs dflags of
  775. Nothing -> doWithArgs args "main"
  776. Just f -> doWithArgs args f
  777. runRun :: String -> GHCi ()
  778. runRun s = case toCmdArgs s of
  779. Left err -> liftIO (hPutStrLn stderr err)
  780. Right (cmd, args) -> doWithArgs args cmd
  781. doWithArgs :: [String] -> String -> GHCi ()
  782. doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
  783. show args ++ " (" ++ cmd ++ ")"]
  784. addModule :: [FilePath] -> InputT GHCi ()
  785. addModule files = do
  786. lift revertCAFs -- always revert CAFs on load/add.
  787. files <- mapM expandPath files
  788. targets <- mapM (\m -> GHC.guessTarget m Nothing) files
  789. -- remove old targets with the same id; e.g. for :add *M
  790. mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
  791. mapM_ GHC.addTarget targets
  792. prev_context <- GHC.getContext
  793. ok <- trySuccess $ GHC.load LoadAllTargets
  794. afterLoad ok False prev_context
  795. changeDirectory :: String -> InputT GHCi ()
  796. changeDirectory "" = do
  797. -- :cd on its own changes to the user's home directory
  798. either_dir <- liftIO $ IO.try getHomeDirectory
  799. case either_dir of
  800. Left _e -> return ()
  801. Right dir -> changeDirectory dir
  802. changeDirectory dir = do
  803. graph <- GHC.getModuleGraph
  804. when (not (null graph)) $
  805. do liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,"
  806. liftIO $ putStrLn "because the search path has changed."
  807. prev_context <- GHC.getContext
  808. GHC.setTargets []
  809. _ <- GHC.load LoadAllTargets
  810. lift $ setContextAfterLoad prev_context False []
  811. GHC.workingDirectoryChanged
  812. dir <- expandPath dir
  813. liftIO $ setCurrentDirectory dir
  814. trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
  815. trySuccess act =
  816. handleSourceError (\e -> do GHC.printExceptionAndWarnings e
  817. return Failed) $ do
  818. act
  819. editFile :: String -> GHCi ()
  820. editFile str =
  821. do file <- if null str then chooseEditFile else return str
  822. st <- getGHCiState
  823. let cmd = editor st
  824. when (null cmd)
  825. $ ghcError (CmdLineError "editor not set, use :set editor")
  826. _ <- liftIO $ system (cmd ++ ' ':file)
  827. return ()
  828. -- The user didn't specify a file so we pick one for them.
  829. -- Our strategy is to pick the first module that failed to load,
  830. -- or otherwise the first target.
  831. --
  832. -- XXX: Can we figure out what happened if the depndecy analysis fails
  833. -- (e.g., because the porgrammeer mistyped the name of a module)?
  834. -- XXX: Can we figure out the location of an error to pass to the editor?
  835. -- XXX: if we could figure out the list of errors that occured during the
  836. -- last load/reaload, then we could start the editor focused on the first
  837. -- of those.
  838. chooseEditFile :: GHCi String
  839. chooseEditFile =
  840. do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
  841. graph <- GHC.getModuleGraph
  842. failed_graph <- filterM hasFailed graph
  843. let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
  844. pick xs = case xs of
  845. x : _ -> GHC.ml_hs_file (GHC.ms_location x)
  846. _ -> Nothing
  847. case pick (order failed_graph) of
  848. Just file -> return file
  849. Nothing ->
  850. do targets <- GHC.getTargets
  851. case msum (map fromTarget targets) of
  852. Just file -> return file
  853. Nothing -> ghcError (CmdLineError "No files to edit.")
  854. where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
  855. fromTarget _ = Nothing -- when would we get a module target?
  856. defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
  857. defineMacro _ (':':_) =
  858. liftIO $ putStrLn "macro name cannot start with a colon"
  859. defineMacro overwrite s = do
  860. let (macro_name, definition) = break isSpace s
  861. macros <- liftIO (readIORef macros_ref)
  862. let defined = map cmdName macros
  863. if (null macro_name)
  864. then if null defined
  865. then liftIO $ putStrLn "no macros defined"
  866. else liftIO $ putStr ("the following macros are defined:\n" ++
  867. unlines defined)
  868. else do
  869. if (not overwrite && macro_name `elem` defined)
  870. then ghcError (CmdLineError
  871. ("macro '" ++ macro_name ++ "' is already defined"))
  872. else do
  873. let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
  874. -- give the expression a type signature, so we can be sure we're getting
  875. -- something of the right type.
  876. let new_expr = '(' : definition ++ ") :: String -> IO String"
  877. -- compile the expression
  878. handleSourceError (\e -> GHC.printExceptionAndWarnings e) $
  879. withFlattenedDynflags $ do
  880. hv <- GHC.compileExpr new_expr
  881. liftIO (writeIORef macros_ref --
  882. (filtered ++ [(macro_name, lift . runMacro hv, noCompletion)]))
  883. runMacro :: GHC.HValue{-String -> IO String-} -> String -> GHCi Bool
  884. runMacro fun s = do
  885. str <- liftIO ((unsafeCoerce# fun :: String -> IO String) s)
  886. -- make sure we force any exceptions in the result, while we are still
  887. -- inside the exception handler for commands:
  888. seqList str (return ())
  889. enqueueCommands (lines str)
  890. return False
  891. undefineMacro :: String -> GHCi ()
  892. undefineMacro str = mapM_ undef (words str)
  893. where undef macro_name = do
  894. cmds <- liftIO (readIORef macros_ref)
  895. if (macro_name `notElem` map cmdName cmds)
  896. then ghcError (CmdLineError
  897. ("macro '" ++ macro_name ++ "' is not defined"))
  898. else do
  899. liftIO (writeIORef macros_ref (filter ((/= macro_name) . cmdName) cmds))
  900. cmdCmd :: String -> GHCi ()
  901. cmdCmd str = do
  902. let expr = '(' : str ++ ") :: IO String"
  903. handleSourceError (\e -> GHC.printExceptionAndWarnings e) $
  904. withFlattenedDynflags $ do
  905. hv <- GHC.compileExpr expr
  906. cmds <- liftIO $ (unsafeCoerce# hv :: IO String)
  907. enqueueCommands (lines cmds)
  908. return ()
  909. loadModuleName :: GHC.GhcMonad m => ImportDecl RdrName -> m Module
  910. loadModuleName = flip GHC.findModule Nothing . unLoc . ideclName
  911. loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
  912. loadModule fs = timeIt (loadModule' fs)
  913. loadModule_ :: [FilePath] -> InputT GHCi ()
  914. loadModule_ fs = loadModule (zip fs (repeat Nothing)) >> return ()
  915. loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
  916. loadModule' files = do
  917. prev_context <- GHC.getContext
  918. -- unload first
  919. _ <- GHC.abandonAll
  920. lift discardActiveBreakPoints
  921. GHC.setTargets []
  922. _ <- GHC.load LoadAllTargets
  923. let (filenames, phases) = unzip files
  924. exp_filenames <- mapM expandPath filenames
  925. let files' = zip exp_filenames phases
  926. targets <- mapM (uncurry GHC.guessTarget) files'
  927. -- NOTE: we used to do the dependency anal first, so that if it
  928. -- fails we didn't throw away the current set of modules. This would
  929. -- require some re-working of the GHC interface, so we'll leave it
  930. -- as a ToDo for now.
  931. GHC.setTargets targets
  932. doLoad False prev_context LoadAllTargets
  933. checkModule :: String -> InputT GHCi ()
  934. checkModule m = do
  935. let modl = GHC.mkModuleName m
  936. prev_context <- GHC.getContext
  937. ok <- handleSourceError (\e -> GHC.printExceptionAndWarnings e >> return False) $ do
  938. r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
  939. liftIO $ putStrLn $ showSDoc $
  940. case GHC.moduleInfo r of
  941. cm | Just scope <- GHC.modInfoTopLevelScope cm ->
  942. let
  943. (local,global) = ASSERT( all isExternalName scope )
  944. partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
  945. in
  946. (text "global names: " <+> ppr global) $$
  947. (text "local names: " <+> ppr local)
  948. _ -> empty
  949. return True
  950. afterLoad (successIf ok) False prev_context
  951. reloadModule :: String -> InputT GHCi ()
  952. reloadModule m = do
  953. prev_context <- GHC.getContext
  954. _ <- doLoad True prev_context $
  955. if null m then LoadAllTargets
  956. else LoadUpTo (GHC.mkModuleName m)
  957. return ()
  958. doLoad :: Bool -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> LoadHowMuch -> InputT GHCi SuccessFlag
  959. doLoad retain_context prev_context howmuch = do
  960. -- turn off breakpoints before we load: we can't turn them off later, because
  961. -- the ModBreaks will have gone away.
  962. lift discardActiveBreakPoints
  963. ok <- trySuccess $ GHC.load howmuch
  964. afterLoad ok retain_context prev_context
  965. return ok
  966. afterLoad :: SuccessFlag -> Bool -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> InputT GHCi ()
  967. afterLoad ok retain_context prev_context = do
  968. lift revertCAFs -- always revert CAFs on load.
  969. lift discardTickArrays
  970. loaded_mod_summaries <- getLoadedModules
  971. let loaded_mods = map GHC.ms_mod loaded_mod_summaries
  972. loaded_mod_names = map GHC.moduleName loaded_mods
  973. modulesLoadedMsg ok loaded_mod_names
  974. withFlattenedDynflags $ lift $ setContextAfterLoad prev_context retain_context loaded_mod_summaries
  975. setContextAfterLoad :: ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> Bool -> [GHC.ModSummary] -> GHCi ()
  976. setContextAfterLoad prev keep_ctxt [] = do
  977. prel_mod <- getPrelude
  978. setContextKeepingPackageModules prev keep_ctxt ([], [(prel_mod, Nothing)])
  979. setContextAfterLoad prev keep_ctxt ms = do
  980. -- load a target if one is available, otherwise load the topmost module.
  981. targets <- GHC.getTargets
  982. case [ m | Just m <- map (findTarget ms) targets ] of
  983. [] ->
  984. let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
  985. load_this (last graph')
  986. (m:_) ->
  987. load_this m
  988. where
  989. findTarget ms t
  990. = case filter (`matches` t) ms of
  991. [] -> Nothing
  992. (m:_) -> Just m
  993. summary `matches` Target (TargetModule m) _ _
  994. = GHC.ms_mod_name summary == m
  995. summary `matches` Target (TargetFile f _) _ _
  996. | Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
  997. _ `matches` _
  998. = False
  999. load_this summary | m <- GHC.ms_mod summary = do
  1000. b <- GHC.moduleIsInterpreted m
  1001. if b then setContextKeepingPackageModules prev keep_ctxt ([m], [])
  1002. else do
  1003. prel_mod <- getPrelude
  1004. setContextKeepingPackageModules prev keep_ctxt ([],[(prel_mod,Nothing),(m,Nothing)])
  1005. -- | Keep any package modules (except Prelude) when changing the context.
  1006. setContextKeepingPackageModules
  1007. :: ([Module],[(Module, Maybe (ImportDecl RdrName))]) -- previous context
  1008. -> Bool -- re-execute :module commands
  1009. -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -- new context
  1010. -> GHCi ()
  1011. setContextKeepingPackageModules prev_context keep_ctxt (as,bs) = do
  1012. let (_,bs0) = prev_context
  1013. prel_mod <- getPrelude
  1014. -- filter everything, not just lefts
  1015. let pkg_modules = filter ((\p -> not (isHomeModule p) && p /= prel_mod) . fst) bs0
  1016. let bs1 = if null as then nubBy sameFst ((prel_mod,Nothing) : bs) else bs
  1017. GHC.setContext as (nubBy sameFst (bs1 ++ pkg_modules))
  1018. if keep_ctxt
  1019. then do
  1020. st <- getGHCiState
  1021. mapM_ (playCtxtCmd False) (remembered_ctx st)
  1022. else do
  1023. st <- getGHCiState
  1024. setGHCiState st{ remembered_ctx = [] }
  1025. isHomeModule :: Module -> Bool
  1026. isHomeModule mod = GHC.modulePackageId mod == mainPackageId
  1027. sameFst :: (Module, Maybe (ImportDecl RdrName)) -> (Module, Maybe (ImportDecl RdrName)) -> Bool
  1028. sameFst x y = fst x == fst y
  1029. modulesLoadedMsg :: SuccessFlag -> [ModuleName] -> InputT GHCi ()
  1030. modulesLoadedMsg ok mods = do
  1031. dflags <- getDynFlags
  1032. when (verbosity dflags > 0) $ do
  1033. let mod_commas
  1034. | null mods = text "none."
  1035. | otherwise = hsep (
  1036. punctuate comma (map ppr mods)) <> text "."
  1037. case ok of
  1038. Failed ->
  1039. liftIO $ putStrLn $ showSDoc (text "Failed, modules loaded: " <> mod_commas)
  1040. Succeeded ->
  1041. liftIO $ putStrLn $ showSDoc (text "Ok, modules loaded: " <> mod_commas)
  1042. typeOfExpr :: String -> InputT GHCi ()
  1043. typeOfExpr str
  1044. = handleSourceError (\e -> GHC.printExceptionAndWarnings e)
  1045. $ withFlattenedDynflags
  1046. $ do
  1047. ty <- GHC.exprType str
  1048. dflags <- getDynFlags
  1049. let pefas = dopt Opt_PrintExplicitForalls dflags
  1050. printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser pefas ty)]
  1051. kindOfType :: String -> InputT GHCi ()
  1052. kindOfType str
  1053. = handleSourceError (\e -> GHC.printExceptionAndWarnings e)
  1054. $ withFlattenedDynflags
  1055. $ do
  1056. ty <- GHC.typeKind str
  1057. printForUser $ text str <+> dcolon <+> ppr ty
  1058. quit :: String -> InputT GHCi Bool
  1059. quit _ = return True
  1060. shellEscape :: String -> GHCi Bool
  1061. shellEscape str = liftIO (system str >> return False)
  1062. withFlattenedDynflags :: GHC.GhcMonad m => m a -> m a
  1063. withFlattenedDynflags m
  1064. = do dflags <- GHC.getSessionDynFlags
  1065. gbracket (GHC.setSessionDynFlags dflags)
  1066. (\_ -> GHC.setSessionDynFlags dflags)
  1067. (\_ -> m)
  1068. -----------------------------------------------------------------------------
  1069. -- Browsing a module's contents
  1070. browseCmd :: Bool -> String -> InputT GHCi ()
  1071. browseCmd bang m =
  1072. case words m of
  1073. ['*':s] | looksLikeModuleName s -> do
  1074. m <- lift $ wantInterpretedModule s
  1075. browseModule bang m False
  1076. [s] | looksLikeModuleName s -> do
  1077. m <- lift $ lookupModule s
  1078. browseModule bang m True
  1079. [] -> do
  1080. (as,bs) <- GHC.getContext
  1081. -- Guess which module the user wants to browse. Pick
  1082. -- modules that are interpreted first. The most
  1083. -- recently-added module occurs last, it seems.
  1084. case (as,bs) of
  1085. (as@(_:_), _) -> browseModule bang (last as) True
  1086. ([], bs@(_:_)) -> browseModule bang (fst (last bs)) True
  1087. ([], []) -> ghcError (CmdLineError ":browse: no current module")
  1088. _ -> ghcError (CmdLineError "syntax: :browse <module>")
  1089. -- without bang, show items in context of their parents and omit children
  1090. -- with bang, show class methods and data constructors separately, and
  1091. -- indicate import modules, to aid qualifying unqualified names
  1092. -- with sorted, sort items alphabetically
  1093. browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
  1094. browseModule bang modl exports_only = withFlattenedDynflags $ do
  1095. -- :browse! reports qualifiers wrt current context
  1096. current_unqual <- GHC.getPrintUnqual
  1097. -- Temporarily set the context to the module we're interested in,
  1098. -- just so we can get an appropriate PrintUnqualified
  1099. (as,bs) <- GHC.getContext
  1100. prel_mod <- lift getPrelude
  1101. if exports_only then GHC.setContext [] [(prel_mod,Nothing), (modl,Nothing)]
  1102. else GHC.setContext [modl] []
  1103. target_unqual <- GHC.getPrintUnqual
  1104. GHC.setContext as bs
  1105. let unqual = if bang then current_unqual else target_unqual
  1106. mb_mod_info <- GHC.getModuleInfo modl
  1107. case mb_mod_info of
  1108. Nothing -> ghcError (CmdLineError ("unknown module: " ++
  1109. GHC.moduleNameString (GHC.moduleName modl)))
  1110. Just mod_info -> do
  1111. dflags <- getDynFlags
  1112. let names
  1113. | exports_only = GHC.modInfoExports mod_info
  1114. | otherwise = GHC.modInfoTopLevelScope mod_info
  1115. `orElse` []

Large files files are truncated, but you can click here to view the full file