PageRenderTime 38ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc/InteractiveUI.hs

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