1 {-# OPTIONS -fno-cse #-}
2 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
4 {-# OPTIONS_GHC -fno-warn-name-shadowing #-}
5 -----------------------------------------------------------------------------
7 -- GHC Interactive User Interface
9 -- (c) The GHC Team 2005-2006
11 -----------------------------------------------------------------------------
13 module InteractiveUI ( interactiveUI, ghciWelcomeMsg ) where
15 #include "HsVersions.h"
17 import qualified GhciMonad
18 import GhciMonad hiding (runStmt)
23 import qualified GHC hiding (resume, runStmt)
24 import GHC ( LoadHowMuch(..), Target(..), TargetId(..),
26 BreakIndex, Resume, SingleStep,
27 Ghc, handleSourceError )
30 import qualified Lexer
34 -- import PackageConfig
37 import HscTypes ( handleFlagWarnings )
39 import qualified RdrName ( getGRE_NameQualifier_maybes ) -- should this come via GHC?
40 import RdrName (RdrName)
41 import Outputable hiding (printForUser, printForUserPartWay)
42 import Module -- for ModuleEnv
46 -- Other random utilities
48 import BasicTypes hiding (isTopLevel)
49 import Panic hiding (showException)
55 import Maybes ( orElse, expectJust )
60 #ifndef mingw32_HOST_OS
61 import System.Posix hiding (getEnv)
63 import qualified System.Win32
66 import System.Console.Haskeline as Haskeline
67 import qualified System.Console.Haskeline.Encoding as Encoding
68 import Control.Monad.Trans
72 import Exception hiding (catch, block, unblock)
74 -- import Control.Concurrent
76 import System.FilePath
77 import qualified Data.ByteString.Char8 as BS
81 import System.Environment
82 import System.Exit ( exitWith, ExitCode(..) )
83 import System.Directory
85 import System.IO.Error
88 import Control.Monad as Monad
91 import GHC.Exts ( unsafeCoerce# )
93 import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
94 import GHC.IO.Handle ( hFlushAll )
98 import Data.IORef ( IORef, readIORef, writeIORef )
100 -----------------------------------------------------------------------------
102 ghciWelcomeMsg :: String
103 ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
104 ": http://www.haskell.org/ghc/ :? for help"
106 cmdName :: Command -> String
109 GLOBAL_VAR(macros_ref, [], [Command])
111 builtin_commands :: [Command]
113 -- Hugs users are accustomed to :e, so make sure it doesn't overlap
114 ("?", keepGoing help, noCompletion),
115 ("add", keepGoingPaths addModule, completeFilename),
116 ("abandon", keepGoing abandonCmd, noCompletion),
117 ("break", keepGoing breakCmd, completeIdentifier),
118 ("back", keepGoing backCmd, noCompletion),
119 ("browse", keepGoing' (browseCmd False), completeModule),
120 ("browse!", keepGoing' (browseCmd True), completeModule),
121 ("cd", keepGoing' changeDirectory, completeFilename),
122 ("check", keepGoing' checkModule, completeHomeModule),
123 ("continue", keepGoing continueCmd, noCompletion),
124 ("cmd", keepGoing cmdCmd, completeExpression),
125 ("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
126 ("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
127 ("def", keepGoing (defineMacro False), completeExpression),
128 ("def!", keepGoing (defineMacro True), completeExpression),
129 ("delete", keepGoing deleteCmd, noCompletion),
130 ("edit", keepGoing editFile, completeFilename),
131 ("etags", keepGoing createETagsFileCmd, completeFilename),
132 ("force", keepGoing forceCmd, completeExpression),
133 ("forward", keepGoing forwardCmd, noCompletion),
134 ("help", keepGoing help, noCompletion),
135 ("history", keepGoing historyCmd, noCompletion),
136 ("info", keepGoing' info, completeIdentifier),
137 ("kind", keepGoing' kindOfType, completeIdentifier),
138 ("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
139 ("list", keepGoing' listCmd, noCompletion),
140 ("module", keepGoing setContext, completeSetModule),
141 ("main", keepGoing runMain, completeFilename),
142 ("print", keepGoing printCmd, completeExpression),
143 ("quit", quit, noCompletion),
144 ("reload", keepGoing' reloadModule, noCompletion),
145 ("run", keepGoing runRun, completeFilename),
146 ("set", keepGoing setCmd, completeSetOptions),
147 ("show", keepGoing showCmd, completeShowOptions),
148 ("sprint", keepGoing sprintCmd, completeExpression),
149 ("step", keepGoing stepCmd, completeIdentifier),
150 ("steplocal", keepGoing stepLocalCmd, completeIdentifier),
151 ("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
152 ("type", keepGoing' typeOfExpr, completeExpression),
153 ("trace", keepGoing traceCmd, completeExpression),
154 ("undef", keepGoing undefineMacro, completeMacro),
155 ("unset", keepGoing unsetOptions, completeSetOptions)
159 -- We initialize readline (in the interactiveUI function) to use
160 -- word_break_chars as the default set of completion word break characters.
161 -- This can be overridden for a particular command (for example, filename
162 -- expansion shouldn't consider '/' to be a word break) by setting the third
163 -- entry in the Command tuple above.
165 -- NOTE: in order for us to override the default correctly, any custom entry
166 -- must be a SUBSET of word_break_chars.
167 word_break_chars :: String
168 word_break_chars = let symbols = "!#$%&*+/<=>?@\\^|-~"
169 specials = "(),;[]`{}"
171 in spaces ++ specials ++ symbols
173 flagWordBreakChars :: String
174 flagWordBreakChars = " \t\n"
177 keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
178 keepGoing a str = keepGoing' (lift . a) str
180 keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
181 keepGoing' a str = a str >> return False
183 keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
185 = do case toArgs str of
186 Left err -> Encoding.encode err >>= liftIO . BS.hPutStrLn stderr
190 shortHelpText :: String
191 shortHelpText = "use :? for help.\n"
195 " Commands available from the prompt:\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 " :ctags[!] [<file>] create tags file for Vi (default: \"tags\")\n" ++
206 " (!: use regex instead of line number)\n" ++
207 " :def <cmd> <expr> define a command :<cmd>\n" ++
208 " :edit <file> edit file\n" ++
209 " :edit edit last module\n" ++
210 " :etags [<file>] create tags file for Emacs (default: \"TAGS\")\n" ++
211 " :help, :? display this list of commands\n" ++
212 " :info [<name> ...] display information about the given names\n" ++
213 " :kind <type> show the kind of <type>\n" ++
214 " :load [*]<module> ... load module(s) and their dependents\n" ++
215 " :main [<arguments> ...] run the main function with the given arguments\n" ++
216 " :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
217 " :quit exit GHCi\n" ++
218 " :reload reload the current module set\n" ++
219 " :run function [<arguments> ...] run the function with the given arguments\n" ++
220 " :type <expr> show the type of <expr>\n" ++
221 " :undef <cmd> undefine user-defined command :<cmd>\n" ++
222 " :!<command> run the shell command <command>\n" ++
224 " -- Commands for debugging:\n" ++
226 " :abandon at a breakpoint, abandon current computation\n" ++
227 " :back go back in the history (after :trace)\n" ++
228 " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
229 " :break <name> set a breakpoint on the specified function\n" ++
230 " :continue resume after a breakpoint\n" ++
231 " :delete <number> delete the specified breakpoint\n" ++
232 " :delete * delete all breakpoints\n" ++
233 " :force <expr> print <expr>, forcing unevaluated parts\n" ++
234 " :forward go forward in the history (after :back)\n" ++
235 " :history [<n>] after :trace, show the execution history\n" ++
236 " :list show the source code around current breakpoint\n" ++
237 " :list identifier show the source code for <identifier>\n" ++
238 " :list [<module>] <line> show the source code around line number <line>\n" ++
239 " :print [<name> ...] prints a value without forcing its computation\n" ++
240 " :sprint [<name> ...] simplifed version of :print\n" ++
241 " :step single-step after stopping at a breakpoint\n"++
242 " :step <expr> single-step into <expr>\n"++
243 " :steplocal single-step within the current top-level binding\n"++
244 " :stepmodule single-step restricted to the current module\n"++
245 " :trace trace after stopping at a breakpoint\n"++
246 " :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
249 " -- Commands for changing settings:\n" ++
251 " :set <option> ... set options\n" ++
252 " :set args <arg> ... set the arguments returned by System.getArgs\n" ++
253 " :set prog <progname> set the value returned by System.getProgName\n" ++
254 " :set prompt <prompt> set the prompt used in GHCi\n" ++
255 " :set editor <cmd> set the command used for :edit\n" ++
256 " :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
257 " :unset <option> ... unset options\n" ++
259 " Options for ':set' and ':unset':\n" ++
261 " +m allow multiline commands\n" ++
262 " +r revert top-level expressions after each evaluation\n" ++
263 " +s print timing/memory stats after each evaluation\n" ++
264 " +t print type after evaluation\n" ++
265 " -<flags> most GHC command line flags can also be set here\n" ++
266 " (eg. -v2, -fglasgow-exts, etc.)\n" ++
267 " for GHCi-specific flags, see User's Guide,\n"++
268 " Flag reference, Interactive-mode options\n" ++
270 " -- Commands for displaying information:\n" ++
272 " :show bindings show the current bindings made at the prompt\n" ++
273 " :show breaks show the active breakpoints\n" ++
274 " :show context show the breakpoint context\n" ++
275 " :show modules show the currently loaded modules\n" ++
276 " :show packages show the currently active package flags\n" ++
277 " :show languages show the currently active language flags\n" ++
278 " :show <setting> show value of <setting>, which is one of\n" ++
279 " [args, prog, prompt, editor, stop]\n" ++
282 findEditor :: IO String
287 win <- System.Win32.getWindowsDirectory
288 return (win </> "notepad.exe")
293 foreign import ccall unsafe "rts_isProfiled" isProfiled :: IO CInt
295 default_progname, default_prompt, default_stop :: String
296 default_progname = "<interactive>"
297 default_prompt = "%s> "
300 default_args :: [String]
303 interactiveUI :: [(FilePath, Maybe Phase)] -> Maybe [String]
305 interactiveUI srcs maybe_exprs = do
306 -- although GHCi compiles with -prof, it is not usable: the byte-code
307 -- compiler and interpreter don't work with profiling. So we check for
308 -- this up front and emit a helpful error message (#2197)
309 i <- liftIO $ isProfiled
311 ghcError (InstallationError "GHCi cannot be used when compiled with -prof")
313 -- HACK! If we happen to get into an infinite loop (eg the user
314 -- types 'let x=x in x' at the prompt), then the thread will block
315 -- on a blackhole, and become unreachable during GC. The GC will
316 -- detect that it is unreachable and send it the NonTermination
317 -- exception. However, since the thread is unreachable, everything
318 -- it refers to might be finalized, including the standard Handles.
319 -- This sounds like a bug, but we don't have a good solution right
321 _ <- liftIO $ newStablePtr stdin
322 _ <- liftIO $ newStablePtr stdout
323 _ <- liftIO $ newStablePtr stderr
325 -- Initialise buffering for the *interpreted* I/O system
328 liftIO $ when (isNothing maybe_exprs) $ do
329 -- Only for GHCi (not runghc and ghc -e):
331 -- Turn buffering off for the compiled program's stdout/stderr
333 -- Turn buffering off for GHCi's stdout
335 hSetBuffering stdout NoBuffering
336 -- We don't want the cmd line to buffer any input that might be
337 -- intended for the program, so unbuffer stdin.
338 hSetBuffering stdin NoBuffering
339 #if defined(mingw32_HOST_OS)
340 -- On Unix, stdin will use the locale encoding. The IO library
341 -- doesn't do this on Windows (yet), so for now we use UTF-8,
342 -- for consistency with GHC 6.10 and to make the tests work.
343 hSetEncoding stdin utf8
346 -- initial context is just the Prelude
347 prel_mod <- GHC.lookupModule (GHC.mkModuleName "Prelude") Nothing
348 GHC.setContext [] [(prel_mod, Nothing)]
350 default_editor <- liftIO $ findEditor
352 startGHCi (runGHCi srcs maybe_exprs)
353 GHCiState{ progname = default_progname,
355 prompt = default_prompt,
357 editor = default_editor,
358 -- session = session,
363 tickarrays = emptyModuleEnv,
364 last_command = Nothing,
367 ghc_e = isJust maybe_exprs
372 withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
373 withGhcAppData right left = do
374 either_dir <- tryIO (getAppUserDataDirectory "ghc")
377 do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
381 runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
382 runGHCi paths maybe_exprs = do
384 read_dot_files = not opt_IgnoreDotGhci
386 current_dir = return (Just ".ghci")
388 app_user_dir = liftIO $ withGhcAppData
389 (\dir -> return (Just (dir </> "ghci.conf")))
393 either_dir <- liftIO $ tryIO (getEnv "HOME")
395 Right home -> return (Just (home </> ".ghci"))
398 canonicalizePath' :: FilePath -> IO (Maybe FilePath)
399 canonicalizePath' fp = liftM Just (canonicalizePath fp)
400 `catchIO` \_ -> return Nothing
402 sourceConfigFile :: FilePath -> GHCi ()
403 sourceConfigFile file = do
404 exists <- liftIO $ doesFileExist file
406 dir_ok <- liftIO $ checkPerms (getDirectory file)
407 file_ok <- liftIO $ checkPerms file
408 when (dir_ok && file_ok) $ do
409 either_hdl <- liftIO $ tryIO (openFile file ReadMode)
412 -- NOTE: this assumes that runInputT won't affect the terminal;
413 -- can we assume this will always be the case?
414 -- This would be a good place for runFileInputT.
416 do runInputTWithPrefs defaultPrefs defaultSettings $
417 runCommands $ fileLoop hdl
418 liftIO (hClose hdl `catchIO` \_ -> return ())
420 getDirectory f = case takeDirectory f of "" -> "."; d -> d
422 when (read_dot_files) $ do
423 mcfgs0 <- sequence [ current_dir, app_user_dir, home_dir ]
424 mcfgs <- liftIO $ mapM canonicalizePath' (catMaybes mcfgs0)
425 mapM_ sourceConfigFile $ nub $ catMaybes mcfgs
426 -- nub, because we don't want to read .ghci twice if the
429 -- Perform a :load for files given on the GHCi command line
430 -- When in -e mode, if the load fails then we want to stop
431 -- immediately rather than going on to evaluate the expression.
432 when (not (null paths)) $ do
433 ok <- ghciHandle (\e -> do showException e; return Failed) $
434 -- TODO: this is a hack.
435 runInputTWithPrefs defaultPrefs defaultSettings $ do
436 let (filePaths, phases) = unzip paths
437 filePaths' <- mapM (Encoding.decode . BS.pack) filePaths
438 loadModule (zip filePaths' phases)
439 when (isJust maybe_exprs && failed ok) $
440 liftIO (exitWith (ExitFailure 1))
442 -- if verbosity is greater than 0, or we are connected to a
443 -- terminal, display the prompt in the interactive loop.
444 is_tty <- liftIO (hIsTerminalDevice stdin)
445 dflags <- getDynFlags
446 let show_prompt = verbosity dflags > 0 || is_tty
451 -- enter the interactive loop
452 runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
454 -- just evaluate the expression we were given
455 enqueueCommands exprs
456 let handle e = do st <- getGHCiState
457 -- flush the interpreter's stdout/stderr on exit (#3890)
459 -- Jump through some hoops to get the
460 -- current progname in the exception text:
461 -- <progname>: <exception>
462 liftIO $ withProgName (progname st)
463 -- this used to be topHandlerFastExit, see #2228
465 runInputTWithPrefs defaultPrefs defaultSettings $ do
466 runCommands' handle (return Nothing)
469 liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
471 runGHCiInput :: InputT GHCi a -> GHCi a
473 histFile <- liftIO $ withGhcAppData (\dir -> return (Just (dir </> "ghci_history")))
475 let settings = setComplete ghciCompleteWord
476 $ defaultSettings {historyFile = histFile}
479 nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
480 nextInputLine show_prompt is_tty
482 prompt <- if show_prompt then lift mkPrompt else return ""
485 when show_prompt $ lift mkPrompt >>= liftIO . putStr
488 -- NOTE: We only read .ghci files if they are owned by the current user,
489 -- and aren't world writable. Otherwise, we could be accidentally
490 -- running code planted by a malicious third party.
492 -- Furthermore, We only read ./.ghci if . is owned by the current user
493 -- and isn't writable by anyone else. I think this is sufficient: we
494 -- don't need to check .. and ../.. etc. because "." always refers to
495 -- the same directory while a process is running.
497 checkPerms :: String -> IO Bool
498 #ifdef mingw32_HOST_OS
503 handleIO (\_ -> return False) $ do
504 st <- getFileStatus name
506 if fileOwner st /= me then do
507 putStrLn $ "WARNING: " ++ name ++ " is owned by someone else, IGNORING!"
510 let mode = System.Posix.fileMode st
511 if (groupWriteMode == (mode `intersectFileModes` groupWriteMode))
512 || (otherWriteMode == (mode `intersectFileModes` otherWriteMode))
514 putStrLn $ "*** WARNING: " ++ name ++
515 " is writable by someone else, IGNORING!"
520 fileLoop :: MonadIO m => Handle -> InputT m (Maybe String)
522 l <- liftIO $ tryIO $ hGetLine hdl
524 Left e | isEOFError e -> return Nothing
525 | InvalidArgument <- etype -> return Nothing
526 | otherwise -> liftIO $ ioError e
527 where etype = ioeGetErrorType e
528 -- treat InvalidArgument in the same way as EOF:
529 -- this can happen if the user closed stdin, or
530 -- perhaps did getContents which closes stdin at
532 Right l -> return (Just l)
534 mkPrompt :: GHCi String
536 (toplevs,exports) <- GHC.getContext
537 resumes <- GHC.getResumeContext
538 -- st <- getGHCiState
544 let ix = GHC.resumeHistoryIx r
546 then return (brackets (ppr (GHC.resumeSpan r)) <> space)
548 let hist = GHC.resumeHistory r !! (ix-1)
549 span <- GHC.getHistorySpan hist
550 return (brackets (ppr (negate ix) <> char ':'
551 <+> ppr span) <> space)
553 dots | _:rs <- resumes, not (null rs) = text "... "
558 -- let (btoplevs, bexports) = fromMaybe ([],[]) (remembered_ctx st) in
559 -- hsep (map (\m -> text "!*" <> ppr (GHC.moduleName m)) btoplevs) <+>
560 -- hsep (map (\m -> char '!' <> ppr (GHC.moduleName m)) bexports) <+>
561 hsep (map (\m -> char '*' <> ppr (GHC.moduleName m)) toplevs) <+>
562 hsep (map (ppr . GHC.moduleName) (nub (map fst exports)))
564 deflt_prompt = dots <> context_bit <> modules_bit
566 f ('%':'s':xs) = deflt_prompt <> f xs
567 f ('%':'%':xs) = char '%' <> f xs
568 f (x:xs) = char x <> f xs
572 return (showSDoc (f (prompt st)))
575 queryQueue :: GHCi (Maybe String)
580 c:cs -> do setGHCiState st{ cmdqueue = cs }
583 runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
584 runCommands = runCommands' handler
586 runCommands' :: (SomeException -> GHCi Bool) -- Exception handler
587 -> InputT GHCi (Maybe String) -> InputT GHCi ()
588 runCommands' eh getCmd = do
589 b <- ghandle (\e -> case fromException e of
590 Just UserInterrupt -> return $ Just False
591 _ -> case fromException e of
593 do liftIO (print (ghc_e :: GhcException))
596 liftIO (Exception.throwIO e))
597 (runOneCommand eh getCmd)
600 Just _ -> runCommands' eh getCmd
602 runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
603 -> InputT GHCi (Maybe Bool)
604 runOneCommand eh getCmd = do
605 mb_cmd <- noSpace (lift queryQueue)
606 mb_cmd <- maybe (noSpace getCmd) (return . Just) mb_cmd
608 Nothing -> return Nothing
609 Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
610 handleSourceError printErrorAndKeepGoing
612 -- source error's are handled by runStmt
613 -- is the handler necessary here?
615 printErrorAndKeepGoing err = do
616 GHC.printException err
619 noSpace q = q >>= maybe (return Nothing)
620 (\c->case removeSpaces c of
622 ":{" -> multiLineCmd q
623 c -> return (Just c) )
625 st <- lift getGHCiState
627 lift $ setGHCiState st{ prompt = "%s| " }
628 mb_cmd <- collectCommand q ""
629 lift $ getGHCiState >>= \st->setGHCiState st{ prompt = p }
631 -- we can't use removeSpaces for the sublines here, so
632 -- multiline commands are somewhat more brittle against
633 -- fileformat errors (such as \r in dos input on unix),
634 -- we get rid of any extra spaces for the ":}" test;
635 -- we also avoid silent failure if ":}" is not found;
636 -- and since there is no (?) valid occurrence of \r (as
637 -- opposed to its String representation, "\r") inside a
638 -- ghci command, we replace any such with ' ' (argh:-(
639 collectCommand q c = q >>=
640 maybe (liftIO (ioError collectError))
641 (\l->if removeSpaces l == ":}"
642 then return (Just $ removeSpaces c)
643 else collectCommand q (c ++ "\n" ++ map normSpace l))
644 where normSpace '\r' = ' '
646 -- QUESTION: is userError the one to use here?
647 collectError = userError "unterminated multiline command :{ .. :}"
648 doCommand (':' : cmd) = do
649 result <- specialCommand cmd
651 True -> return Nothing
652 _ -> return $ Just True
654 ml <- lift $ isOptionSet Multiline
657 mb_stmt <- checkInputForLayout stmt 1 getCmd
659 Nothing -> return $ Just True
661 result <- timeIt $ lift $ runStmt ml_stmt GHC.RunToCompletion
664 result <- timeIt $ lift $ runStmt stmt GHC.RunToCompletion
668 -- lex the input. If there is an unclosed layout context, request input
669 checkInputForLayout :: String -> Int -> InputT GHCi (Maybe String)
670 -> InputT GHCi (Maybe String)
671 checkInputForLayout stmt line_number getStmt = do
672 dflags' <- lift $ getDynFlags
673 let dflags = xopt_set dflags' Opt_AlternativeLayoutRule
674 st <- lift $ getGHCiState
675 let buf = stringToStringBuffer stmt
676 loc = mkSrcLoc (fsLit (progname st)) line_number 1
677 pstate = Lexer.mkPState dflags buf loc
678 case Lexer.unP goToEnd pstate of
679 (Lexer.POk _ False) -> return $ Just stmt
681 st <- lift getGHCiState
683 lift $ setGHCiState st{ prompt = "%s| " }
684 mb_stmt <- ghciHandle (\ex -> case fromException ex of
685 Just UserInterrupt -> return Nothing
686 _ -> case fromException ex of
688 do liftIO (print (ghc_e :: GhcException))
690 _other -> liftIO (Exception.throwIO ex))
692 lift $ getGHCiState >>= \st->setGHCiState st{ prompt = p }
693 -- the recursive call does not recycle parser state
694 -- as we use a new string buffer
696 Nothing -> return Nothing
697 Just str -> if str == ""
698 then return $ Just stmt
699 else checkInputForLayout (stmt++"\n"++str) (line_number+1) getStmt
701 eof <- Lexer.nextIsEOF
703 then Lexer.activeContext
704 else Lexer.lexer return >> goToEnd
706 enqueueCommands :: [String] -> GHCi ()
707 enqueueCommands cmds = do
709 setGHCiState st{ cmdqueue = cmds ++ cmdqueue st }
712 runStmt :: String -> SingleStep -> GHCi Bool
714 | null (filter (not.isSpace) stmt)
716 | "import " `isPrefixOf` stmt
717 = do newContextCmd (Import stmt); return False
719 = do -- In the new IO library, read handles buffer data even if the Handle
720 -- is set to NoBuffering. This causes problems for GHCi where there
721 -- are really two stdin Handles. So we flush any bufferred data in
722 -- GHCi's stdin Handle here (only relevant if stdin is attached to
723 -- a file, otherwise the read buffer can't be flushed).
724 _ <- liftIO $ tryIO $ hFlushAll stdin
725 result <- GhciMonad.runStmt stmt step
726 afterRunStmt (const True) result
728 --afterRunStmt :: GHC.RunResult -> GHCi Bool
729 -- False <=> the statement failed to compile
730 afterRunStmt :: (SrcSpan -> Bool) -> GHC.RunResult -> GHCi Bool
731 afterRunStmt _ (GHC.RunException e) = throw e
732 afterRunStmt step_here run_result = do
733 resumes <- GHC.getResumeContext
735 GHC.RunOk names -> do
736 show_types <- isOptionSet ShowType
737 when show_types $ printTypeOfNames names
738 GHC.RunBreak _ names mb_info
739 | isNothing mb_info ||
740 step_here (GHC.resumeSpan $ head resumes) -> do
741 mb_id_loc <- toBreakIdAndLocation mb_info
742 let breakCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
744 then printStoppedAtBreakInfo (head resumes) names
745 else enqueueCommands [breakCmd]
746 -- run the command set with ":set stop <cmd>"
748 enqueueCommands [stop st]
750 | otherwise -> resume step_here GHC.SingleStep >>=
751 afterRunStmt step_here >> return ()
755 liftIO installSignalHandlers
756 b <- isOptionSet RevertCAFs
759 return (case run_result of GHC.RunOk _ -> True; _ -> False)
761 toBreakIdAndLocation ::
762 Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
763 toBreakIdAndLocation Nothing = return Nothing
764 toBreakIdAndLocation (Just info) = do
765 let mod = GHC.breakInfo_module info
766 nm = GHC.breakInfo_number info
768 return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
769 breakModule loc == mod,
770 breakTick loc == nm ]
772 printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
773 printStoppedAtBreakInfo resume names = do
774 printForUser $ ptext (sLit "Stopped at") <+>
775 ppr (GHC.resumeSpan resume)
776 -- printTypeOfNames session names
777 let namesSorted = sortBy compareNames names
778 tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
779 docs <- pprTypeAndContents [id | AnId id <- tythings]
780 printForUserPartWay docs
782 printTypeOfNames :: [Name] -> GHCi ()
783 printTypeOfNames names
784 = mapM_ (printTypeOfName ) $ sortBy compareNames names
786 compareNames :: Name -> Name -> Ordering
787 n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
788 where compareWith n = (getOccString n, getSrcSpan n)
790 printTypeOfName :: Name -> GHCi ()
792 = do maybe_tything <- GHC.lookupName n
793 case maybe_tything of
795 Just thing -> printTyThing thing
798 data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
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
806 GotCommand (_,f,_) -> f (dropWhile isSpace rest)
808 do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
812 do liftIO $ hPutStr stdout ("there is no last command to perform\n"
816 lookupCommand :: String -> GHCi (MaybeCommand)
817 lookupCommand "" = do
819 case last_command st of
820 Just c -> return $ GotCommand c
821 Nothing -> return NoLastCommand
822 lookupCommand str = do
823 mc <- liftIO $ lookupCommand' str
825 setGHCiState st{ last_command = mc }
827 Just c -> GotCommand c
828 Nothing -> BadCommand
830 lookupCommand' :: String -> IO (Maybe Command)
831 lookupCommand' ":" = return Nothing
832 lookupCommand' str' = do
833 macros <- readIORef macros_ref
834 let{ (str, cmds) = case str' of
835 ':' : rest -> (rest, builtin_commands)
836 _ -> (str', macros ++ builtin_commands) }
837 -- look for exact match first, then the first prefix match
838 return $ case [ c | c <- cmds, str == cmdName c ] of
840 [] -> case [ c | c@(s,_,_) <- cmds, str `isPrefixOf` s ] of
844 getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
845 getCurrentBreakSpan = do
846 resumes <- GHC.getResumeContext
850 let ix = GHC.resumeHistoryIx r
852 then return (Just (GHC.resumeSpan r))
854 let hist = GHC.resumeHistory r !! (ix-1)
855 span <- GHC.getHistorySpan hist
858 getCurrentBreakModule :: GHCi (Maybe Module)
859 getCurrentBreakModule = do
860 resumes <- GHC.getResumeContext
864 let ix = GHC.resumeHistoryIx r
866 then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
868 let hist = GHC.resumeHistory r !! (ix-1)
869 return $ Just $ GHC.getHistoryModule hist
871 -----------------------------------------------------------------------------
874 noArgs :: GHCi () -> String -> GHCi ()
876 noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
878 help :: String -> GHCi ()
879 help _ = liftIO (putStr helpText)
881 info :: String -> InputT GHCi ()
882 info "" = ghcError (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
883 info s = handleSourceError GHC.printException $
884 do { let names = words s
885 ; dflags <- getDynFlags
886 ; let pefas = dopt Opt_PrintExplicitForalls dflags
887 ; mapM_ (infoThing pefas) names }
889 infoThing pefas str = do
890 names <- GHC.parseName str
891 mb_stuffs <- mapM GHC.getInfo names
892 let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
893 unqual <- GHC.getPrintUnqual
894 liftIO $ putStrLn $ showSDocForUser unqual $
895 vcat (intersperse (text "") $
896 map (pprInfo pefas) filtered)
898 -- Filter out names whose parent is also there Good
899 -- example is '[]', which is both a type and data
900 -- constructor in the same type
901 filterOutChildren :: (a -> TyThing) -> [a] -> [a]
902 filterOutChildren get_thing xs
903 = filterOut has_parent xs
905 all_names = mkNameSet (map (getName . get_thing) xs)
906 has_parent x = case pprTyThingParent_maybe (get_thing x) of
907 Just p -> getName p `elemNameSet` all_names
910 pprInfo :: PrintExplicitForalls -> (TyThing, Fixity, [GHC.Instance]) -> SDoc
911 pprInfo pefas (thing, fixity, insts)
912 = pprTyThingInContextLoc pefas thing
913 $$ show_fixity fixity
914 $$ vcat (map GHC.pprInstance insts)
917 | fix == GHC.defaultFixity = empty
918 | otherwise = ppr fix <+> ppr (GHC.getName thing)
920 runMain :: String -> GHCi ()
921 runMain s = case toArgs s of
922 Left err -> liftIO (hPutStrLn stderr err)
924 do dflags <- getDynFlags
925 case mainFunIs dflags of
926 Nothing -> doWithArgs args "main"
927 Just f -> doWithArgs args f
929 runRun :: String -> GHCi ()
930 runRun s = case toCmdArgs s of
931 Left err -> liftIO (hPutStrLn stderr err)
932 Right (cmd, args) -> doWithArgs args cmd
934 doWithArgs :: [String] -> String -> GHCi ()
935 doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
936 show args ++ " (" ++ cmd ++ ")"]
938 addModule :: [FilePath] -> InputT GHCi ()
940 lift revertCAFs -- always revert CAFs on load/add.
941 files <- mapM expandPath files
942 targets <- mapM (\m -> GHC.guessTarget m Nothing) files
943 -- remove old targets with the same id; e.g. for :add *M
944 mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
945 mapM_ GHC.addTarget targets
946 prev_context <- GHC.getContext
947 ok <- trySuccess $ GHC.load LoadAllTargets
948 afterLoad ok False prev_context
950 changeDirectory :: String -> InputT GHCi ()
951 changeDirectory "" = do
952 -- :cd on its own changes to the user's home directory
953 either_dir <- liftIO $ tryIO getHomeDirectory
956 Right dir -> changeDirectory dir
957 changeDirectory dir = do
958 graph <- GHC.getModuleGraph
959 when (not (null graph)) $
960 liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
961 prev_context <- GHC.getContext
963 _ <- GHC.load LoadAllTargets
964 lift $ setContextAfterLoad prev_context False []
965 GHC.workingDirectoryChanged
966 dir <- expandPath dir
967 liftIO $ setCurrentDirectory dir
969 trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
971 handleSourceError (\e -> do GHC.printException e
975 editFile :: String -> GHCi ()
977 do file <- if null str then chooseEditFile else return str
981 $ ghcError (CmdLineError "editor not set, use :set editor")
982 _ <- liftIO $ system (cmd ++ ' ':file)
985 -- The user didn't specify a file so we pick one for them.
986 -- Our strategy is to pick the first module that failed to load,
987 -- or otherwise the first target.
989 -- XXX: Can we figure out what happened if the depndecy analysis fails
990 -- (e.g., because the porgrammeer mistyped the name of a module)?
991 -- XXX: Can we figure out the location of an error to pass to the editor?
992 -- XXX: if we could figure out the list of errors that occured during the
993 -- last load/reaload, then we could start the editor focused on the first
995 chooseEditFile :: GHCi String
997 do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
999 graph <- GHC.getModuleGraph
1000 failed_graph <- filterM hasFailed graph
1001 let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
1002 pick xs = case xs of
1003 x : _ -> GHC.ml_hs_file (GHC.ms_location x)
1006 case pick (order failed_graph) of
1007 Just file -> return file
1009 do targets <- GHC.getTargets
1010 case msum (map fromTarget targets) of
1011 Just file -> return file
1012 Nothing -> ghcError (CmdLineError "No files to edit.")
1014 where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
1015 fromTarget _ = Nothing -- when would we get a module target?
1017 defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
1018 defineMacro _ (':':_) =
1019 liftIO $ putStrLn "macro name cannot start with a colon"
1020 defineMacro overwrite s = do
1021 let (macro_name, definition) = break isSpace s
1022 macros <- liftIO (readIORef macros_ref)
1023 let defined = map cmdName macros
1024 if (null macro_name)
1025 then if null defined
1026 then liftIO $ putStrLn "no macros defined"
1027 else liftIO $ putStr ("the following macros are defined:\n" ++
1030 if (not overwrite && macro_name `elem` defined)
1031 then ghcError (CmdLineError
1032 ("macro '" ++ macro_name ++ "' is already defined"))
1035 let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
1037 -- give the expression a type signature, so we can be sure we're getting
1038 -- something of the right type.
1039 let new_expr = '(' : definition ++ ") :: String -> IO String"
1041 -- compile the expression
1042 handleSourceError (\e -> GHC.printException e) $
1044 hv <- GHC.compileExpr new_expr
1045 liftIO (writeIORef macros_ref --
1046 (filtered ++ [(macro_name, lift . runMacro hv, noCompletion)]))
1048 runMacro :: GHC.HValue{-String -> IO String-} -> String -> GHCi Bool
1050 str <- liftIO ((unsafeCoerce# fun :: String -> IO String) s)
1051 -- make sure we force any exceptions in the result, while we are still
1052 -- inside the exception handler for commands:
1053 seqList str (return ())
1054 enqueueCommands (lines str)
1057 undefineMacro :: String -> GHCi ()
1058 undefineMacro str = mapM_ undef (words str)
1059 where undef macro_name = do
1060 cmds <- liftIO (readIORef macros_ref)
1061 if (macro_name `notElem` map cmdName cmds)
1062 then ghcError (CmdLineError
1063 ("macro '" ++ macro_name ++ "' is not defined"))
1065 liftIO (writeIORef macros_ref (filter ((/= macro_name) . cmdName) cmds))
1067 cmdCmd :: String -> GHCi ()
1069 let expr = '(' : str ++ ") :: IO String"
1070 handleSourceError (\e -> GHC.printException e) $
1072 hv <- GHC.compileExpr expr
1073 cmds <- liftIO $ (unsafeCoerce# hv :: IO String)
1074 enqueueCommands (lines cmds)
1077 loadModuleName :: GHC.GhcMonad m => ImportDecl RdrName -> m Module
1078 loadModuleName = flip GHC.findModule Nothing . unLoc . ideclName
1080 loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
1081 loadModule fs = timeIt (loadModule' fs)
1083 loadModule_ :: [FilePath] -> InputT GHCi ()
1084 loadModule_ fs = loadModule (zip fs (repeat Nothing)) >> return ()
1086 loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
1087 loadModule' files = do
1088 prev_context <- GHC.getContext
1092 lift discardActiveBreakPoints
1094 _ <- GHC.load LoadAllTargets
1096 let (filenames, phases) = unzip files
1097 exp_filenames <- mapM expandPath filenames
1098 let files' = zip exp_filenames phases
1099 targets <- mapM (uncurry GHC.guessTarget) files'
1101 -- NOTE: we used to do the dependency anal first, so that if it
1102 -- fails we didn't throw away the current set of modules. This would
1103 -- require some re-working of the GHC interface, so we'll leave it
1104 -- as a ToDo for now.
1106 GHC.setTargets targets
1107 doLoad False prev_context LoadAllTargets
1109 checkModule :: String -> InputT GHCi ()
1111 let modl = GHC.mkModuleName m
1112 prev_context <- GHC.getContext
1113 ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
1114 r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
1115 liftIO $ putStrLn $ showSDoc $
1116 case GHC.moduleInfo r of
1117 cm | Just scope <- GHC.modInfoTopLevelScope cm ->
1119 (local,global) = ASSERT( all isExternalName scope )
1120 partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
1122 (text "global names: " <+> ppr global) $$
1123 (text "local names: " <+> ppr local)
1126 afterLoad (successIf ok) False prev_context
1128 reloadModule :: String -> InputT GHCi ()
1130 prev_context <- GHC.getContext
1131 _ <- doLoad True prev_context $
1132 if null m then LoadAllTargets
1133 else LoadUpTo (GHC.mkModuleName m)
1136 doLoad :: Bool -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> LoadHowMuch -> InputT GHCi SuccessFlag
1137 doLoad retain_context prev_context howmuch = do
1138 -- turn off breakpoints before we load: we can't turn them off later, because
1139 -- the ModBreaks will have gone away.
1140 lift discardActiveBreakPoints
1141 ok <- trySuccess $ GHC.load howmuch
1142 afterLoad ok retain_context prev_context
1145 afterLoad :: SuccessFlag -> Bool -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> InputT GHCi ()
1146 afterLoad ok retain_context prev_context = do
1147 lift revertCAFs -- always revert CAFs on load.
1148 lift discardTickArrays
1149 loaded_mod_summaries <- getLoadedModules
1150 let loaded_mods = map GHC.ms_mod loaded_mod_summaries
1151 loaded_mod_names = map GHC.moduleName loaded_mods
1152 modulesLoadedMsg ok loaded_mod_names
1154 lift $ setContextAfterLoad prev_context retain_context loaded_mod_summaries
1157 setContextAfterLoad :: ([Module],[(Module, Maybe (ImportDecl RdrName))]) -> Bool -> [GHC.ModSummary] -> GHCi ()
1158 setContextAfterLoad prev keep_ctxt [] = do
1159 prel_mod <- getPrelude
1160 setContextKeepingPackageModules prev keep_ctxt ([], [(prel_mod, Nothing)])
1161 setContextAfterLoad prev keep_ctxt ms = do
1162 -- load a target if one is available, otherwise load the topmost module.
1163 targets <- GHC.getTargets
1164 case [ m | Just m <- map (findTarget ms) targets ] of
1166 let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
1167 load_this (last graph')
1172 = case filter (`matches` t) ms of
1176 summary `matches` Target (TargetModule m) _ _
1177 = GHC.ms_mod_name summary == m
1178 summary `matches` Target (TargetFile f _) _ _
1179 | Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
1183 load_this summary | m <- GHC.ms_mod summary = do
1184 b <- GHC.moduleIsInterpreted m
1185 if b then setContextKeepingPackageModules prev keep_ctxt ([m], [])
1187 prel_mod <- getPrelude
1188 setContextKeepingPackageModules prev keep_ctxt ([],[(prel_mod,Nothing),(m,Nothing)])
1190 -- | Keep any package modules (except Prelude) when changing the context.
1191 setContextKeepingPackageModules
1192 :: ([Module],[(Module, Maybe (ImportDecl RdrName))]) -- previous context
1193 -> Bool -- re-execute :module commands
1194 -> ([Module],[(Module, Maybe (ImportDecl RdrName))]) -- new context
1196 setContextKeepingPackageModules prev_context keep_ctxt (as,bs) = do
1197 let (_,bs0) = prev_context
1198 prel_mod <- getPrelude
1199 -- filter everything, not just lefts
1200 let pkg_modules = filter ((\p -> not (isHomeModule p) && p /= prel_mod) . fst) bs0
1201 let bs1 = if null as then nubBy sameFst ((prel_mod,Nothing) : bs) else bs
1202 GHC.setContext as (nubBy sameFst (bs1 ++ pkg_modules))
1206 mapM_ (playCtxtCmd False) (remembered_ctx st)
1209 setGHCiState st{ remembered_ctx = [] }
1211 isHomeModule :: Module -> Bool
1212 isHomeModule mod = GHC.modulePackageId mod == mainPackageId
1214 sameFst :: (Module, Maybe (ImportDecl RdrName)) -> (Module, Maybe (ImportDecl RdrName)) -> Bool
1215 sameFst x y = fst x == fst y
1217 modulesLoadedMsg :: SuccessFlag -> [ModuleName] -> InputT GHCi ()
1218 modulesLoadedMsg ok mods = do
1219 dflags <- getDynFlags
1220 when (verbosity dflags > 0) $ do
1222 | null mods = text "none."
1223 | otherwise = hsep (
1224 punctuate comma (map ppr mods)) <> text "."
1227 liftIO $ putStrLn $ showSDoc (text "Failed, modules loaded: " <> mod_commas)
1229 liftIO $ putStrLn $ showSDoc (text "Ok, modules loaded: " <> mod_commas)
1232 typeOfExpr :: String -> InputT GHCi ()
1234 = handleSourceError GHC.printException
1236 ty <- GHC.exprType str
1237 dflags <- getDynFlags
1238 let pefas = dopt Opt_PrintExplicitForalls dflags
1239 printForUser $ sep [text str, nest 2 (dcolon <+> pprTypeForUser pefas ty)]
1241 kindOfType :: String -> InputT GHCi ()
1243 = handleSourceError GHC.printException
1245 ty <- GHC.typeKind str
1246 printForUser $ text str <+> dcolon <+> ppr ty
1248 quit :: String -> InputT GHCi Bool
1249 quit _ = return True
1251 shellEscape :: String -> GHCi Bool
1252 shellEscape str = liftIO (system str >> return False)
1254 -----------------------------------------------------------------------------
1255 -- Browsing a module's contents
1257 browseCmd :: Bool -> String -> InputT GHCi ()
1260 ['*':s] | looksLikeModuleName s -> do
1261 m <- lift $ wantInterpretedModule s
1262 browseModule bang m False
1263 [s] | looksLikeModuleName s -> do
1264 m <- lift $ lookupModule s
1265 browseModule bang m True
1267 (as,bs) <- GHC.getContext
1268 -- Guess which module the user wants to browse. Pick
1269 -- modules that are interpreted first. The most
1270 -- recently-added module occurs last, it seems.
1272 (as@(_:_), _) -> browseModule bang (last as) True
1273 ([], bs@(_:_)) -> browseModule bang (fst (last bs)) True
1274 ([], []) -> ghcError (CmdLineError ":browse: no current module")
1275 _ -> ghcError (CmdLineError "syntax: :browse <module>")
1277 -- without bang, show items in context of their parents and omit children
1278 -- with bang, show class methods and data constructors separately, and
1279 -- indicate import modules, to aid qualifying unqualified names
1280 -- with sorted, sort items alphabetically
1281 browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
1282 browseModule bang modl exports_only = do
1283 -- :browse! reports qualifiers wrt current context
1284 current_unqual <- GHC.getPrintUnqual
1285 -- Temporarily set the context to the module we're interested in,
1286 -- just so we can get an appropriate PrintUnqualified
1287 (as,bs) <- GHC.getContext
1288 prel_mod <- lift getPrelude
1289 if exports_only then GHC.setContext [] [(prel_mod,Nothing), (modl,Nothing)]
1290 else GHC.setContext [modl] []
1291 target_unqual <- GHC.getPrintUnqual
1292 GHC.setContext as bs
1294 let unqual = if bang then current_unqual else target_unqual
1296 mb_mod_info <- GHC.getModuleInfo modl
1298 Nothing -> ghcError (CmdLineError ("unknown module: " ++
1299 GHC.moduleNameString (GHC.moduleName modl)))
1301 dflags <- getDynFlags
1303 | exports_only = GHC.modInfoExports mod_info
1304 | otherwise = GHC.modInfoTopLevelScope mod_info
1307 -- sort alphabetically name, but putting
1308 -- locally-defined identifiers first.
1309 -- We would like to improve this; see #1799.
1310 sorted_names = loc_sort local ++ occ_sort external
1312 (local,external) = ASSERT( all isExternalName names )
1313 partition ((==modl) . nameModule) names
1314 occ_sort = sortBy (compare `on` nameOccName)
1315 -- try to sort by src location. If the first name in
1316 -- our list has a good source location, then they all should.
1318 | n:_ <- names, isGoodSrcSpan (nameSrcSpan n)
1319 = sortBy (compare `on` nameSrcSpan) names
1323 mb_things <- mapM GHC.lookupName sorted_names
1324 let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
1326 rdr_env <- GHC.getGRE
1328 let pefas = dopt Opt_PrintExplicitForalls dflags
1329 things | bang = catMaybes mb_things
1330 | otherwise = filtered_things
1331 pretty | bang = pprTyThing
1332 | otherwise = pprTyThingInContext
1334 labels [] = text "-- not currently imported"
1335 labels l = text $ intercalate "\n" $ map qualifier l
1336 qualifier = maybe "-- defined locally"
1337 (("-- imported via "++) . intercalate ", "
1338 . map GHC.moduleNameString)
1339 importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
1340 modNames = map (importInfo . GHC.getName) things
1342 -- annotate groups of imports with their import modules
1343 -- the default ordering is somewhat arbitrary, so we group
1344 -- by header and sort groups; the names themselves should
1345 -- really come in order of source appearance.. (trac #1799)
1346 annotate mts = concatMap (\(m,ts)->labels m:ts)
1347 $ sortBy cmpQualifiers $ group mts
1348 where cmpQualifiers =
1349 compare `on` (map (fmap (map moduleNameFS)) . fst)
1351 group mts@((m,_):_) = (m,map snd g) : group ng
1352 where (g,ng) = partition ((==m).fst) mts
1354 let prettyThings = map (pretty pefas) things
1355 prettyThings' | bang = annotate $ zip modNames prettyThings
1356 | otherwise = prettyThings
1357 liftIO $ putStrLn $ showSDocForUser unqual (vcat prettyThings')
1358 -- ToDo: modInfoInstances currently throws an exception for
1359 -- package modules. When it works, we can do this:
1360 -- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
1362 -----------------------------------------------------------------------------
1363 -- Setting the module context
1365 newContextCmd :: CtxtCmd -> GHCi ()
1366 newContextCmd cmd = do
1367 playCtxtCmd True cmd
1369 let cmds = remembered_ctx st
1370 setGHCiState st{ remembered_ctx = cmds ++ [cmd] }
1372 setContext :: String -> GHCi ()
1374 | all sensible strs = newContextCmd cmd
1375 | otherwise = ghcError (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
1379 '+':stuff -> rest AddModules stuff
1380 '-':stuff -> rest RemModules stuff
1381 stuff -> rest SetContext stuff
1383 rest cmd stuff = (cmd as bs, strs)
1384 where strs = words stuff
1385 (as,bs) = partitionWith starred strs
1387 sensible ('*':m) = looksLikeModuleName m
1388 sensible m = looksLikeModuleName m
1390 starred ('*':m) = Left m
1393 playCtxtCmd:: Bool -> CtxtCmd -> GHCi ()
1394 playCtxtCmd fail cmd = do
1395 (prev_as,prev_bs) <- GHC.getContext
1397 SetContext as bs -> do
1398 (as',bs') <- do_checks as bs
1399 prel_mod <- getPrelude
1400 let bs'' = if null as && prel_mod `notElem` (map fst bs')
1401 then (prel_mod,Nothing):bs'
1403 GHC.setContext as' bs''
1405 AddModules as bs -> do
1406 (as',bs') <- do_checks as bs
1407 -- it should replace the old stuff, not the other way around
1408 -- need deleteAllBy, not deleteFirstsBy for sameFst
1409 let remaining_as = prev_as \\ (as' ++ map fst bs')
1410 remaining_bs = deleteAllBy sameFst prev_bs (bs' ++ map contextualize as')
1411 GHC.setContext (remaining_as ++ as') (remaining_bs ++ bs')
1413 RemModules as bs -> do
1414 (as',bs') <- do_checks as bs
1415 let new_as = prev_as \\ (as' ++ map fst bs')
1416 new_bs = deleteAllBy sameFst prev_bs (map contextualize as' ++ bs')
1417 GHC.setContext new_as new_bs
1420 m_idecl <- maybe_fail $ GHC.parseImportDecl str
1422 Nothing -> return ()
1424 m_mdl <- maybe_fail $ loadModuleName idecl
1426 Nothing -> return ()
1427 Just m -> GHC.setContext prev_as (prev_bs ++ [(m, Just idecl)])
1430 maybe_fail | fail = liftM Just
1431 | otherwise = trymaybe
1433 do_checks as bs = do
1434 as' <- mapM (maybe_fail . wantInterpretedModule) as
1435 bs' <- mapM (maybe_fail . lookupModule) bs
1436 return (catMaybes as', map contextualize (catMaybes bs'))
1438 contextualize x = (x,Nothing)
1439 deleteAllBy f a b = filter (\x->(not (any (f x) b))) a
1441 trymaybe ::GHCi a -> GHCi (Maybe a)
1445 Left _ -> return Nothing
1446 Right a -> return (Just a)
1448 ----------------------------------------------------------------------------
1451 -- set options in the interpreter. Syntax is exactly the same as the
1452 -- ghc command line, except that certain options aren't available (-C,
1455 -- This is pretty fragile: most options won't work as expected. ToDo:
1456 -- figure out which ones & disallow them.
1458 setCmd :: String -> GHCi ()
1460 = do st <- getGHCiState
1461 let opts = options st
1462 liftIO $ putStrLn (showSDoc (
1463 text "options currently set: " <>
1466 else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
1468 dflags <- getDynFlags
1469 liftIO $ putStrLn (showSDoc (
1470 vcat (text "GHCi-specific dynamic flag settings:"
1471 :map (flagSetting dflags) ghciFlags)
1473 liftIO $ putStrLn (showSDoc (
1474 vcat (text "other dynamic, non-language, flag settings:"
1475 :map (flagSetting dflags) others)
1477 where flagSetting dflags (str, f, _)
1478 | dopt f dflags = text " " <> text "-f" <> text str
1479 | otherwise = text " " <> text "-fno-" <> text str
1480 (ghciFlags,others) = partition (\(_, f, _) -> f `elem` flags)
1482 flags = [Opt_PrintExplicitForalls
1483 ,Opt_PrintBindResult
1484 ,Opt_BreakOnException
1486 ,Opt_PrintEvldWithShow
1489 = case getCmd str of
1490 Right ("args", rest) ->
1492 Left err -> liftIO (hPutStrLn stderr err)
1493 Right args -> setArgs args
1494 Right ("prog", rest) ->
1496 Right [prog] -> setProg prog
1497 _ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
1498 Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
1499 Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
1500 Right ("stop", rest) -> setStop $ dropWhile isSpace rest
1501 _ -> case toArgs str of
1502 Left err -> liftIO (hPutStrLn stderr err)
1503 Right wds -> setOptions wds
1505 setArgs, setOptions :: [String] -> GHCi ()
1506 setProg, setEditor, setStop, setPrompt :: String -> GHCi ()
1510 setGHCiState st{ args = args }
1514 setGHCiState st{ progname = prog }
1518 setGHCiState st{ editor = cmd }
1520 setStop str@(c:_) | isDigit c
1521 = do let (nm_str,rest) = break (not.isDigit) str
1524 let old_breaks = breaks st
1525 if all ((/= nm) . fst) old_breaks
1526 then printForUser (text "Breakpoint" <+> ppr nm <+>
1527 text "does not exist")
1529 let new_breaks = map fn old_breaks
1530 fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
1531 | otherwise = (i,loc)
1532 setGHCiState st{ breaks = new_breaks }
1535 setGHCiState st{ stop = cmd }
1537 setPrompt value = do
1540 then liftIO $ hPutStrLn stderr $ "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
1542 '\"' : _ -> case reads value of
1543 [(value', xs)] | all isSpace xs ->
1544 setGHCiState (st { prompt = value' })
1546 liftIO $ hPutStrLn stderr "Can't parse prompt string. Use Haskell syntax."
1547 _ -> setGHCiState (st { prompt = value })
1550 do -- first, deal with the GHCi opts (+s, +t, etc.)
1551 let (plus_opts, minus_opts) = partitionWith isPlus wds
1552 mapM_ setOpt plus_opts
1553 -- then, dynamic flags
1554 newDynFlags minus_opts
1556 newDynFlags :: [String] -> GHCi ()
1557 newDynFlags minus_opts = do
1558 dflags <- getDynFlags
1559 let pkg_flags = packageFlags dflags
1560 (dflags', leftovers, warns) <- liftIO $ GHC.parseDynamicFlags dflags $ map noLoc minus_opts
1561 liftIO $ handleFlagWarnings dflags' warns
1563 if (not (null leftovers))
1564 then ghcError . CmdLineError
1565 $ "Some flags have not been recognized: "
1566 ++ (concat . intersperse ", " $ map unLoc leftovers)
1569 new_pkgs <- setDynFlags dflags'
1571 -- if the package flags changed, we should reset the context
1572 -- and link the new packages.
1573 dflags <- getDynFlags
1574 when (packageFlags dflags /= pkg_flags) $ do
1575 liftIO $ hPutStrLn stderr "package flags have changed, resetting and loading new packages..."
1577 _ <- GHC.load LoadAllTargets
1578 liftIO (linkPackages dflags new_pkgs)
1579 -- package flags changed, we can't re-use any of the old context
1580 setContextAfterLoad ([],[]) False []
1584 unsetOptions :: String -> GHCi ()
1586 = -- first, deal with the GHCi opts (+s, +t, etc.)
1587 let opts = words str
1588 (minus_opts, rest1) = partition isMinus opts
1589 (plus_opts, rest2) = partitionWith isPlus rest1
1590 (other_opts, rest3) = partition (`elem` map fst defaulters) rest2
1593 [ ("args" , setArgs default_args)
1594 , ("prog" , setProg default_progname)
1595 , ("prompt", setPrompt default_prompt)
1596 , ("editor", liftIO findEditor >>= setEditor)
1597 , ("stop" , setStop default_stop)
1600 no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
1601 no_flag f = ghcError (ProgramError ("don't know how to reverse " ++ f))
1603 in if (not (null rest3))
1604 then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
1606 mapM_ (fromJust.flip lookup defaulters) other_opts
1608 mapM_ unsetOpt plus_opts
1610 no_flags <- mapM no_flag minus_opts
1611 newDynFlags no_flags
1613 isMinus :: String -> Bool
1614 isMinus ('-':_) = True
1617 isPlus :: String -> Either String String
1618 isPlus ('+':opt) = Left opt
1619 isPlus other = Right other
1621 setOpt, unsetOpt :: String -> GHCi ()
1624 = case strToGHCiOpt str of
1625 Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
1626 Just o -> setOption o
1629 = case strToGHCiOpt str of
1630 Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
1631 Just o -> unsetOption o
1633 strToGHCiOpt :: String -> (Maybe GHCiOption)
1634 strToGHCiOpt "m" = Just Multiline
1635 strToGHCiOpt "s" = Just ShowTiming
1636 strToGHCiOpt "t" = Just ShowType
1637 strToGHCiOpt "r" = Just RevertCAFs
1638 strToGHCiOpt _ = Nothing
1640 optToStr :: GHCiOption -> String
1641 optToStr Multiline = "m"
1642 optToStr ShowTiming = "s"
1643 optToStr ShowType = "t"
1644 optToStr RevertCAFs = "r"
1646 -- ---------------------------------------------------------------------------
1649 showCmd :: String -> GHCi ()
1653 ["args"] -> liftIO $ putStrLn (show (args st))
1654 ["prog"] -> liftIO $ putStrLn (show (progname st))
1655 ["prompt"] -> liftIO $ putStrLn (show (prompt st))
1656 ["editor"] -> liftIO $ putStrLn (show (editor st))
1657 ["stop"] -> liftIO $ putStrLn (show (stop st))
1658 ["modules" ] -> showModules
1659 ["bindings"] -> showBindings
1660 ["linker"] -> liftIO showLinkerState
1661 ["breaks"] -> showBkptTable
1662 ["context"] -> showContext
1663 ["packages"] -> showPackages
1664 ["languages"] -> showLanguages
1665 _ -> ghcError (CmdLineError ("syntax: :show [ args | prog | prompt | editor | stop | modules | bindings\n"++
1666 " | breaks | context | packages | languages ]"))
1668 showModules :: GHCi ()
1670 loaded_mods <- getLoadedModules
1671 -- we want *loaded* modules only, see #1734
1672 let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
1673 mapM_ show_one loaded_mods
1675 getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
1676 getLoadedModules = do
1677 graph <- GHC.getModuleGraph
1678 filterM (GHC.isLoaded . GHC.ms_mod_name) graph
1680 showBindings :: GHCi ()
1682 bindings <- GHC.getBindings
1683 docs <- pprTypeAndContents
1684 [ id | AnId id <- sortBy compareTyThings bindings]
1685 printForUserPartWay docs
1687 compareTyThings :: TyThing -> TyThing -> Ordering
1688 t1 `compareTyThings` t2 = getName t1 `compareNames` getName t2
1690 printTyThing :: TyThing -> GHCi ()
1691 printTyThing tyth = do dflags <- getDynFlags
1692 let pefas = dopt Opt_PrintExplicitForalls dflags
1693 printForUser (pprTyThing pefas tyth)
1695 showBkptTable :: GHCi ()
1698 printForUser $ prettyLocations (breaks st)
1700 showContext :: GHCi ()
1702 resumes <- GHC.getResumeContext
1703 printForUser $ vcat (map pp_resume (reverse resumes))
1706 ptext (sLit "--> ") <> text (GHC.resumeStmt resume)
1707 $$ nest 2 (ptext (sLit "Stopped at") <+> ppr (GHC.resumeSpan resume))
1709 showPackages :: GHCi ()
1711 pkg_flags <- fmap packageFlags getDynFlags
1712 liftIO $ putStrLn $ showSDoc $ vcat $
1713 text ("active package flags:"++if null pkg_flags then " none" else "")
1714 : map showFlag pkg_flags
1715 where showFlag (ExposePackage p) = text $ " -package " ++ p
1716 showFlag (HidePackage p) = text $ " -hide-package " ++ p
1717 showFlag (IgnorePackage p) = text $ " -ignore-package " ++ p
1718 showFlag (ExposePackageId p) = text $ " -package-id " ++ p
1720 showLanguages :: GHCi ()
1722 dflags <- getDynFlags
1723 liftIO $ putStrLn $ showSDoc $ vcat $
1724 text "active language flags:" :
1725 [text (" -X" ++ str) | (str, f, _) <- DynFlags.xFlags, xopt f dflags]
1727 -- -----------------------------------------------------------------------------
1730 completeCmd, completeMacro, completeIdentifier, completeModule,
1732 completeHomeModule, completeSetOptions, completeShowOptions,
1733 completeHomeModuleOrFile, completeExpression
1734 :: CompletionFunc GHCi
1736 ghciCompleteWord :: CompletionFunc GHCi
1737 ghciCompleteWord line@(left,_) = case firstWord of
1738 ':':cmd | null rest -> completeCmd line
1740 completion <- lookupCompletion cmd
1742 "import" -> completeModule line
1743 _ -> completeExpression line
1745 (firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
1746 lookupCompletion ('!':_) = return completeFilename
1747 lookupCompletion c = do
1748 maybe_cmd <- liftIO $ lookupCommand' c
1750 Just (_,_,f) -> return f
1751 Nothing -> return completeFilename
1753 completeCmd = wrapCompleter " " $ \w -> do
1754 macros <- liftIO $ readIORef macros_ref
1755 let macro_names = map (':':) . map cmdName $ macros
1756 let command_names = map (':':) . map cmdName $ builtin_commands
1757 let{ candidates = case w of
1758 ':' : ':' : _ -> map (':':) command_names
1759 _ -> nub $ macro_names ++ command_names }
1760 return $ filter (w `isPrefixOf`) candidates
1762 completeMacro = wrapIdentCompleter $ \w -> do
1763 cmds <- liftIO $ readIORef macros_ref
1764 return (filter (w `isPrefixOf`) (map cmdName cmds))
1766 completeIdentifier = wrapIdentCompleter $ \w -> do
1767 rdrs <- GHC.getRdrNamesInScope
1768 return (filter (w `isPrefixOf`) (map (showSDoc.ppr) rdrs))
1770 completeModule = wrapIdentCompleter $ \w -> do
1771 dflags <- GHC.getSessionDynFlags
1772 let pkg_mods = allExposedModules dflags
1773 loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
1774 return $ filter (w `isPrefixOf`)
1775 $ map (showSDoc.ppr) $ loaded_mods ++ pkg_mods
1777 completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
1778 modules <- case m of
1780 (toplevs, exports) <- GHC.getContext
1781 return $ map GHC.moduleName (nub (map fst exports) ++ toplevs)
1783 dflags <- GHC.getSessionDynFlags
1784 let pkg_mods = allExposedModules dflags
1785 loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
1786 return $ loaded_mods ++ pkg_mods
1787 return $ filter (w `isPrefixOf`) $ map (showSDoc.ppr) modules
1789 completeHomeModule = wrapIdentCompleter listHomeModules
1791 listHomeModules :: String -> GHCi [String]
1792 listHomeModules w = do
1793 g <- GHC.getModuleGraph
1794 let home_mods = map GHC.ms_mod_name g
1795 return $ sort $ filter (w `isPrefixOf`)
1796 $ map (showSDoc.ppr) home_mods
1798 completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
1799 return (filter (w `isPrefixOf`) options)
1800 where options = "args":"prog":"prompt":"editor":"stop":flagList
1801 flagList = map head $ group $ sort allFlags
1803 completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
1804 return (filter (w `isPrefixOf`) options)
1805 where options = ["args", "prog", "prompt", "editor", "stop",
1806 "modules", "bindings", "linker", "breaks",
1807 "context", "packages", "languages"]
1809 completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
1810 $ unionComplete (fmap (map simpleCompletion) . listHomeModules)
1813 unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
1814 unionComplete f1 f2 line = do
1819 wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
1820 wrapCompleter breakChars fun = completeWord Nothing breakChars
1821 $ fmap (map simpleCompletion) . fmap sort . fun
1823 wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
1824 wrapIdentCompleter = wrapCompleter word_break_chars
1826 wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
1827 wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
1828 $ \rest -> fmap (map simpleCompletion) . fmap sort . fun (getModifier rest)
1830 getModifier = find (`elem` modifChars)
1832 allExposedModules :: DynFlags -> [ModuleName]
1833 allExposedModules dflags
1834 = concat (map exposedModules (filter exposed (eltsUFM pkg_db)))
1836 pkg_db = pkgIdMap (pkgState dflags)
1838 completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
1841 -- ---------------------------------------------------------------------------
1842 -- User code exception handling
1844 -- This is the exception handler for exceptions generated by the
1845 -- user's code and exceptions coming from children sessions;
1846 -- it normally just prints out the exception. The
1847 -- handler must be recursive, in case showing the exception causes
1848 -- more exceptions to be raised.
1850 -- Bugfix: if the user closed stdout or stderr, the flushing will fail,
1851 -- raising another exception. We therefore don't put the recursive
1852 -- handler arond the flushing operation, so if stderr is closed
1853 -- GHCi will just die gracefully rather than going into an infinite loop.
1854 handler :: SomeException -> GHCi Bool
1856 handler exception = do
1858 liftIO installSignalHandlers
1859 ghciHandle handler (showException exception >> return False)
1861 showException :: SomeException -> GHCi ()
1863 liftIO $ case fromException se of
1864 -- omit the location for CmdLineError:
1865 Just (CmdLineError s) -> putStrLn s
1867 Just ph@(PhaseFailed {}) -> putStrLn (showGhcException ph "")
1868 Just other_ghc_ex -> print other_ghc_ex
1870 case fromException se of
1871 Just UserInterrupt -> putStrLn "Interrupted."
1872 _ -> putStrLn ("*** Exception: " ++ show se)
1874 -----------------------------------------------------------------------------
1875 -- recursive exception handlers
1877 -- Don't forget to unblock async exceptions in the handler, or if we're
1878 -- in an exception loop (eg. let a = error a in a) the ^C exception
1879 -- may never be delivered. Thanks to Marcin for pointing out the bug.
1881 ghciHandle :: MonadException m => (SomeException -> m a) -> m a -> m a
1882 ghciHandle h m = Haskeline.catch m $ \e -> unblock (h e)
1884 ghciTry :: GHCi a -> GHCi (Either SomeException a)
1885 ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
1887 -- ----------------------------------------------------------------------------
1890 -- TODO: won't work if home dir is encoded.
1891 -- (changeDirectory may not work either in that case.)
1892 expandPath :: MonadIO m => String -> InputT m String
1893 expandPath path = do
1894 exp_path <- liftIO $ expandPathIO path
1895 enc <- fmap BS.unpack $ Encoding.encode exp_path
1898 expandPathIO :: String -> IO String
1900 case dropWhile isSpace path of
1902 tilde <- getHomeDirectory -- will fail if HOME not defined
1903 return (tilde ++ '/':d)
1907 wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
1908 wantInterpretedModule str = do
1909 modl <- lookupModule str
1910 dflags <- getDynFlags
1911 when (GHC.modulePackageId modl /= thisPackage dflags) $
1912 ghcError (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
1913 is_interpreted <- GHC.moduleIsInterpreted modl
1914 when (not is_interpreted) $
1915 ghcError (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
1918 wantNameFromInterpretedModule :: GHC.GhcMonad m
1919 => (Name -> SDoc -> m ())
1923 wantNameFromInterpretedModule noCanDo str and_then =
1924 handleSourceError GHC.printException $ do
1925 names <- GHC.parseName str
1929 let modl = ASSERT( isExternalName n ) GHC.nameModule n
1930 if not (GHC.isExternalName n)
1931 then noCanDo n $ ppr n <>
1932 text " is not defined in an interpreted module"
1934 is_interpreted <- GHC.moduleIsInterpreted modl
1935 if not is_interpreted
1936 then noCanDo n $ text "module " <> ppr modl <>
1937 text " is not interpreted"
1940 -- -----------------------------------------------------------------------------
1941 -- commands for debugger
1943 sprintCmd, printCmd, forceCmd :: String -> GHCi ()
1944 sprintCmd = pprintCommand False False
1945 printCmd = pprintCommand True False
1946 forceCmd = pprintCommand False True
1948 pprintCommand :: Bool -> Bool -> String -> GHCi ()
1949 pprintCommand bind force str = do
1950 pprintClosureCommand bind force str
1952 stepCmd :: String -> GHCi ()
1953 stepCmd [] = doContinue (const True) GHC.SingleStep
1954 stepCmd expression = runStmt expression GHC.SingleStep >> return ()
1956 stepLocalCmd :: String -> GHCi ()
1957 stepLocalCmd [] = do
1958 mb_span <- getCurrentBreakSpan
1960 Nothing -> stepCmd []
1962 Just mod <- getCurrentBreakModule
1963 current_toplevel_decl <- enclosingTickSpan mod loc
1964 doContinue (`isSubspanOf` current_toplevel_decl) GHC.SingleStep
1966 stepLocalCmd expression = stepCmd expression
1968 stepModuleCmd :: String -> GHCi ()
1969 stepModuleCmd [] = do
1970 mb_span <- getCurrentBreakSpan
1972 Nothing -> stepCmd []
1974 Just span <- getCurrentBreakSpan
1975 let f some_span = srcSpanFileName_maybe span == srcSpanFileName_maybe some_span
1976 doContinue f GHC.SingleStep
1978 stepModuleCmd expression = stepCmd expression
1980 -- | Returns the span of the largest tick containing the srcspan given
1981 enclosingTickSpan :: Module -> SrcSpan -> GHCi SrcSpan
1982 enclosingTickSpan mod src = do
1983 ticks <- getTickArray mod
1984 let line = srcSpanStartLine src
1985 ASSERT (inRange (bounds ticks) line) do
1986 let enclosing_spans = [ span | (_,span) <- ticks ! line
1987 , srcSpanEnd span >= srcSpanEnd src]
1988 return . head . sortBy leftmost_largest $ enclosing_spans
1990 traceCmd :: String -> GHCi ()
1991 traceCmd [] = doContinue (const True) GHC.RunAndLogSteps
1992 traceCmd expression = runStmt expression GHC.RunAndLogSteps >> return ()
1994 continueCmd :: String -> GHCi ()
1995 continueCmd = noArgs $ doContinue (const True) GHC.RunToCompletion
1997 -- doContinue :: SingleStep -> GHCi ()
1998 doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
1999 doContinue pred step = do
2000 runResult <- resume pred step
2001 _ <- afterRunStmt pred runResult
2004 abandonCmd :: String -> GHCi ()
2005 abandonCmd = noArgs $ do
2006 b <- GHC.abandon -- the prompt will change to indicate the new context
2007 when (not b) $ liftIO $ putStrLn "There is no computation running."
2009 deleteCmd :: String -> GHCi ()
2010 deleteCmd argLine = do
2011 deleteSwitch $ words argLine
2013 deleteSwitch :: [String] -> GHCi ()
2015 liftIO $ putStrLn "The delete command requires at least one argument."
2016 -- delete all break points
2017 deleteSwitch ("*":_rest) = discardActiveBreakPoints
2018 deleteSwitch idents = do
2019 mapM_ deleteOneBreak idents
2021 deleteOneBreak :: String -> GHCi ()
2023 | all isDigit str = deleteBreak (read str)
2024 | otherwise = return ()
2026 historyCmd :: String -> GHCi ()
2028 | null arg = history 20
2029 | all isDigit arg = history (read arg)
2030 | otherwise = liftIO $ putStrLn "Syntax: :history [num]"
2033 resumes <- GHC.getResumeContext
2035 [] -> liftIO $ putStrLn "Not stopped at a breakpoint"
2037 let hist = GHC.resumeHistory r
2038 (took,rest) = splitAt num hist
2040 [] -> liftIO $ putStrLn $
2041 "Empty history. Perhaps you forgot to use :trace?"
2043 spans <- mapM GHC.getHistorySpan took
2044 let nums = map (printf "-%-3d:") [(1::Int)..]
2045 names = map GHC.historyEnclosingDecls took
2046 printForUser (vcat(zipWith3
2047 (\x y z -> x <+> y <+> z)
2049 (map (bold . hcat . punctuate colon . map text) names)
2050 (map (parens . ppr) spans)))
2051 liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
2053 bold :: SDoc -> SDoc
2054 bold c | do_bold = text start_bold <> c <> text end_bold
2057 backCmd :: String -> GHCi ()
2058 backCmd = noArgs $ do
2059 (names, _, span) <- GHC.back
2060 printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr span
2061 printTypeOfNames names
2062 -- run the command set with ":set stop <cmd>"
2064 enqueueCommands [stop st]
2066 forwardCmd :: String -> GHCi ()
2067 forwardCmd = noArgs $ do
2068 (names, ix, span) <- GHC.forward
2069 printForUser $ (if (ix == 0)
2070 then ptext (sLit "Stopped at")
2071 else ptext (sLit "Logged breakpoint at")) <+> ppr span
2072 printTypeOfNames names
2073 -- run the command set with ":set stop <cmd>"
2075 enqueueCommands [stop st]
2077 -- handle the "break" command
2078 breakCmd :: String -> GHCi ()
2079 breakCmd argLine = do
2080 breakSwitch $ words argLine
2082 breakSwitch :: [String] -> GHCi ()
2084 liftIO $ putStrLn "The break command requires at least one argument."
2085 breakSwitch (arg1:rest)
2086 | looksLikeModuleName arg1 && not (null rest) = do
2087 mod <- wantInterpretedModule arg1
2088 breakByModule mod rest
2089 | all isDigit arg1 = do
2090 (toplevel, _) <- GHC.getContext
2092 (mod : _) -> breakByModuleLine mod (read arg1) rest
2094 liftIO $ putStrLn "Cannot find default module for breakpoint."
2095 liftIO $ putStrLn "Perhaps no modules are loaded for debugging?"
2096 | otherwise = do -- try parsing it as an identifier
2097 wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
2098 let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
2099 if GHC.isGoodSrcLoc loc
2100 then ASSERT( isExternalName name )
2101 findBreakAndSet (GHC.nameModule name) $
2102 findBreakByCoord (Just (GHC.srcLocFile loc))
2103 (GHC.srcLocLine loc,
2105 else noCanDo name $ text "can't find its location: " <> ppr loc
2107 noCanDo n why = printForUser $
2108 text "cannot set breakpoint on " <> ppr n <> text ": " <> why
2110 breakByModule :: Module -> [String] -> GHCi ()
2111 breakByModule mod (arg1:rest)
2112 | all isDigit arg1 = do -- looks like a line number
2113 breakByModuleLine mod (read arg1) rest
2117 breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
2118 breakByModuleLine mod line args
2119 | [] <- args = findBreakAndSet mod $ findBreakByLine line
2120 | [col] <- args, all isDigit col =
2121 findBreakAndSet mod $ findBreakByCoord Nothing (line, read col)
2122 | otherwise = breakSyntax
2125 breakSyntax = ghcError (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
2127 findBreakAndSet :: Module -> (TickArray -> Maybe (Int, SrcSpan)) -> GHCi ()
2128 findBreakAndSet mod lookupTickTree = do
2129 tickArray <- getTickArray mod
2130 (breakArray, _) <- getModBreak mod
2131 case lookupTickTree tickArray of
2132 Nothing -> liftIO $ putStrLn $ "No breakpoints found at that location."
2133 Just (tick, span) -> do
2134 success <- liftIO $ setBreakFlag True breakArray tick
2138 recordBreak $ BreakLocation
2145 text "Breakpoint " <> ppr nm <>
2147 then text " was already set at " <> ppr span
2148 else text " activated at " <> ppr span
2150 printForUser $ text "Breakpoint could not be activated at"
2153 -- When a line number is specified, the current policy for choosing
2154 -- the best breakpoint is this:
2155 -- - the leftmost complete subexpression on the specified line, or
2156 -- - the leftmost subexpression starting on the specified line, or
2157 -- - the rightmost subexpression enclosing the specified line
2159 findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,SrcSpan)
2160 findBreakByLine line arr
2161 | not (inRange (bounds arr) line) = Nothing
2163 listToMaybe (sortBy (leftmost_largest `on` snd) complete) `mplus`
2164 listToMaybe (sortBy (leftmost_smallest `on` snd) incomplete) `mplus`
2165 listToMaybe (sortBy (rightmost `on` snd) ticks)
2169 starts_here = [ tick | tick@(_,span) <- ticks,
2170 GHC.srcSpanStartLine span == line ]
2172 (complete,incomplete) = partition ends_here starts_here
2173 where ends_here (_,span) = GHC.srcSpanEndLine span == line
2175 findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
2176 -> Maybe (BreakIndex,SrcSpan)
2177 findBreakByCoord mb_file (line, col) arr
2178 | not (inRange (bounds arr) line) = Nothing
2180 listToMaybe (sortBy (rightmost `on` snd) contains ++
2181 sortBy (leftmost_smallest `on` snd) after_here)
2185 -- the ticks that span this coordinate
2186 contains = [ tick | tick@(_,span) <- ticks, span `spans` (line,col),
2187 is_correct_file span ]
2189 is_correct_file span
2190 | Just f <- mb_file = GHC.srcSpanFile span == f
2193 after_here = [ tick | tick@(_,span) <- ticks,
2194 GHC.srcSpanStartLine span == line,
2195 GHC.srcSpanStartCol span >= col ]
2197 -- For now, use ANSI bold on terminals that we know support it.
2198 -- Otherwise, we add a line of carets under the active expression instead.
2199 -- In particular, on Windows and when running the testsuite (which sets
2200 -- TERM to vt100 for other reasons) we get carets.
2201 -- We really ought to use a proper termcap/terminfo library.
2203 do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
2204 where mTerm = System.Environment.getEnv "TERM"
2205 `catchIO` \_ -> return "TERM not set"
2207 start_bold :: String
2208 start_bold = "\ESC[1m"
2210 end_bold = "\ESC[0m"
2212 listCmd :: String -> InputT GHCi ()
2213 listCmd c = listCmd' c
2215 listCmd' :: String -> InputT GHCi ()
2217 mb_span <- lift getCurrentBreakSpan
2220 printForUser $ text "Not stopped at a breakpoint; nothing to list"
2222 | GHC.isGoodSrcSpan span -> listAround span True
2224 do resumes <- GHC.getResumeContext
2226 [] -> panic "No resumes"
2228 do let traceIt = case GHC.resumeHistory r of
2229 [] -> text "rerunning with :trace,"
2231 doWhat = traceIt <+> text ":back then :list"
2232 printForUser (text "Unable to list source for" <+>
2234 $$ text "Try" <+> doWhat)
2235 listCmd' str = list2 (words str)
2237 list2 :: [String] -> InputT GHCi ()
2238 list2 [arg] | all isDigit arg = do
2239 (toplevel, _) <- GHC.getContext
2241 [] -> liftIO $ putStrLn "No module to list"
2242 (mod : _) -> listModuleLine mod (read arg)
2243 list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
2244 mod <- wantInterpretedModule arg1
2245 listModuleLine mod (read arg2)
2247 wantNameFromInterpretedModule noCanDo arg $ \name -> do
2248 let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
2249 if GHC.isGoodSrcLoc loc
2251 tickArray <- ASSERT( isExternalName name )
2252 lift $ getTickArray (GHC.nameModule name)
2253 let mb_span = findBreakByCoord (Just (GHC.srcLocFile loc))
2254 (GHC.srcLocLine loc, GHC.srcLocCol loc)
2257 Nothing -> listAround (GHC.srcLocSpan loc) False
2258 Just (_,span) -> listAround span False
2260 noCanDo name $ text "can't find its location: " <>
2263 noCanDo n why = printForUser $
2264 text "cannot list source code for " <> ppr n <> text ": " <> why
2266 liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
2268 listModuleLine :: Module -> Int -> InputT GHCi ()
2269 listModuleLine modl line = do
2270 graph <- GHC.getModuleGraph
2271 let this = filter ((== modl) . GHC.ms_mod) graph
2273 [] -> panic "listModuleLine"
2275 let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
2276 loc = GHC.mkSrcLoc (mkFastString (filename)) line 0
2277 listAround (GHC.srcLocSpan loc) False
2279 -- | list a section of a source file around a particular SrcSpan.
2280 -- If the highlight flag is True, also highlight the span using
2281 -- start_bold\/end_bold.
2283 -- GHC files are UTF-8, so we can implement this by:
2284 -- 1) read the file in as a BS and syntax highlight it as before
2285 -- 2) convert the BS to String using utf-string, and write it out.
2286 -- It would be better if we could convert directly between UTF-8 and the
2287 -- console encoding, of course.
2288 listAround :: MonadIO m => SrcSpan -> Bool -> InputT m ()
2289 listAround span do_highlight = do
2290 contents <- liftIO $ BS.readFile (unpackFS file)
2292 lines = BS.split '\n' contents
2293 these_lines = take (line2 - line1 + 1 + pad_before + pad_after) $
2294 drop (line1 - 1 - pad_before) $ lines
2295 fst_line = max 1 (line1 - pad_before)
2296 line_nos = [ fst_line .. ]
2298 highlighted | do_highlight = zipWith highlight line_nos these_lines
2299 | otherwise = [\p -> BS.concat[p,l] | l <- these_lines]
2301 bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
2302 prefixed = zipWith ($) highlighted bs_line_nos
2304 let output = BS.intercalate (BS.pack "\n") prefixed
2305 utf8Decoded <- liftIO $ BS.useAsCStringLen output
2306 $ \(p,n) -> utf8DecodeString (castPtr p) n
2307 liftIO $ putStrLn utf8Decoded
2309 file = GHC.srcSpanFile span
2310 line1 = GHC.srcSpanStartLine span
2311 col1 = GHC.srcSpanStartCol span - 1
2312 line2 = GHC.srcSpanEndLine span
2313 col2 = GHC.srcSpanEndCol span - 1
2315 pad_before | line1 == 1 = 0
2319 highlight | do_bold = highlight_bold
2320 | otherwise = highlight_carets
2322 highlight_bold no line prefix
2323 | no == line1 && no == line2
2324 = let (a,r) = BS.splitAt col1 line
2325 (b,c) = BS.splitAt (col2-col1) r
2327 BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
2329 = let (a,b) = BS.splitAt col1 line in
2330 BS.concat [prefix, a, BS.pack start_bold, b]
2332 = let (a,b) = BS.splitAt col2 line in
2333 BS.concat [prefix, a, BS.pack end_bold, b]
2334 | otherwise = BS.concat [prefix, line]
2336 highlight_carets no line prefix
2337 | no == line1 && no == line2
2338 = BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
2339 BS.replicate (col2-col1) '^']
2341 = BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
2344 = BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
2346 | otherwise = BS.concat [prefix, line]
2348 indent = BS.pack (" " ++ replicate (length (show no)) ' ')
2349 nl = BS.singleton '\n'
2351 -- --------------------------------------------------------------------------
2354 getTickArray :: Module -> GHCi TickArray
2355 getTickArray modl = do
2357 let arrmap = tickarrays st
2358 case lookupModuleEnv arrmap modl of
2359 Just arr -> return arr
2361 (_breakArray, ticks) <- getModBreak modl
2362 let arr = mkTickArray (assocs ticks)
2363 setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
2366 discardTickArrays :: GHCi ()
2367 discardTickArrays = do
2369 setGHCiState st{tickarrays = emptyModuleEnv}
2371 mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
2373 = accumArray (flip (:)) [] (1, max_line)
2374 [ (line, (nm,span)) | (nm,span) <- ticks,
2375 line <- srcSpanLines span ]
2377 max_line = foldr max 0 (map GHC.srcSpanEndLine (map snd ticks))
2378 srcSpanLines span = [ GHC.srcSpanStartLine span ..
2379 GHC.srcSpanEndLine span ]
2381 lookupModule :: GHC.GhcMonad m => String -> m Module
2382 lookupModule modName
2383 = GHC.lookupModule (GHC.mkModuleName modName) Nothing
2385 -- don't reset the counter back to zero?
2386 discardActiveBreakPoints :: GHCi ()
2387 discardActiveBreakPoints = do
2389 mapM_ (turnOffBreak.snd) (breaks st)
2390 setGHCiState $ st { breaks = [] }
2392 deleteBreak :: Int -> GHCi ()
2393 deleteBreak identity = do
2395 let oldLocations = breaks st
2396 (this,rest) = partition (\loc -> fst loc == identity) oldLocations
2398 then printForUser (text "Breakpoint" <+> ppr identity <+>
2399 text "does not exist")
2401 mapM_ (turnOffBreak.snd) this
2402 setGHCiState $ st { breaks = rest }
2404 turnOffBreak :: BreakLocation -> GHCi Bool
2405 turnOffBreak loc = do
2406 (arr, _) <- getModBreak (breakModule loc)
2407 liftIO $ setBreakFlag False arr (breakTick loc)
2409 getModBreak :: Module -> GHCi (GHC.BreakArray, Array Int SrcSpan)
2410 getModBreak mod = do
2411 Just mod_info <- GHC.getModuleInfo mod
2412 let modBreaks = GHC.modInfoModBreaks mod_info
2413 let array = GHC.modBreaks_flags modBreaks
2414 let ticks = GHC.modBreaks_locs modBreaks
2415 return (array, ticks)
2417 setBreakFlag :: Bool -> GHC.BreakArray -> Int -> IO Bool
2418 setBreakFlag toggle array index
2419 | toggle = GHC.setBreakOn array index
2420 | otherwise = GHC.setBreakOff array index