PageRenderTime 31ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc-patch/InteractiveUI.hs

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

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