PageRenderTime 66ms CodeModel.GetById 5ms RepoModel.GetById 1ms 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
  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 bs
  1155. let unqual = if bang then current_unqual else target_unqual
  1156. mb_mod_info <- GHC.getModuleInfo modl
  1157. case mb_mod_info of
  1158. Nothing -> ghcError (CmdLineError ("unknown module: " ++
  1159. GHC.moduleNameString (GHC.moduleName modl)))
  1160. Just mod_info -> do
  1161. dflags <- getDynFlags
  1162. let names
  1163. | exports_only = GHC.modInfoExports mod_info
  1164. | otherwise = GHC.modInfoTopLevelScope mod_info
  1165. `orElse` []
  1166. -- sort alphabetically name, but putting
  1167. -- locally-defined identifiers first.
  1168. -- We would like to improve this; see #1799.
  1169. sorted_names = loc_sort local ++ occ_sort external
  1170. where
  1171. (local,external) = ASSERT( all isExternalName names )
  1172. partition ((==modl) . nameModule) names
  1173. occ_sort = sortBy (compare `on` nameOccName)
  1174. -- try to sort by src location. If the first name in
  1175. -- our list has a good source location, then they all should.
  1176. loc_sort names
  1177. | n:_ <- names, isGoodSrcSpan (nameSrcSpan n)
  1178. = sortBy (compare `on` nameSrcSpan) names
  1179. | otherwise
  1180. = occ_sort names
  1181. mb_things <- mapM GHC.lookupName sorted_names
  1182. let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
  1183. rdr_env <- GHC.getGRE
  1184. let pefas = dopt Opt_PrintExplicitForalls dflags
  1185. things | bang = catMaybes mb_things
  1186. | otherwise = filtered_things
  1187. pretty | bang = pprTyThing
  1188. | otherwise = pprTyThingInContext
  1189. labels [] = text "-- not currently imported"
  1190. labels l = text $ intercalate "\n" $ map qualifier l
  1191. qualifier = maybe "-- defined locally"
  1192. (("-- imported via "++) . intercalate ", "
  1193. . map GHC.moduleNameString)
  1194. importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
  1195. modNames = map (importInfo . GHC.getName) things
  1196. -- annotate groups of imports with their import modules
  1197. -- the default ordering is somewhat arbitrary, so we group
  1198. -- by header and sort groups; the names themselves should
  1199. -- really come in order of source appearance.. (trac #1799)
  1200. annotate mts = concatMap (\(m,ts)->labels m:ts)
  1201. $ sortBy cmpQualifiers $ group mts
  1202. where cmpQualifiers =
  1203. compare `on` (map (fmap (map moduleNameFS)) . fst)
  1204. group [] = []
  1205. group mts@((m,_):_) = (m,map snd g) : group ng
  1206. where (g,ng) = partition ((==m).fst) mts
  1207. let prettyThings = map (pretty pefas) things
  1208. prettyThings' | bang = annotate $ zip modNames prettyThings
  1209. | otherwise = prettyThings
  1210. io (putStrLn $ showSDocForUser unqual (vcat prettyThings'))
  1211. -- ToDo: modInfoInstances currently throws an exception for
  1212. -- package modules. When it works, we can do this:
  1213. -- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
  1214. -----------------------------------------------------------------------------
  1215. -- Setting the module context
  1216. setContext :: String -> GHCi ()
  1217. setContext str
  1218. | all sensible strs = do
  1219. playCtxtCmd True (cmd, as, bs)
  1220. st <- getGHCiState
  1221. setGHCiState st{ remembered_ctx = remembered_ctx st ++ [(cmd,as,bs)] }
  1222. | otherwise = ghcError (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
  1223. where
  1224. (cmd, strs, as, bs) =
  1225. case str of
  1226. '+':stuff -> rest AddModules stuff
  1227. '-':stuff -> rest RemModules stuff
  1228. stuff -> rest SetContext stuff
  1229. rest cmd stuff = (cmd, strs, as, bs)
  1230. where strs = words stuff
  1231. (as,bs) = partitionWith starred strs
  1232. sensible ('*':m) = looksLikeModuleName m
  1233. sensible m = looksLikeModuleName m
  1234. starred ('*':m) = Left m
  1235. starred m = Right m
  1236. playCtxtCmd :: Bool -> (CtxtCmd, [String], [String]) -> GHCi ()
  1237. playCtxtCmd fail (cmd, as, bs)
  1238. = do
  1239. (as',bs') <- do_checks fail
  1240. (prev_as,prev_bs) <- GHC.getContext
  1241. (new_as, new_bs) <-
  1242. case cmd of
  1243. SetContext -> do
  1244. prel_mod <- getPrelude
  1245. let bs'' = if null as && prel_mod `notElem` bs' then prel_mod:bs'
  1246. else bs'
  1247. return (as',bs'')
  1248. AddModules -> do
  1249. let as_to_add = as' \\ (prev_as ++ prev_bs)
  1250. bs_to_add = bs' \\ (prev_as ++ prev_bs)
  1251. return (prev_as ++ as_to_add, prev_bs ++ bs_to_add)
  1252. RemModules -> do
  1253. let new_as = prev_as \\ (as' ++ bs')
  1254. new_bs = prev_bs \\ (as' ++ bs')
  1255. return (new_as, new_bs)
  1256. GHC.setContext new_as new_bs
  1257. where
  1258. do_checks True = do
  1259. as' <- mapM wantInterpretedModule as
  1260. bs' <- mapM lookupModule bs
  1261. return (as',bs')
  1262. do_checks False = do
  1263. as' <- mapM (trymaybe . wantInterpretedModule) as
  1264. bs' <- mapM (trymaybe . lookupModule) bs
  1265. return (catMaybes as', catMaybes bs')
  1266. trymaybe m = do
  1267. r <- ghciTry m
  1268. case r of
  1269. Left _ -> return Nothing
  1270. Right a -> return (Just a)
  1271. ----------------------------------------------------------------------------
  1272. -- Code for `:set'
  1273. -- set options in the interpreter. Syntax is exactly the same as the
  1274. -- ghc command line, except that certain options aren't available (-C,
  1275. -- -E etc.)
  1276. --
  1277. -- This is pretty fragile: most options won't work as expected. ToDo:
  1278. -- figure out which ones & disallow them.
  1279. setCmd :: String -> GHCi ()
  1280. setCmd ""
  1281. = do st <- getGHCiState
  1282. let opts = options st
  1283. io $ putStrLn (showSDoc (
  1284. text "options currently set: " <>
  1285. if null opts
  1286. then text "none."
  1287. else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
  1288. ))
  1289. dflags <- getDynFlags
  1290. io $ putStrLn (showSDoc (
  1291. vcat (text "GHCi-specific dynamic flag settings:"
  1292. :map (flagSetting dflags) ghciFlags)
  1293. ))
  1294. io $ putStrLn (showSDoc (
  1295. vcat (text "other dynamic, non-language, flag settings:"
  1296. :map (flagSetting dflags) nonLanguageDynFlags)
  1297. ))
  1298. where flagSetting dflags (str, f, _)
  1299. | dopt f dflags = text " " <> text "-f" <> text str
  1300. | otherwise = text " " <> text "-fno-" <> text str
  1301. (ghciFlags,others) = partition (\(_, f, _) -> f `elem` flags)
  1302. DynFlags.fFlags
  1303. nonLanguageDynFlags = filterOut (\(_, f, _) -> f `elem` languageOptions)
  1304. others
  1305. flags = [Opt_PrintExplicitForalls
  1306. ,Opt_PrintBindResult
  1307. ,Opt_BreakOnException
  1308. ,Opt_BreakOnError
  1309. ,Opt_PrintEvldWithShow
  1310. ]
  1311. setCmd str
  1312. = case getCmd str of
  1313. Right ("args", rest) ->
  1314. case toArgs rest of
  1315. Left err -> io (hPutStrLn stderr err)
  1316. Right args -> setArgs args
  1317. Right ("prog", rest) ->
  1318. case toArgs rest of
  1319. Right [prog] -> setProg prog
  1320. _ -> io (hPutStrLn stderr "syntax: :set prog <progname>")
  1321. Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
  1322. Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
  1323. Right ("stop", rest) -> setStop $ dropWhile isSpace rest
  1324. _ -> case toArgs str of
  1325. Left err -> io (hPutStrLn stderr err)
  1326. Right wds -> setOptions wds
  1327. setArgs, setOptions :: [String] -> GHCi ()
  1328. setProg, setEditor, setStop, setPrompt :: String -> GHCi ()
  1329. setArgs args = do
  1330. st <- getGHCiState
  1331. setGHCiState st{ args = args }
  1332. setProg prog = do
  1333. st <- getGHCiState
  1334. setGHCiState st{ progname = prog }
  1335. setEditor cmd = do
  1336. st <- getGHCiState
  1337. setGHCiState st{ editor = cmd }
  1338. setStop str@(c:_) | isDigit c
  1339. = do let (nm_str,rest) = break (not.isDigit) str
  1340. nm = read nm_str
  1341. st <- getGHCiState
  1342. let old_breaks = breaks st
  1343. if all ((/= nm) . fst) old_breaks
  1344. then printForUser (text "Breakpoint" <+> ppr nm <+>
  1345. text "does not exist")
  1346. else do
  1347. let new_breaks = map fn old_breaks
  1348. fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
  1349. | otherwise = (i,loc)
  1350. setGHCiState st{ breaks = new_breaks }
  1351. setStop cmd = do
  1352. st <- getGHCiState
  1353. setGHCiState st{ stop = cmd }
  1354. setPrompt value = do
  1355. st <- getGHCiState
  1356. if null value
  1357. then io $ hPutStrLn stderr $ "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
  1358. else case value of
  1359. '\"' : _ -> case reads value of
  1360. [(value', xs)] | all isSpace xs ->
  1361. setGHCiState (st { prompt = value' })
  1362. _ ->
  1363. io $ hPutStrLn stderr "Can't parse prompt string. Use Haskell syntax."
  1364. _ -> setGHCiState (st { prompt = value })
  1365. setOptions wds =
  1366. do -- first, deal with the GHCi opts (+s, +t, etc.)
  1367. let (plus_opts, minus_opts) = partitionWith isPlus wds
  1368. mapM_ setOpt plus_opts
  1369. -- then, dynamic flags
  1370. newDynFlags minus_opts
  1371. newDynFlags :: [String] -> GHCi ()
  1372. newDynFlags minus_opts = do
  1373. dflags <- getDynFlags
  1374. let pkg_flags = packageFlags dflags
  1375. (dflags', leftovers, warns) <- io $ GHC.parseDynamicFlags dflags $ map noLoc minus_opts
  1376. handleFlagWarnings dflags' warns
  1377. if (not (null leftovers))
  1378. then ghcError $ errorsToGhcException leftovers
  1379. else return ()
  1380. new_pkgs <- setDynFlags dflags'
  1381. -- if the package flags changed, we should reset the context
  1382. -- and link the new packages.
  1383. dflags <- getDynFlags
  1384. when (packageFlags dflags /= pkg_flags) $ do
  1385. io $ hPutStrLn stderr "package flags have changed, resetting and loading new packages..."
  1386. GHC.setTargets []
  1387. GHC.load LoadAllTargets
  1388. io (linkPackages dflags new_pkgs)
  1389. -- package flags changed, we can't re-use any of the old context
  1390. setContextAfterLoad ([],[]) False []
  1391. return ()
  1392. unsetOptions :: String -> GHCi ()
  1393. unsetOptions str
  1394. = do -- first, deal with the GHCi opts (+s, +t, etc.)
  1395. let opts = words str
  1396. (minus_opts, rest1) = partition isMinus opts
  1397. (plus_opts, rest2) = partitionWith isPlus rest1
  1398. if (not (null rest2))
  1399. then io (putStrLn ("unknown option: '" ++ head rest2 ++ "'"))
  1400. else do
  1401. mapM_ unsetOpt plus_opts
  1402. let no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
  1403. no_flag f = ghcError (ProgramError ("don't know how to reverse " ++ f))
  1404. no_flags <- mapM no_flag minus_opts
  1405. newDynFlags no_flags
  1406. isMinus :: String -> Bool
  1407. isMinus ('-':_) = True
  1408. isMinus _ = False
  1409. isPlus :: String -> Either String String
  1410. isPlus ('+':opt) = Left opt
  1411. isPlus other = Right other
  1412. setOpt, unsetOpt :: String -> GHCi ()
  1413. setOpt str
  1414. = case strToGHCiOpt str of
  1415. Nothing -> io (putStrLn ("unknown option: '" ++ str ++ "'"))
  1416. Just o -> setOption o
  1417. unsetOpt str
  1418. = case strToGHCiOpt str of
  1419. Nothing -> io (putStrLn ("unknown option: '" ++ str ++ "'"))
  1420. Just o -> unsetOption o
  1421. strToGHCiOpt :: String -> (Maybe GHCiOption)
  1422. strToGHCiOpt "s" = Just ShowTiming
  1423. strToGHCiOpt "t" = Just ShowType
  1424. strToGHCiOpt "r" = Just RevertCAFs
  1425. strToGHCiOpt _ = Nothing
  1426. optToStr :: GHCiOption -> String
  1427. optToStr ShowTiming = "s"
  1428. optToStr ShowType = "t"
  1429. optToStr RevertCAFs = "r"
  1430. -- ---------------------------------------------------------------------------
  1431. -- code for `:show'
  1432. showCmd :: String -> GHCi ()
  1433. showCmd str = do
  1434. st <- getGHCiState
  1435. case words str of
  1436. ["args"] -> io $ putStrLn (show (args st))
  1437. ["prog"] -> io $ putStrLn (show (progname st))
  1438. ["prompt"] -> io $ putStrLn (show (prompt st))
  1439. ["editor"] -> io $ putStrLn (show (editor st))
  1440. ["stop"] -> io $ putStrLn (show (stop st))
  1441. ["modules" ] -> showModules
  1442. ["bindings"] -> showBindings
  1443. ["linker"] -> io showLinkerState
  1444. ["breaks"] -> showBkptTable
  1445. ["context"] -> showContext
  1446. ["packages"] -> showPackages
  1447. ["languages"] -> showLanguages
  1448. _ -> ghcError (CmdLineError ("syntax: :show [ args | prog | prompt | editor | stop | modules | bindings\n"++
  1449. " | breaks | context | packages | languages ]"))
  1450. showModules :: GHCi ()
  1451. showModules = do
  1452. loaded_mods <- getLoadedModules
  1453. -- we want *loaded* modules only, see #1734
  1454. let show_one ms = do m <- GHC.showModule ms; io (putStrLn m)
  1455. mapM_ show_one loaded_mods
  1456. getLoadedModules :: GHCi [GHC.ModSummary]
  1457. getLoadedModules = do
  1458. graph <- GHC.getModuleGraph
  1459. filterM (GHC.isLoaded . GHC.ms_mod_name) graph
  1460. showBindings :: GHCi ()
  1461. showBindings = do
  1462. bindings <- GHC.getBindings
  1463. docs <- pprTypeAndContents
  1464. [ id | AnId id <- sortBy compareTyThings bindings]
  1465. printForUserPartWay docs
  1466. compareTyThings :: TyThing -> TyThing -> Ordering
  1467. t1 `compareTyThings` t2 = getName t1 `compareNames` getName t2
  1468. printTyThing :: TyThing -> GHCi ()
  1469. printTyThing tyth = do dflags <- getDynFlags
  1470. let pefas = dopt Opt_PrintExplicitForalls dflags
  1471. printForUser (pprTyThing pefas tyth)
  1472. showBkptTable :: GHCi ()
  1473. showBkptTable = do
  1474. st <- getGHCiState
  1475. printForUser $ prettyLocations (breaks st)
  1476. showContext :: GHCi ()
  1477. showContext = do
  1478. resumes <- GHC.getResumeContext
  1479. printForUser $ vcat (map pp_resume (reverse resumes))
  1480. where
  1481. pp_resume resume =
  1482. ptext (sLit "--> ") <> text (GHC.resumeStmt resume)
  1483. $$ nest 2 (ptext (sLit "Stopped at") <+> ppr (GHC.resumeSpan resume))
  1484. showPackages :: GHCi ()
  1485. showPackages = do
  1486. pkg_flags <- fmap packageFlags getDynFlags
  1487. io $ putStrLn $ showSDoc $ vcat $
  1488. text ("active package flags:"++if null pkg_flags then " none" else "")
  1489. : map showFlag pkg_flags
  1490. pkg_ids <- fmap (preloadPackages . pkgState) getDynFlags
  1491. io $ putStrLn $ showSDoc $ vcat $
  1492. text "packages currently loaded:"
  1493. : map (nest 2 . text . packageIdString)
  1494. (sortBy (compare `on` packageIdFS) pkg_ids)
  1495. where showFlag (ExposePackage p) = text $ " -package " ++ p
  1496. showFlag (HidePackage p) = text $ " -hide-package " ++ p
  1497. showFlag (IgnorePackage p) = text $ " -ignore-package " ++ p
  1498. showLanguages :: GHCi ()
  1499. showLanguages = do
  1500. dflags <- getDynFlags
  1501. io $ putStrLn $ showSDoc $ vcat $
  1502. text "active language flags:" :
  1503. [text (" -X" ++ str) | (str, f, _) <- DynFlags.xFlags, dopt f dflags]
  1504. -- -----------------------------------------------------------------------------
  1505. -- Completion
  1506. completeNone :: String -> IO [String]
  1507. completeNone _w = return []
  1508. completeMacro, completeIdentifier, completeModule,
  1509. completeHomeModule, completeSetOptions, completeShowOptions,
  1510. completeFilename, completeHomeModuleOrFile
  1511. :: String -> IO [String]
  1512. #ifdef USE_EDITLINE
  1513. completeWord :: String -> Int -> Int -> IO (Maybe (String, [String]))
  1514. completeWord w start end = do
  1515. line <- Readline.getLineBuffer
  1516. let line_words = words (dropWhile isSpace line)
  1517. case w of
  1518. ':':_ | all isSpace (take (start-1) line) -> wrapCompleter completeCmd w
  1519. _other
  1520. | ((':':c) : _) <- line_words -> do
  1521. completionVars <- lookupCompletionVars c
  1522. case completionVars of
  1523. (Nothing,complete) -> wrapCompleter complete w
  1524. (Just breakChars,complete)
  1525. -> let (n,w') = selectWord
  1526. (words' (`elem` breakChars) 0 line)
  1527. complete' w = do rets <- complete w
  1528. return (map (drop n) rets)
  1529. in wrapCompleter complete' w'
  1530. | ("import" : _) <- line_words ->
  1531. wrapCompleter completeModule w
  1532. | otherwise -> do
  1533. --printf "complete %s, start = %d, end = %d\n" w start end
  1534. wrapCompleter completeIdentifier w
  1535. where words' _ _ [] = []
  1536. words' isBreak n str = let (w,r) = break isBreak str
  1537. (s,r') = span isBreak r
  1538. in (n,w):words' isBreak (n+length w+length s) r'
  1539. -- In a Haskell expression we want to parse 'a-b' as three words
  1540. -- where a compiler flag (e.g. -ddump-simpl) should
  1541. -- only be a single word.
  1542. selectWord [] = (0,w)
  1543. selectWord ((offset,x):xs)
  1544. | offset+length x >= start = (start-offset,take (end-offset) x)
  1545. | otherwise = selectWord xs
  1546. lookupCompletionVars ('!':_) = return (Just filenameWordBreakChars,
  1547. completeFilename)
  1548. lookupCompletionVars c = do
  1549. maybe_cmd <- lookupCommand' c
  1550. case maybe_cmd of
  1551. Just (_,_,ws,f) -> return (ws,f)
  1552. Nothing -> return (Just filenameWordBreakChars,
  1553. completeFilename)
  1554. completeCmd :: String -> IO [String]
  1555. completeCmd w = do
  1556. cmds <- readIORef macros_ref
  1557. return (filter (w `isPrefixOf`) (map (':':)
  1558. (map cmdName (builtin_commands ++ cmds))))
  1559. completeMacro w = do
  1560. cmds <- readIORef macros_ref
  1561. return (filter (w `isPrefixOf`) (map cmdName cmds))
  1562. completeIdentifier w = do
  1563. rdrs <- withRestoredSession GHC.getRdrNamesInScope
  1564. return (filter (w `isPrefixOf`) (map (showSDoc.ppr) rdrs))
  1565. completeModule w = do
  1566. dflags <- withRestoredSession GHC.getSessionDynFlags
  1567. let pkg_mods = allExposedModules dflags
  1568. return (filter (w `isPrefixOf`) (map (showSDoc.ppr) pkg_mods))
  1569. completeHomeModule w = do
  1570. g <- withRestoredSession GHC.getModuleGraph
  1571. let home_mods = map GHC.ms_mod_name g
  1572. return (filter (w `isPrefixOf`) (map (showSDoc.ppr) home_mods))
  1573. completeSetOptions w = do
  1574. return (filter (w `isPrefixOf`) options)
  1575. where options = "args":"prog":"prompt":"editor":"stop":flagList
  1576. flagList = map head $ group $ sort allFlags
  1577. completeShowOptions w = do
  1578. return (filter (w `isPrefixOf`) options)
  1579. where options = ["args", "prog", "prompt", "editor", "stop",
  1580. "modules", "bindings", "linker", "breaks",
  1581. "context", "packages", "languages"]
  1582. completeFilename w = do
  1583. ws <- Readline.filenameCompletionFunction w
  1584. case ws of
  1585. -- If we only found one result, and it's a directory,
  1586. -- add a trailing slash.
  1587. [file] -> do
  1588. isDir <- expandPathIO file >>= doesDirectoryExist
  1589. if isDir && last file /= '/'
  1590. then return [file ++ "/"]
  1591. else return [file]
  1592. _ -> return ws
  1593. completeHomeModuleOrFile = unionComplete completeHomeModule completeFilename
  1594. unionComplete :: (String -> IO [String]) -> (String -> IO [String]) -> String -> IO [String]
  1595. unionComplete f1 f2 w = do
  1596. s1 <- f1 w
  1597. s2 <- f2 w
  1598. return (s1 ++ s2)
  1599. wrapCompleter :: (String -> IO [String]) -> String -> IO (Maybe (String,[String]))
  1600. wrapCompleter fun w = do
  1601. strs <- fun w
  1602. case strs of
  1603. [] -> Readline.setAttemptedCompletionOver True >> return Nothing
  1604. [x] -> -- Add a trailing space, unless it already has an appended slash.
  1605. let appended = if last x == '/' then x else x ++ " "
  1606. in return (Just (appended,[]))
  1607. xs -> case getCommonPrefix xs of
  1608. "" -> return (Just ("",xs))
  1609. pref -> return (Just (pref,xs))
  1610. getCommonPrefix :: [String] -> String
  1611. getCommonPrefix [] = ""
  1612. getCommonPrefix (s:ss) = foldl common s ss
  1613. where common _s "" = ""
  1614. common "" _s = ""
  1615. common (c:cs) (d:ds)
  1616. | c == d = c : common cs ds
  1617. | otherwise = ""
  1618. allExposedModules :: DynFlags -> [ModuleName]
  1619. allExposedModules dflags
  1620. = concat (map exposedModules (filter exposed (eltsUFM pkg_db)))
  1621. where
  1622. pkg_db = pkgIdMap (pkgState dflags)
  1623. #else
  1624. completeMacro = completeNone
  1625. completeIdentifier = completeNone
  1626. completeModule = completeNone
  1627. completeHomeModule = completeNone
  1628. completeSetOptions = completeNone
  1629. completeShowOptions = completeNone
  1630. completeFilename = completeNone
  1631. completeHomeModuleOrFile=completeNone
  1632. #endif
  1633. -- ---------------------------------------------------------------------------
  1634. -- User code exception handling
  1635. -- This is the exception handler for exceptions generated by the
  1636. -- user's code and exceptions coming from children sessions;
  1637. -- it normally just prints out the exception. The
  1638. -- handler must be recursive, in case showing the exception causes
  1639. -- more exceptions to be raised.
  1640. --
  1641. -- Bugfix: if the user closed stdout or stderr, the flushing will fail,
  1642. -- raising another exception. We therefore don't put the recursive
  1643. -- handler arond the flushing operation, so if stderr is closed
  1644. -- GHCi will just die gracefully rather than going into an infinite loop.
  1645. handler :: SomeException -> GHCi Bool
  1646. handler exception = do
  1647. flushInterpBuffers
  1648. io installSignalHandlers
  1649. ghciHandle handler (showException exception >> return False)
  1650. showException :: SomeException -> GHCi ()
  1651. showException se =
  1652. io $ case fromException se of
  1653. Just Interrupted -> putStrLn "Interrupted."
  1654. -- omit the location for CmdLineError:
  1655. Just (CmdLineError s) -> putStrLn s
  1656. -- ditto:
  1657. Just ph@(PhaseFailed {}) -> putStrLn (showGhcException ph "")
  1658. Just other_ghc_ex -> print other_ghc_ex
  1659. Nothing -> putStrLn ("*** Exception: " ++ show se)
  1660. -----------------------------------------------------------------------------
  1661. -- recursive exception handlers
  1662. -- Don't forget to unblock async exceptions in the handler, or if we're
  1663. -- in an exception loop (eg. let a = error a in a) the ^C exception
  1664. -- may never be delivered. Thanks to Marcin for pointing out the bug.
  1665. ghciHandle :: (SomeException -> GHCi a) -> GHCi a -> GHCi a
  1666. ghciHandle h (GHCi m) = GHCi $ \s ->
  1667. gcatch (m s)
  1668. (\e -> unGHCi (ghciUnblock (h e)) s)
  1669. ghciUnblock :: GHCi a -> GHCi a
  1670. ghciUnblock (GHCi a) =
  1671. GHCi $ \s -> reifyGhc $ \gs ->
  1672. Exception.unblock (reflectGhc (a s) gs)
  1673. ghciTry :: GHCi a -> GHCi (Either SomeException a)
  1674. ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
  1675. -- ----------------------------------------------------------------------------
  1676. -- Utils
  1677. expandPath :: String -> GHCi String
  1678. expandPath path = io (expandPathIO path)
  1679. expandPathIO :: String -> IO String
  1680. expandPathIO path =
  1681. case dropWhile isSpace path of
  1682. ('~':d) -> do
  1683. tilde <- getHomeDirectory -- will fail if HOME not defined
  1684. return (tilde ++ '/':d)
  1685. other ->
  1686. return other
  1687. wantInterpretedModule :: String -> GHCi Module
  1688. wantInterpretedModule str = do
  1689. modl <- lookupModule str
  1690. dflags <- getDynFlags
  1691. when (GHC.modulePackageId modl /= thisPackage dflags) $
  1692. ghcError (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
  1693. is_interpreted <- GHC.moduleIsInterpreted modl
  1694. when (not is_interpreted) $
  1695. ghcError (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
  1696. return modl
  1697. wantNameFromInterpretedModule :: (Name -> SDoc -> GHCi ()) -> String
  1698. -> (Name -> GHCi ())
  1699. -> GHCi ()
  1700. wantNameFromInterpretedModule noCanDo str and_then =
  1701. handleSourceError (GHC.printExceptionAndWarnings) $ do
  1702. names <- GHC.parseName str
  1703. case names of
  1704. [] -> return ()
  1705. (n:_) -> do
  1706. let modl = ASSERT( isExternalName n ) GHC.nameModule n
  1707. if not (GHC.isExternalName n)
  1708. then noCanDo n $ ppr n <>
  1709. text " is not defined in an interpreted module"
  1710. else do
  1711. is_interpreted <- GHC.moduleIsInterpreted modl
  1712. if not is_interpreted
  1713. then noCanDo n $ text "module " <> ppr modl <>
  1714. text " is not interpreted"
  1715. else and_then n
  1716. -- -----------------------------------------------------------------------------
  1717. -- commands for debugger
  1718. sprintCmd, printCmd, forceCmd :: String -> GHCi ()
  1719. sprintCmd = pprintCommand False False
  1720. printCmd = pprintCommand True False
  1721. forceCmd = pprintCommand False True
  1722. pprintCommand :: Bool -> Bool -> String -> GHCi ()
  1723. pprintCommand bind force str = do
  1724. pprintClosureCommand bind force str
  1725. stepCmd :: String -> GHCi ()
  1726. stepCmd [] = doContinue (const True) GHC.SingleStep
  1727. stepCmd expression = do runStmt expression GHC.SingleStep; return ()
  1728. stepLocalCmd :: String -> GHCi ()
  1729. stepLocalCmd [] = do
  1730. mb_span <- getCurrentBreakSpan
  1731. case mb_span of
  1732. Nothing -> stepCmd []
  1733. Just loc -> do
  1734. Just mod <- getCurrentBreakModule
  1735. current_toplevel_decl <- enclosingTickSpan mod loc
  1736. doContinue (`isSubspanOf` current_toplevel_decl) GHC.SingleStep
  1737. stepLocalCmd expression = stepCmd expression
  1738. stepModuleCmd :: String -> GHCi ()
  1739. stepModuleCmd [] = do
  1740. mb_span <- getCurrentBreakSpan
  1741. case mb_span of
  1742. Nothing -> stepCmd []
  1743. Just _ -> do
  1744. Just span <- getCurrentBreakSpan
  1745. let f some_span = srcSpanFileName_maybe span == srcSpanFileName_maybe some_span
  1746. doContinue f GHC.SingleStep
  1747. stepModuleCmd expression = stepCmd expression
  1748. -- | Returns the span of the largest tick containing the srcspan given
  1749. enclosingTickSpan :: Module -> SrcSpan -> GHCi SrcSpan
  1750. enclosingTickSpan mod src = do
  1751. ticks <- getTickArray mod
  1752. let line = srcSpanStartLine src
  1753. ASSERT (inRange (bounds ticks) line) do
  1754. let enclosing_spans = [ span | (_,span) <- ticks ! line
  1755. , srcSpanEnd span >= srcSpanEnd src]
  1756. return . head . sortBy leftmost_largest $ enclosing_spans
  1757. traceCmd :: String -> GHCi ()
  1758. traceCmd [] = doContinue (const True) GHC.RunAndLogSteps
  1759. traceCmd expression = do runStmt expression GHC.RunAndLogSteps; return ()
  1760. continueCmd :: String -> GHCi ()
  1761. continueCmd = noArgs $ doContinue (const True) GHC.RunToCompletion
  1762. -- doContinue :: SingleStep -> GHCi ()
  1763. doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
  1764. doContinue pred step = do
  1765. runResult <- resume pred step
  1766. afterRunStmt pred runResult
  1767. return ()
  1768. abandonCmd :: String -> GHCi ()
  1769. abandonCmd = noArgs $ do
  1770. b <- GHC.abandon -- the prompt will change to indicate the new context
  1771. when (not b) $ io $ putStrLn "There is no computation running."
  1772. return ()
  1773. deleteCmd :: String -> GHCi ()
  1774. deleteCmd argLine = do
  1775. deleteSwitch $ words argLine
  1776. where
  1777. deleteSwitch :: [String] -> GHCi ()
  1778. deleteSwitch [] =
  1779. io $ putStrLn "The delete command requires at least one argument."
  1780. -- delete all break points
  1781. deleteSwitch ("*":_rest) = discardActiveBreakPoints
  1782. deleteSwitch idents = do
  1783. mapM_ deleteOneBreak idents
  1784. where
  1785. deleteOneBreak :: String -> GHCi ()
  1786. deleteOneBreak str
  1787. | all isDigit str = deleteBreak (read str)
  1788. | otherwise = return ()
  1789. historyCmd :: String -> GHCi ()
  1790. historyCmd arg
  1791. | null arg = history 20
  1792. | all isDigit arg = history (read arg)
  1793. | otherwise = io $ putStrLn "Syntax: :history [num]"
  1794. where
  1795. history num = do
  1796. resumes <- GHC.getResumeContext
  1797. case resumes of
  1798. [] -> io $ putStrLn "Not stopped at a breakpoint"
  1799. (r:_) -> do
  1800. let hist = GHC.resumeHistory r
  1801. (took,rest) = splitAt num hist
  1802. case hist of
  1803. [] -> io $ putStrLn $
  1804. "Empty history. Perhaps you forgot to use :trace?"
  1805. _ -> do
  1806. spans <- mapM GHC.getHistorySpan took
  1807. let nums = map (printf "-%-3d:") [(1::Int)..]
  1808. names = map GHC.historyEnclosingDecl took
  1809. printForUser (vcat(zipWith3
  1810. (\x y z -> x <+> y <+> z)
  1811. (map text nums)
  1812. (map (bold . ppr) names)
  1813. (map (parens . ppr) spans)))
  1814. io $ putStrLn $ if null rest then "<end of history>" else "..."
  1815. bold :: SDoc -> SDoc
  1816. bold c | do_bold = text start_bold <> c <> text end_bold
  1817. | otherwise = c
  1818. backCmd :: String -> GHCi ()
  1819. backCmd = noArgs $ do
  1820. (names, _, span) <- GHC.back
  1821. printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr span
  1822. printTypeOfNames names
  1823. -- run the command set with ":set stop <cmd>"
  1824. st <- getGHCiState
  1825. enqueueCommands [stop st]
  1826. forwardCmd :: String -> GHCi ()
  1827. forwardCmd = noArgs $ do
  1828. (names, ix, span) <- GHC.forward
  1829. printForUser $ (if (ix == 0)
  1830. then ptext (sLit "Stopped at")
  1831. else ptext (sLit "Logged breakpoint at")) <+> ppr span
  1832. printTypeOfNames names
  1833. -- run the command set with ":set stop <cmd>"
  1834. st <- getGHCiState
  1835. enqueueCommands [stop st]
  1836. -- handle the "break" command
  1837. breakCmd :: String -> GHCi ()
  1838. breakCmd argLine = do
  1839. breakSwitch $ words argLine
  1840. breakSwitch :: [String] -> GHCi ()
  1841. breakSwitch [] = do
  1842. io $ putStrLn "The break command requires at least one argument."
  1843. breakSwitch (arg1:rest)
  1844. | looksLikeModuleName arg1 && not (null rest) = do
  1845. mod <- wantInterpretedModule arg1
  1846. breakByModule mod rest
  1847. | all isDigit arg1 = do
  1848. (toplevel, _) <- GHC.getContext
  1849. case toplevel of
  1850. (mod : _) -> breakByModuleLine mod (read arg1) rest
  1851. [] -> do
  1852. io $ putStrLn "Cannot find default module for breakpoint."
  1853. io $ putStrLn "Perhaps no modules are loaded for debugging?"
  1854. | otherwise = do -- try parsing it as an identifier
  1855. wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
  1856. let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
  1857. if GHC.isGoodSrcLoc loc
  1858. then ASSERT( isExternalName name )
  1859. findBreakAndSet (GHC.nameModule name) $
  1860. findBreakByCoord (Just (GHC.srcLocFile loc))
  1861. (GHC.srcLocLine loc,
  1862. GHC.srcLocCol loc)
  1863. else noCanDo name $ text "can't find its location: " <> ppr loc
  1864. where
  1865. noCanDo n why = printForUser $
  1866. text "cannot set breakpoint on " <> ppr n <> text ": " <> why
  1867. breakByModule :: Module -> [String] -> GHCi ()
  1868. breakByModule mod (arg1:rest)
  1869. | all isDigit arg1 = do -- looks like a line number
  1870. breakByModuleLine mod (read arg1) rest
  1871. breakByModule _ _
  1872. = breakSyntax
  1873. breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
  1874. breakByModuleLine mod line args
  1875. | [] <- args = findBreakAndSet mod $ findBreakByLine line
  1876. | [col] <- args, all isDigit col =
  1877. findBreakAndSet mod $ findBreakByCoord Nothing (line, read col)
  1878. | otherwise = breakSyntax
  1879. breakSyntax :: a
  1880. breakSyntax = ghcError (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
  1881. findBreakAndSet :: Module -> (TickArray -> Maybe (Int, SrcSpan)) -> GHCi ()
  1882. findBreakAndSet mod lookupTickTree = do
  1883. tickArray <- getTickArray mod
  1884. (breakArray, _) <- getModBreak mod
  1885. case lookupTickTree tickArray of
  1886. Nothing -> io $ putStrLn $ "No breakpoints found at that location."
  1887. Just (tick, span) -> do
  1888. success <- io $ setBreakFlag True breakArray tick
  1889. if success
  1890. then do
  1891. (alreadySet, nm) <-
  1892. recordBreak $ BreakLocation
  1893. { breakModule = mod
  1894. , breakLoc = span
  1895. , breakTick = tick
  1896. , onBreakCmd = ""
  1897. }
  1898. printForUser $
  1899. text "Breakpoint " <> ppr nm <>
  1900. if alreadySet
  1901. then text " was already set at " <> ppr span
  1902. else text " activated at " <> ppr span
  1903. else do
  1904. printForUser $ text "Breakpoint could not be activated at"
  1905. <+> ppr span
  1906. -- When a line number is specified, the current policy for choosing
  1907. -- the best breakpoint is this:
  1908. -- - the leftmost complete subexpression on the specified line, or
  1909. -- - the leftmost subexpression starting on the specified line, or
  1910. -- - the rightmost subexpression enclosing the specified line
  1911. --
  1912. findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,SrcSpan)
  1913. findBreakByLine line arr
  1914. | not (inRange (bounds arr) line) = Nothing
  1915. | otherwise =
  1916. listToMaybe (sortBy (leftmost_largest `on` snd) complete) `mplus`
  1917. listToMaybe (sortBy (leftmost_smallest `on` snd) incomplete) `mplus`
  1918. listToMaybe (sortBy (rightmost `on` snd) ticks)
  1919. where
  1920. ticks = arr ! line
  1921. starts_here = [ tick | tick@(_,span) <- ticks,
  1922. GHC.srcSpanStartLine span == line ]
  1923. (complete,incomplete) = partition ends_here starts_here
  1924. where ends_here (_,span) = GHC.srcSpanEndLine span == line
  1925. findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
  1926. -> Maybe (BreakIndex,SrcSpan)
  1927. findBreakByCoord mb_file (line, col) arr
  1928. | not (inRange (bounds arr) line) = Nothing
  1929. | otherwise =
  1930. listToMaybe (sortBy (rightmost `on` snd) contains ++
  1931. sortBy (leftmost_smallest `on` snd) after_here)
  1932. where
  1933. ticks = arr ! line
  1934. -- the ticks that span this coordinate
  1935. contains = [ tick | tick@(_,span) <- ticks, span `spans` (line,col),
  1936. is_correct_file span ]
  1937. is_correct_file span
  1938. | Just f <- mb_file = GHC.srcSpanFile span == f
  1939. | otherwise = True
  1940. after_here = [ tick | tick@(_,span) <- ticks,
  1941. GHC.srcSpanStartLine span == line,
  1942. GHC.srcSpanStartCol span >= col ]
  1943. -- For now, use ANSI bold on terminals that we know support it.
  1944. -- Otherwise, we add a line of carets under the active expression instead.
  1945. -- In particular, on Windows and when running the testsuite (which sets
  1946. -- TERM to vt100 for other reasons) we get carets.
  1947. -- We really ought to use a proper termcap/terminfo library.
  1948. do_bold :: Bool
  1949. do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
  1950. where mTerm = System.Environment.getEnv "TERM"
  1951. `catchIO` \_ -> return "TERM not set"
  1952. start_bold :: String
  1953. start_bold = "\ESC[1m"
  1954. end_bold :: String
  1955. end_bold = "\ESC[0m"
  1956. listCmd :: String -> GHCi ()
  1957. listCmd "" = do
  1958. mb_span <- getCurrentBreakSpan
  1959. case mb_span of
  1960. Nothing ->
  1961. printForUser $ text "Not stopped at a breakpoint; nothing to list"
  1962. Just span
  1963. | GHC.isGoodSrcSpan span -> io $ listAround span True
  1964. | otherwise ->
  1965. do resumes <- GHC.getResumeContext
  1966. case resumes of
  1967. [] -> panic "No resumes"
  1968. (r:_) ->
  1969. do let traceIt = case GHC.resumeHistory r of
  1970. [] -> text "rerunning with :trace,"
  1971. _ -> empty
  1972. doWhat = traceIt <+> text ":back then :list"
  1973. printForUser (text "Unable to list source for" <+>
  1974. ppr span
  1975. $$ text "Try" <+> doWhat)
  1976. listCmd str = list2 (words str)
  1977. list2 :: [String] -> GHCi ()
  1978. list2 [arg] | all isDigit arg = do
  1979. (toplevel, _) <- GHC.getContext
  1980. case toplevel of
  1981. [] -> io $ putStrLn "No module to list"
  1982. (mod : _) -> listModuleLine mod (read arg)
  1983. list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
  1984. mod <- wantInterpretedModule arg1
  1985. listModuleLine mod (read arg2)
  1986. list2 [arg] = do
  1987. wantNameFromInterpretedModule noCanDo arg $ \name -> do
  1988. let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
  1989. if GHC.isGoodSrcLoc loc
  1990. then do
  1991. tickArray <- ASSERT( isExternalName name )
  1992. getTickArray (GHC.nameModule name)
  1993. let mb_span = findBreakByCoord (Just (GHC.srcLocFile loc))
  1994. (GHC.srcLocLine loc, GHC.srcLocCol loc)
  1995. tickArray
  1996. case mb_span of
  1997. Nothing -> io $ listAround (GHC.srcLocSpan loc) False
  1998. Just (_,span) -> io $ listAround span False
  1999. else
  2000. noCanDo name $ text "can't find its location: " <>
  2001. ppr loc
  2002. where
  2003. noCanDo n why = printForUser $
  2004. text "cannot list source code for " <> ppr n <> text ": " <> why
  2005. list2 _other =
  2006. io $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
  2007. listModuleLine :: Module -> Int -> GHCi ()
  2008. listModuleLine modl line = do
  2009. graph <- GHC.getModuleGraph
  2010. let this = filter ((== modl) . GHC.ms_mod) graph
  2011. case this of
  2012. [] -> panic "listModuleLine"
  2013. summ:_ -> do
  2014. let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
  2015. loc = GHC.mkSrcLoc (mkFastString (filename)) line 0
  2016. io $ listAround (GHC.srcLocSpan loc) False
  2017. -- | list a section of a source file around a particular SrcSpan.
  2018. -- If the highlight flag is True, also highlight the span using
  2019. -- start_bold\/end_bold.
  2020. listAround :: SrcSpan -> Bool -> IO ()
  2021. listAround span do_highlight = do
  2022. contents <- BS.readFile (unpackFS file)
  2023. let
  2024. lines = BS.split '\n' contents
  2025. these_lines = take (line2 - line1 + 1 + pad_before + pad_after) $
  2026. drop (line1 - 1 - pad_before) $ lines
  2027. fst_line = max 1 (line1 - pad_before)
  2028. line_nos = [ fst_line .. ]
  2029. highlighted | do_highlight = zipWith highlight line_nos these_lines
  2030. | otherwise = [\p -> BS.concat[p,l] | l <- these_lines]
  2031. bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
  2032. prefixed = zipWith ($) highlighted bs_line_nos
  2033. --
  2034. BS.putStrLn (BS.intercalate (BS.pack "\n") prefixed)
  2035. where
  2036. file = GHC.srcSpanFile span
  2037. line1 = GHC.srcSpanStartLine span
  2038. col1 = GHC.srcSpanStartCol span
  2039. line2 = GHC.srcSpanEndLine span
  2040. col2 = GHC.srcSpanEndCol span
  2041. pad_before | line1 == 1 = 0
  2042. | otherwise = 1
  2043. pad_after = 1
  2044. highlight | do_bold = highlight_bold
  2045. | otherwise = highlight_carets
  2046. highlight_bold no line prefix
  2047. | no == line1 && no == line2
  2048. = let (a,r) = BS.splitAt col1 line
  2049. (b,c) = BS.splitAt (col2-col1) r
  2050. in
  2051. BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
  2052. | no == line1
  2053. = let (a,b) = BS.splitAt col1 line in
  2054. BS.concat [prefix, a, BS.pack start_bold, b]
  2055. | no == line2
  2056. = let (a,b) = BS.splitAt col2 line in
  2057. BS.concat [prefix, a, BS.pack end_bold, b]
  2058. | otherwise = BS.concat [prefix, line]
  2059. highlight_carets no line prefix
  2060. | no == line1 && no == line2
  2061. = BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
  2062. BS.replicate (col2-col1) '^']
  2063. | no == line1
  2064. = BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
  2065. prefix, line]
  2066. | no == line2
  2067. = BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
  2068. BS.pack "^^"]
  2069. | otherwise = BS.concat [prefix, line]
  2070. where
  2071. indent = BS.pack (" " ++ replicate (length (show no)) ' ')
  2072. nl = BS.singleton '\n'
  2073. -- --------------------------------------------------------------------------
  2074. -- Tick arrays
  2075. getTickArray :: Module -> GHCi TickArray
  2076. getTickArray modl = do
  2077. st <- getGHCiState
  2078. let arrmap = tickarrays st
  2079. case lookupModuleEnv arrmap modl of
  2080. Just arr -> return arr
  2081. Nothing -> do
  2082. (_breakArray, ticks) <- getModBreak modl
  2083. let arr = mkTickArray (assocs ticks)
  2084. setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
  2085. return arr
  2086. discardTickArrays :: GHCi ()
  2087. discardTickArrays = do
  2088. st <- getGHCiState
  2089. setGHCiState st{tickarrays = emptyModuleEnv}
  2090. mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
  2091. mkTickArray ticks
  2092. = accumArray (flip (:)) [] (1, max_line)
  2093. [ (line, (nm,span)) | (nm,span) <- ticks,
  2094. line <- srcSpanLines span ]
  2095. where
  2096. max_line = foldr max 0 (map GHC.srcSpanEndLine (map snd ticks))
  2097. srcSpanLines span = [ GHC.srcSpanStartLine span ..
  2098. GHC.srcSpanEndLine span ]
  2099. lookupModule :: String -> GHCi Module
  2100. lookupModule modName
  2101. = GHC.findModule (GHC.mkModuleName modName) Nothing
  2102. -- don't reset the counter back to zero?
  2103. discardActiveBreakPoints :: GHCi ()
  2104. discardActiveBreakPoints = do
  2105. st <- getGHCiState
  2106. mapM (turnOffBreak.snd) (breaks st)
  2107. setGHCiState $ st { breaks = [] }
  2108. deleteBreak :: Int -> GHCi ()
  2109. deleteBreak identity = do
  2110. st <- getGHCiState
  2111. let oldLocations = breaks st
  2112. (this,rest) = partition (\loc -> fst loc == identity) oldLocations
  2113. if null this
  2114. then printForUser (text "Breakpoint" <+> ppr identity <+>
  2115. text "does not exist")
  2116. else do
  2117. mapM (turnOffBreak.snd) this
  2118. setGHCiState $ st { breaks = rest }
  2119. turnOffBreak :: BreakLocation -> GHCi Bool
  2120. turnOffBreak loc = do
  2121. (arr, _) <- getModBreak (breakModule loc)
  2122. io $ setBreakFlag False arr (breakTick loc)
  2123. getModBreak :: Module -> GHCi (GHC.BreakArray, Array Int SrcSpan)
  2124. getModBreak mod = do
  2125. Just mod_info <- GHC.getModuleInfo mod
  2126. let modBreaks = GHC.modInfoModBreaks mod_info
  2127. let array = GHC.modBreaks_flags modBreaks
  2128. let ticks = GHC.modBreaks_locs modBreaks
  2129. return (array, ticks)
  2130. setBreakFlag :: Bool -> GHC.BreakArray -> Int -> IO Bool
  2131. setBreakFlag toggle array index
  2132. | toggle = GHC.setBreakOn array index
  2133. | otherwise = GHC.setBreakOff array index