PageRenderTime 73ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/ghc/InteractiveUI.hs

http://github.com/ghc/ghc
Haskell | 3134 lines | 2342 code | 419 blank | 373 comment | 150 complexity | f127b2330dc35464217ec761bda3a158 MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, GPL-3.0

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

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

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