PageRenderTime 113ms CodeModel.GetById 31ms RepoModel.GetById 2ms app.codeStats 2ms

/ghc/InteractiveUI.hs

https://bitbucket.org/carter/ghc
Haskell | 3016 lines | 2251 code | 407 blank | 358 comment | 142 complexity | b7714f5823fba1ba12d62e7bd3fda900 MD5 | raw file

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.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]

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