1 {-# OPTIONS -#include "Linker.h" #-}
2 -----------------------------------------------------------------------------
4 -- GHC Interactive User Interface
6 -- (c) The GHC Team 2005-2006
8 -----------------------------------------------------------------------------
10 module InteractiveUI ( interactiveUI, ghciWelcomeMsg ) where
12 #include "HsVersions.h"
20 import GHC ( Session, LoadHowMuch(..), Target(..), TargetId(..),
21 Module, ModuleName, TyThing(..), Phase,
22 BreakIndex, SrcSpan, Resume, SingleStep )
32 import HscTypes ( implicitTyThings )
33 import qualified RdrName ( getGRE_NameQualifier_maybes ) -- should this come via GHC?
34 import Outputable hiding (printForUser, printForUserPartWay)
35 import Module -- for ModuleEnv
39 -- Other random utilities
41 import BasicTypes hiding (isTopLevel)
42 import Panic hiding (showException)
48 import Maybes ( orElse )
52 #ifndef mingw32_HOST_OS
53 import System.Posix hiding (getEnv)
55 import GHC.ConsoleHandler ( flushConsole )
56 import qualified System.Win32
57 import System.FilePath
61 import Control.Concurrent ( yield ) -- Used in readline loop
62 import System.Console.Readline as Readline
67 import Control.Exception as Exception
68 -- import Control.Concurrent
70 import qualified Data.ByteString.Char8 as BS
74 import System.Environment
75 import System.Exit ( exitWith, ExitCode(..) )
76 import System.Directory
78 import System.IO.Error as IO
82 import Control.Monad as Monad
85 import Foreign.C ( withCStringLen )
86 import GHC.Exts ( unsafeCoerce# )
87 import GHC.IOBase ( IOErrorType(InvalidArgument) )
89 import Data.IORef ( IORef, readIORef, writeIORef )
92 import System.Posix.Internals ( setNonBlockingFD )
95 -----------------------------------------------------------------------------
97 ghciWelcomeMsg :: String
98 ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
99 ": http://www.haskell.org/ghc/ :? for help"
101 cmdName :: Command -> String
102 cmdName (n,_,_,_) = n
104 macros_ref :: IORef [Command]
105 GLOBAL_VAR(macros_ref, [], [Command])
107 builtin_commands :: [Command]
109 -- Hugs users are accustomed to :e, so make sure it doesn't overlap
110 ("?", keepGoing help, Nothing, completeNone),
111 ("add", keepGoingPaths addModule, Just filenameWordBreakChars, completeFilename),
112 ("abandon", keepGoing abandonCmd, Nothing, completeNone),
113 ("break", keepGoing breakCmd, Nothing, completeIdentifier),
114 ("back", keepGoing backCmd, Nothing, completeNone),
115 ("browse", keepGoing (browseCmd False), Nothing, completeModule),
116 ("browse!", keepGoing (browseCmd True), Nothing, completeModule),
117 ("cd", keepGoing changeDirectory, Just filenameWordBreakChars, completeFilename),
118 ("check", keepGoing checkModule, Nothing, completeHomeModule),
119 ("continue", keepGoing continueCmd, Nothing, completeNone),
120 ("cmd", keepGoing cmdCmd, Nothing, completeIdentifier),
121 ("ctags", keepGoing createCTagsFileCmd, Just filenameWordBreakChars, completeFilename),
122 ("def", keepGoing (defineMacro False), Nothing, completeIdentifier),
123 ("def!", keepGoing (defineMacro True), Nothing, completeIdentifier),
124 ("delete", keepGoing deleteCmd, Nothing, completeNone),
125 ("e", keepGoing editFile, Just filenameWordBreakChars, completeFilename),
126 ("edit", keepGoing editFile, Just filenameWordBreakChars, completeFilename),
127 ("etags", keepGoing createETagsFileCmd, Just filenameWordBreakChars, completeFilename),
128 ("force", keepGoing forceCmd, Nothing, completeIdentifier),
129 ("forward", keepGoing forwardCmd, Nothing, completeNone),
130 ("help", keepGoing help, Nothing, completeNone),
131 ("history", keepGoing historyCmd, Nothing, completeNone),
132 ("info", keepGoing info, Nothing, completeIdentifier),
133 ("kind", keepGoing kindOfType, Nothing, completeIdentifier),
134 ("load", keepGoingPaths loadModule_, Just filenameWordBreakChars, completeHomeModuleOrFile),
135 ("list", keepGoing listCmd, Nothing, completeNone),
136 ("module", keepGoing setContext, Nothing, completeModule),
137 ("main", keepGoing runMain, Nothing, completeIdentifier),
138 ("print", keepGoing printCmd, Nothing, completeIdentifier),
139 ("quit", quit, Nothing, completeNone),
140 ("reload", keepGoing reloadModule, Nothing, completeNone),
141 ("run", keepGoing runRun, Nothing, completeIdentifier),
142 ("set", keepGoing setCmd, Just flagWordBreakChars, completeSetOptions),
143 ("show", keepGoing showCmd, Nothing, completeNone),
144 ("sprint", keepGoing sprintCmd, Nothing, completeIdentifier),
145 ("step", keepGoing stepCmd, Nothing, completeIdentifier),
146 ("steplocal", keepGoing stepLocalCmd, Nothing, completeIdentifier),
147 ("stepmodule",keepGoing stepModuleCmd, Nothing, completeIdentifier),
148 ("type", keepGoing typeOfExpr, Nothing, completeIdentifier),
149 ("trace", keepGoing traceCmd, Nothing, completeIdentifier),
150 ("undef", keepGoing undefineMacro, Nothing, completeMacro),
151 ("unset", keepGoing unsetOptions, Just flagWordBreakChars, completeSetOptions)
155 -- We initialize readline (in the interactiveUI function) to use
156 -- word_break_chars as the default set of completion word break characters.
157 -- This can be overridden for a particular command (for example, filename
158 -- expansion shouldn't consider '/' to be a word break) by setting the third
159 -- entry in the Command tuple above.
161 -- NOTE: in order for us to override the default correctly, any custom entry
162 -- must be a SUBSET of word_break_chars.
164 word_break_chars :: String
165 word_break_chars = let symbols = "!#$%&*+/<=>?@\\^|-~"
166 specials = "(),;[]`{}"
168 in spaces ++ specials ++ symbols
171 flagWordBreakChars, filenameWordBreakChars :: String
172 flagWordBreakChars = " \t\n"
173 filenameWordBreakChars = " \t\n\\`@$><=;|&{(" -- bash defaults
176 keepGoing :: (String -> GHCi ()) -> (String -> GHCi Bool)
177 keepGoing a str = a str >> return False
179 keepGoingPaths :: ([FilePath] -> GHCi ()) -> (String -> GHCi Bool)
181 = do case toArgs str of
182 Left err -> io (hPutStrLn stderr err)
186 shortHelpText :: String
187 shortHelpText = "use :? for help.\n"
191 " Commands available from the prompt:\n" ++
193 " <statement> evaluate/run <statement>\n" ++
194 " : repeat last command\n" ++
195 " :{\\n ..lines.. \\n:}\\n multiline command\n" ++
196 " :add <filename> ... add module(s) to the current target set\n" ++
197 " :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
198 " (!: more details; *: all top-level names)\n" ++
199 " :cd <dir> change directory to <dir>\n" ++
200 " :cmd <expr> run the commands returned by <expr>::IO String\n" ++
201 " :ctags [<file>] create tags file for Vi (default: \"tags\")\n" ++
202 " :def <cmd> <expr> define a command :<cmd>\n" ++
203 " :edit <file> edit file\n" ++
204 " :edit edit last module\n" ++
205 " :etags [<file>] create tags file for Emacs (default: \"TAGS\")\n" ++
206 " :help, :? display this list of commands\n" ++
207 " :info [<name> ...] display information about the given names\n" ++
208 " :kind <type> show the kind of <type>\n" ++
209 " :load <filename> ... load module(s) and their dependents\n" ++
210 " :main [<arguments> ...] run the main function with the given arguments\n" ++
211 " :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
212 " :quit exit GHCi\n" ++
213 " :reload reload the current module set\n" ++
214 " :run function [<arguments> ...] run the function with the given arguments\n" ++
215 " :type <expr> show the type of <expr>\n" ++
216 " :undef <cmd> undefine user-defined command :<cmd>\n" ++
217 " :!<command> run the shell command <command>\n" ++
219 " -- Commands for debugging:\n" ++
221 " :abandon at a breakpoint, abandon current computation\n" ++
222 " :back go back in the history (after :trace)\n" ++
223 " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
224 " :break <name> set a breakpoint on the specified function\n" ++
225 " :continue resume after a breakpoint\n" ++
226 " :delete <number> delete the specified breakpoint\n" ++
227 " :delete * delete all breakpoints\n" ++
228 " :force <expr> print <expr>, forcing unevaluated parts\n" ++
229 " :forward go forward in the history (after :back)\n" ++
230 " :history [<n>] show the last <n> items in the history (after :trace)\n" ++
231 " :print [<name> ...] prints a value without forcing its computation\n" ++
232 " :sprint [<name> ...] simplifed version of :print\n" ++
233 " :step single-step after stopping at a breakpoint\n"++
234 " :step <expr> single-step into <expr>\n"++
235 " :steplocal single-step restricted to the current top level decl.\n"++
236 " :stepmodule single-step restricted to the current module\n"++
237 " :trace trace after stopping at a breakpoint\n"++
238 " :trace <expr> trace into <expr> (remembers breakpoints for :history)\n"++
241 " -- Commands for changing settings:\n" ++
243 " :set <option> ... set options\n" ++
244 " :set args <arg> ... set the arguments returned by System.getArgs\n" ++
245 " :set prog <progname> set the value returned by System.getProgName\n" ++
246 " :set prompt <prompt> set the prompt used in GHCi\n" ++
247 " :set editor <cmd> set the command used for :edit\n" ++
248 " :set stop <cmd> set the command to run when a breakpoint is hit\n" ++
249 " :unset <option> ... unset options\n" ++
251 " Options for ':set' and ':unset':\n" ++
253 " +r revert top-level expressions after each evaluation\n" ++
254 " +s print timing/memory stats after each evaluation\n" ++
255 " +t print type after evaluation\n" ++
256 " -<flags> most GHC command line flags can also be set here\n" ++
257 " (eg. -v2, -fglasgow-exts, etc.)\n" ++
258 " for GHCi-specific flags, see User's Guide,\n"++
259 " Flag reference, Interactive-mode options\n" ++
261 " -- Commands for displaying information:\n" ++
263 " :show bindings show the current bindings made at the prompt\n" ++
264 " :show breaks show the active breakpoints\n" ++
265 " :show context show the breakpoint context\n" ++
266 " :show modules show the currently loaded modules\n" ++
267 " :show packages show the currently active package flags\n" ++
268 " :show languages show the currently active language flags\n" ++
269 " :show <setting> show anything that can be set with :set (e.g. args)\n" ++
272 findEditor :: IO String
277 win <- System.Win32.getWindowsDirectory
278 return (win </> "notepad.exe")
283 interactiveUI :: Session -> [(FilePath, Maybe Phase)] -> Maybe String -> IO ()
284 interactiveUI session srcs maybe_expr = do
285 -- HACK! If we happen to get into an infinite loop (eg the user
286 -- types 'let x=x in x' at the prompt), then the thread will block
287 -- on a blackhole, and become unreachable during GC. The GC will
288 -- detect that it is unreachable and send it the NonTermination
289 -- exception. However, since the thread is unreachable, everything
290 -- it refers to might be finalized, including the standard Handles.
291 -- This sounds like a bug, but we don't have a good solution right
297 -- Initialise buffering for the *interpreted* I/O system
298 initInterpBuffering session
300 when (isNothing maybe_expr) $ do
301 -- Only for GHCi (not runghc and ghc -e):
303 -- Turn buffering off for the compiled program's stdout/stderr
305 -- Turn buffering off for GHCi's stdout
307 hSetBuffering stdout NoBuffering
308 -- We don't want the cmd line to buffer any input that might be
309 -- intended for the program, so unbuffer stdin.
310 hSetBuffering stdin NoBuffering
313 is_tty <- hIsTerminalDevice stdin
316 Readline.setAttemptedCompletionFunction (Just completeWord)
317 --Readline.parseAndBind "set show-all-if-ambiguous 1"
319 Readline.setBasicWordBreakCharacters word_break_chars
320 Readline.setCompleterWordBreakCharacters word_break_chars
321 Readline.setCompletionAppendCharacter Nothing
324 -- initial context is just the Prelude
325 prel_mod <- GHC.findModule session (GHC.mkModuleName "Prelude")
327 GHC.setContext session [] [prel_mod]
329 default_editor <- findEditor
331 startGHCi (runGHCi srcs maybe_expr)
332 GHCiState{ progname = "<interactive>",
336 editor = default_editor,
342 tickarrays = emptyModuleEnv,
343 last_command = Nothing,
345 remembered_ctx = Nothing
349 Readline.resetTerminal Nothing
354 runGHCi :: [(FilePath, Maybe Phase)] -> Maybe String -> GHCi ()
355 runGHCi paths maybe_expr = do
356 let read_dot_files = not opt_IgnoreDotGhci
358 when (read_dot_files) $ do
361 exists <- io (doesFileExist file)
363 dir_ok <- io (checkPerms ".")
364 file_ok <- io (checkPerms file)
365 when (dir_ok && file_ok) $ do
366 either_hdl <- io (IO.try (openFile "./.ghci" ReadMode))
369 Right hdl -> runCommands (fileLoop hdl False False)
371 when (read_dot_files) $ do
372 -- Read in $HOME/.ghci
373 either_dir <- io (IO.try getHomeDirectory)
377 cwd <- io (getCurrentDirectory)
378 when (dir /= cwd) $ do
379 let file = dir ++ "/.ghci"
380 ok <- io (checkPerms file)
382 either_hdl <- io (IO.try (openFile file ReadMode))
385 Right hdl -> runCommands (fileLoop hdl False False)
387 -- Perform a :load for files given on the GHCi command line
388 -- When in -e mode, if the load fails then we want to stop
389 -- immediately rather than going on to evaluate the expression.
390 when (not (null paths)) $ do
391 ok <- ghciHandle (\e -> do showException e; return Failed) $
393 when (isJust maybe_expr && failed ok) $
394 io (exitWith (ExitFailure 1))
396 -- if verbosity is greater than 0, or we are connected to a
397 -- terminal, display the prompt in the interactive loop.
398 is_tty <- io (hIsTerminalDevice stdin)
399 dflags <- getDynFlags
400 let show_prompt = verbosity dflags > 0 || is_tty
405 #if defined(mingw32_HOST_OS)
406 -- The win32 Console API mutates the first character of
407 -- type-ahead when reading from it in a non-buffered manner. Work
408 -- around this by flushing the input buffer of type-ahead characters,
409 -- but only if stdin is available.
410 flushed <- io (IO.try (GHC.ConsoleHandler.flushConsole stdin))
412 Left err | isDoesNotExistError err -> return ()
413 | otherwise -> io (ioError err)
414 Right () -> return ()
416 -- enter the interactive loop
417 interactiveLoop is_tty show_prompt
419 -- just evaluate the expression we were given
424 io $ do when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
427 interactiveLoop :: Bool -> Bool -> GHCi ()
428 interactiveLoop is_tty show_prompt =
429 -- Ignore ^C exceptions caught here
430 ghciHandleDyn (\e -> case e of
432 #if defined(mingw32_HOST_OS)
435 interactiveLoop is_tty show_prompt
436 _other -> return ()) $
438 ghciUnblock $ do -- unblock necessary if we recursed from the
439 -- exception handler above.
441 -- read commands from stdin
444 then runCommands readlineLoop
445 else runCommands (fileLoop stdin show_prompt is_tty)
447 runCommands (fileLoop stdin show_prompt is_tty)
451 -- NOTE: We only read .ghci files if they are owned by the current user,
452 -- and aren't world writable. Otherwise, we could be accidentally
453 -- running code planted by a malicious third party.
455 -- Furthermore, We only read ./.ghci if . is owned by the current user
456 -- and isn't writable by anyone else. I think this is sufficient: we
457 -- don't need to check .. and ../.. etc. because "." always refers to
458 -- the same directory while a process is running.
460 checkPerms :: String -> IO Bool
461 #ifdef mingw32_HOST_OS
466 Util.handle (\_ -> return False) $ do
467 st <- getFileStatus name
469 if fileOwner st /= me then do
470 putStrLn $ "WARNING: " ++ name ++ " is owned by someone else, IGNORING!"
473 let mode = fileMode st
474 if (groupWriteMode == (mode `intersectFileModes` groupWriteMode))
475 || (otherWriteMode == (mode `intersectFileModes` otherWriteMode))
477 putStrLn $ "*** WARNING: " ++ name ++
478 " is writable by someone else, IGNORING!"
483 fileLoop :: Handle -> Bool -> Bool -> GHCi (Maybe String)
484 fileLoop hdl show_prompt is_tty = do
485 when show_prompt $ do
488 l <- io (IO.try (hGetLine hdl))
490 Left e | isEOFError e -> return Nothing
491 | InvalidArgument <- etype -> return Nothing
492 | otherwise -> io (ioError e)
493 where etype = ioeGetErrorType e
494 -- treat InvalidArgument in the same way as EOF:
495 -- this can happen if the user closed stdin, or
496 -- perhaps did getContents which closes stdin at
499 str <- io $ consoleInputToUnicode is_tty l
502 #ifdef mingw32_HOST_OS
503 -- Convert the console input into Unicode according to the current code page.
504 -- The Windows console stores Unicode characters directly, so this is a
505 -- rather roundabout way of doing things... oh well.
506 -- See #782, #1483, #1649
507 consoleInputToUnicode :: Bool -> String -> IO String
508 consoleInputToUnicode is_tty str
510 cp <- System.Win32.getConsoleCP
511 System.Win32.stringToUnicode cp str
513 decodeStringAsUTF8 str
515 -- for Unix, assume the input is in UTF-8 and decode it to a Unicode String.
517 consoleInputToUnicode :: Bool -> String -> IO String
518 consoleInputToUnicode _is_tty str = decodeStringAsUTF8 str
521 decodeStringAsUTF8 :: String -> IO String
522 decodeStringAsUTF8 str =
523 withCStringLen str $ \(cstr,len) ->
524 utf8DecodeString (castPtr cstr :: Ptr Word8) len
526 mkPrompt :: GHCi String
528 session <- getSession
529 (toplevs,exports) <- io (GHC.getContext session)
530 resumes <- io $ GHC.getResumeContext session
531 -- st <- getGHCiState
537 let ix = GHC.resumeHistoryIx r
539 then return (brackets (ppr (GHC.resumeSpan r)) <> space)
541 let hist = GHC.resumeHistory r !! (ix-1)
542 span <- io$ GHC.getHistorySpan session hist
543 return (brackets (ppr (negate ix) <> char ':'
544 <+> ppr span) <> space)
546 dots | _:rs <- resumes, not (null rs) = text "... "
553 -- let (btoplevs, bexports) = fromMaybe ([],[]) (remembered_ctx st) in
554 -- hsep (map (\m -> text "!*" <> ppr (GHC.moduleName m)) btoplevs) <+>
555 -- hsep (map (\m -> char '!' <> ppr (GHC.moduleName m)) bexports) <+>
556 hsep (map (\m -> char '*' <> ppr (GHC.moduleName m)) toplevs) <+>
557 hsep (map (ppr . GHC.moduleName) exports)
559 deflt_prompt = dots <> context_bit <> modules_bit
561 f ('%':'s':xs) = deflt_prompt <> f xs
562 f ('%':'%':xs) = char '%' <> f xs
563 f (x:xs) = char x <> f xs
567 return (showSDoc (f (prompt st)))
571 readlineLoop :: GHCi (Maybe String)
574 saveSession -- for use by completion
576 l <- io (readline prompt `finally` setNonBlockingFD 0)
577 -- readline sometimes puts stdin into blocking mode,
578 -- so we need to put it back for the IO library
581 Nothing -> return Nothing
584 str <- io $ consoleInputToUnicode True l
588 queryQueue :: GHCi (Maybe String)
593 c:cs -> do setGHCiState st{ cmdqueue = cs }
596 runCommands :: GHCi (Maybe String) -> GHCi ()
597 runCommands getCmd = do
598 mb_cmd <- noSpace queryQueue
599 mb_cmd <- maybe (noSpace getCmd) (return . Just) mb_cmd
603 b <- ghciHandle handler (doCommand c)
604 if b then return () else runCommands getCmd
606 noSpace q = q >>= maybe (return Nothing)
607 (\c->case removeSpaces c of
609 ":{" -> multiLineCmd q
610 c -> return (Just c) )
614 setGHCiState st{ prompt = "%s| " }
615 mb_cmd <- collectCommand q ""
616 getGHCiState >>= \st->setGHCiState st{ prompt = p }
618 -- we can't use removeSpaces for the sublines here, so
619 -- multiline commands are somewhat more brittle against
620 -- fileformat errors (such as \r in dos input on unix),
621 -- we get rid of any extra spaces for the ":}" test;
622 -- we also avoid silent failure if ":}" is not found;
623 -- and since there is no (?) valid occurrence of \r (as
624 -- opposed to its String representation, "\r") inside a
625 -- ghci command, we replace any such with ' ' (argh:-(
626 collectCommand q c = q >>=
627 maybe (io (ioError collectError))
628 (\l->if removeSpaces l == ":}"
629 then return (Just $ removeSpaces c)
630 else collectCommand q (c++map normSpace l))
631 where normSpace '\r' = ' '
633 -- QUESTION: is userError the one to use here?
634 collectError = userError "unterminated multiline command :{ .. :}"
635 doCommand (':' : cmd) = specialCommand cmd
636 doCommand stmt = do timeIt $ runStmt stmt GHC.RunToCompletion
639 enqueueCommands :: [String] -> GHCi ()
640 enqueueCommands cmds = do
642 setGHCiState st{ cmdqueue = cmds ++ cmdqueue st }
645 -- This version is for the GHC command-line option -e. The only difference
646 -- from runCommand is that it catches the ExitException exception and
647 -- exits, rather than printing out the exception.
648 runCommandEval :: String -> GHCi Bool
649 runCommandEval c = ghciHandle handleEval (doCommand c)
651 handleEval (ExitException code) = io (exitWith code)
652 handleEval e = do handler e
653 io (exitWith (ExitFailure 1))
655 doCommand (':' : command) = specialCommand command
657 = do r <- runStmt stmt GHC.RunToCompletion
659 False -> io (exitWith (ExitFailure 1))
660 -- failure to run the command causes exit(1) for ghc -e.
663 runStmt :: String -> SingleStep -> GHCi Bool
665 | null (filter (not.isSpace) stmt) = return False
666 | ["import", mod] <- words stmt = keepGoing setContext ('+':mod)
668 = do st <- getGHCiState
669 session <- getSession
670 result <- io $ withProgName (progname st) $ withArgs (args st) $
671 GHC.runStmt session stmt step
672 afterRunStmt (const True) result
675 --afterRunStmt :: GHC.RunResult -> GHCi Bool
676 -- False <=> the statement failed to compile
677 afterRunStmt :: (SrcSpan -> Bool) -> GHC.RunResult -> GHCi Bool
678 afterRunStmt _ (GHC.RunException e) = throw e
679 afterRunStmt step_here run_result = do
680 session <- getSession
681 resumes <- io $ GHC.getResumeContext session
683 GHC.RunOk names -> do
684 show_types <- isOptionSet ShowType
685 when show_types $ printTypeOfNames session names
686 GHC.RunBreak _ names mb_info
687 | isNothing mb_info ||
688 step_here (GHC.resumeSpan $ head resumes) -> do
689 printForUser $ ptext SLIT("Stopped at") <+>
690 ppr (GHC.resumeSpan $ head resumes)
691 -- printTypeOfNames session names
692 let namesSorted = sortBy compareNames names
693 tythings <- catMaybes `liftM`
694 io (mapM (GHC.lookupName session) namesSorted)
695 docs <- io$ pprTypeAndContents session [id | AnId id <- tythings]
696 printForUserPartWay docs
697 maybe (return ()) runBreakCmd mb_info
698 -- run the command set with ":set stop <cmd>"
700 enqueueCommands [stop st]
702 | otherwise -> io(GHC.resume session GHC.SingleStep) >>=
703 afterRunStmt step_here >> return ()
707 io installSignalHandlers
708 b <- isOptionSet RevertCAFs
709 io (when b revertCAFs)
711 return (case run_result of GHC.RunOk _ -> True; _ -> False)
713 runBreakCmd :: GHC.BreakInfo -> GHCi ()
714 runBreakCmd info = do
715 let mod = GHC.breakInfo_module info
716 nm = GHC.breakInfo_number info
718 case [ loc | (_,loc) <- breaks st,
719 breakModule loc == mod, breakTick loc == nm ] of
721 loc:_ | null cmd -> return ()
722 | otherwise -> do enqueueCommands [cmd]; return ()
723 where cmd = onBreakCmd loc
725 printTypeOfNames :: Session -> [Name] -> GHCi ()
726 printTypeOfNames session names
727 = mapM_ (printTypeOfName session) $ sortBy compareNames names
729 compareNames :: Name -> Name -> Ordering
730 n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
731 where compareWith n = (getOccString n, getSrcSpan n)
733 printTypeOfName :: Session -> Name -> GHCi ()
734 printTypeOfName session n
735 = do maybe_tything <- io (GHC.lookupName session n)
736 case maybe_tything of
738 Just thing -> printTyThing thing
741 data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
743 specialCommand :: String -> GHCi Bool
744 specialCommand ('!':str) = shellEscape (dropWhile isSpace str)
745 specialCommand str = do
746 let (cmd,rest) = break isSpace str
747 maybe_cmd <- lookupCommand cmd
749 GotCommand (_,f,_,_) -> f (dropWhile isSpace rest)
751 do io $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
755 do io $ hPutStr stdout ("there is no last command to perform\n"
759 lookupCommand :: String -> GHCi (MaybeCommand)
760 lookupCommand "" = do
762 case last_command st of
763 Just c -> return $ GotCommand c
764 Nothing -> return NoLastCommand
765 lookupCommand str = do
766 mc <- io $ lookupCommand' str
768 setGHCiState st{ last_command = mc }
770 Just c -> GotCommand c
771 Nothing -> BadCommand
773 lookupCommand' :: String -> IO (Maybe Command)
774 lookupCommand' str = do
775 macros <- readIORef macros_ref
776 let cmds = builtin_commands ++ macros
777 -- look for exact match first, then the first prefix match
778 return $ case [ c | c <- cmds, str == cmdName c ] of
780 [] -> case [ c | c@(s,_,_,_) <- cmds, str `isPrefixOf` s ] of
784 getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
785 getCurrentBreakSpan = do
786 session <- getSession
787 resumes <- io $ GHC.getResumeContext session
791 let ix = GHC.resumeHistoryIx r
793 then return (Just (GHC.resumeSpan r))
795 let hist = GHC.resumeHistory r !! (ix-1)
796 span <- io $ GHC.getHistorySpan session hist
799 getCurrentBreakModule :: GHCi (Maybe Module)
800 getCurrentBreakModule = do
801 session <- getSession
802 resumes <- io $ GHC.getResumeContext session
806 let ix = GHC.resumeHistoryIx r
808 then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
810 let hist = GHC.resumeHistory r !! (ix-1)
811 return $ Just $ GHC.getHistoryModule hist
813 -----------------------------------------------------------------------------
816 noArgs :: GHCi () -> String -> GHCi ()
818 noArgs _ _ = io $ putStrLn "This command takes no arguments"
820 help :: String -> GHCi ()
821 help _ = io (putStr helpText)
823 info :: String -> GHCi ()
824 info "" = throwDyn (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
825 info s = do { let names = words s
826 ; session <- getSession
827 ; dflags <- getDynFlags
828 ; let pefas = dopt Opt_PrintExplicitForalls dflags
829 ; mapM_ (infoThing pefas session) names }
831 infoThing pefas session str = io $ do
832 names <- GHC.parseName session str
833 mb_stuffs <- mapM (GHC.getInfo session) names
834 let filtered = filterOutChildren (\(t,_f,_i) -> t) (catMaybes mb_stuffs)
835 unqual <- GHC.getPrintUnqual session
836 putStrLn (showSDocForUser unqual $
837 vcat (intersperse (text "") $
838 map (pprInfo pefas) filtered))
840 -- Filter out names whose parent is also there Good
841 -- example is '[]', which is both a type and data
842 -- constructor in the same type
843 filterOutChildren :: (a -> TyThing) -> [a] -> [a]
844 filterOutChildren get_thing xs
845 = [x | x <- xs, not (getName (get_thing x) `elemNameSet` implicits)]
847 implicits = mkNameSet [getName t | x <- xs, t <- implicitTyThings (get_thing x)]
849 pprInfo :: PrintExplicitForalls -> (TyThing, Fixity, [GHC.Instance]) -> SDoc
850 pprInfo pefas (thing, fixity, insts)
851 = pprTyThingInContextLoc pefas thing
852 $$ show_fixity fixity
853 $$ vcat (map GHC.pprInstance insts)
856 | fix == GHC.defaultFixity = empty
857 | otherwise = ppr fix <+> ppr (GHC.getName thing)
859 runMain :: String -> GHCi ()
860 runMain s = case toArgs s of
861 Left err -> io (hPutStrLn stderr err)
863 do dflags <- getDynFlags
864 case mainFunIs dflags of
865 Nothing -> doWithArgs args "main"
866 Just f -> doWithArgs args f
868 runRun :: String -> GHCi ()
869 runRun s = case toCmdArgs s of
870 Left err -> io (hPutStrLn stderr err)
871 Right (cmd, args) -> doWithArgs args cmd
873 doWithArgs :: [String] -> String -> GHCi ()
874 doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
875 show args ++ " (" ++ cmd ++ ")"]
877 addModule :: [FilePath] -> GHCi ()
879 io (revertCAFs) -- always revert CAFs on load/add.
880 files <- mapM expandPath files
881 targets <- mapM (\m -> io (GHC.guessTarget m Nothing)) files
882 session <- getSession
883 io (mapM_ (GHC.addTarget session) targets)
884 prev_context <- io $ GHC.getContext session
885 ok <- io (GHC.load session LoadAllTargets)
886 afterLoad ok session False prev_context
888 changeDirectory :: String -> GHCi ()
889 changeDirectory "" = do
890 -- :cd on its own changes to the user's home directory
891 either_dir <- io (IO.try getHomeDirectory)
894 Right dir -> changeDirectory dir
895 changeDirectory dir = do
896 session <- getSession
897 graph <- io (GHC.getModuleGraph session)
898 when (not (null graph)) $
899 io $ putStr "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed.\n"
900 prev_context <- io $ GHC.getContext session
901 io (GHC.setTargets session [])
902 io (GHC.load session LoadAllTargets)
903 setContextAfterLoad session prev_context []
904 io (GHC.workingDirectoryChanged session)
905 dir <- expandPath dir
906 io (setCurrentDirectory dir)
908 editFile :: String -> GHCi ()
910 do file <- if null str then chooseEditFile else return str
914 $ throwDyn (CmdLineError "editor not set, use :set editor")
915 io $ system (cmd ++ ' ':file)
918 -- The user didn't specify a file so we pick one for them.
919 -- Our strategy is to pick the first module that failed to load,
920 -- or otherwise the first target.
922 -- XXX: Can we figure out what happened if the depndecy analysis fails
923 -- (e.g., because the porgrammeer mistyped the name of a module)?
924 -- XXX: Can we figure out the location of an error to pass to the editor?
925 -- XXX: if we could figure out the list of errors that occured during the
926 -- last load/reaload, then we could start the editor focused on the first
928 chooseEditFile :: GHCi String
930 do session <- getSession
931 let hasFailed x = io $ fmap not $ GHC.isLoaded session $ GHC.ms_mod_name x
933 graph <- io (GHC.getModuleGraph session)
934 failed_graph <- filterM hasFailed graph
935 let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
937 x : _ -> GHC.ml_hs_file (GHC.ms_location x)
940 case pick (order failed_graph) of
941 Just file -> return file
943 do targets <- io (GHC.getTargets session)
944 case msum (map fromTarget targets) of
945 Just file -> return file
946 Nothing -> throwDyn (CmdLineError "No files to edit.")
948 where fromTarget (GHC.Target (GHC.TargetFile f _) _) = Just f
949 fromTarget _ = Nothing -- when would we get a module target?
951 defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
952 defineMacro overwrite s = do
953 let (macro_name, definition) = break isSpace s
954 macros <- io (readIORef macros_ref)
955 let defined = map cmdName macros
958 then io $ putStrLn "no macros defined"
959 else io $ putStr ("the following macros are defined:\n" ++
962 if (not overwrite && macro_name `elem` defined)
963 then throwDyn (CmdLineError
964 ("macro '" ++ macro_name ++ "' is already defined"))
967 let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
969 -- give the expression a type signature, so we can be sure we're getting
970 -- something of the right type.
971 let new_expr = '(' : definition ++ ") :: String -> IO String"
973 -- compile the expression
975 maybe_hv <- io (GHC.compileExpr cms new_expr)
978 Just hv -> io (writeIORef macros_ref --
979 (filtered ++ [(macro_name, runMacro hv, Nothing, completeNone)]))
981 runMacro :: GHC.HValue{-String -> IO String-} -> String -> GHCi Bool
983 str <- io ((unsafeCoerce# fun :: String -> IO String) s)
984 enqueueCommands (lines str)
987 undefineMacro :: String -> GHCi ()
988 undefineMacro str = mapM_ undef (words str)
989 where undef macro_name = do
990 cmds <- io (readIORef macros_ref)
991 if (macro_name `notElem` map cmdName cmds)
992 then throwDyn (CmdLineError
993 ("macro '" ++ macro_name ++ "' is not defined"))
995 io (writeIORef macros_ref (filter ((/= macro_name) . cmdName) cmds))
997 cmdCmd :: String -> GHCi ()
999 let expr = '(' : str ++ ") :: IO String"
1000 session <- getSession
1001 maybe_hv <- io (GHC.compileExpr session expr)
1003 Nothing -> return ()
1005 cmds <- io $ (unsafeCoerce# hv :: IO String)
1006 enqueueCommands (lines cmds)
1009 loadModule :: [(FilePath, Maybe Phase)] -> GHCi SuccessFlag
1010 loadModule fs = timeIt (loadModule' fs)
1012 loadModule_ :: [FilePath] -> GHCi ()
1013 loadModule_ fs = do loadModule (zip fs (repeat Nothing)); return ()
1015 loadModule' :: [(FilePath, Maybe Phase)] -> GHCi SuccessFlag
1016 loadModule' files = do
1017 session <- getSession
1018 prev_context <- io $ GHC.getContext session
1021 discardActiveBreakPoints
1022 io (GHC.setTargets session [])
1023 io (GHC.load session LoadAllTargets)
1026 let (filenames, phases) = unzip files
1027 exp_filenames <- mapM expandPath filenames
1028 let files' = zip exp_filenames phases
1029 targets <- io (mapM (uncurry GHC.guessTarget) files')
1031 -- NOTE: we used to do the dependency anal first, so that if it
1032 -- fails we didn't throw away the current set of modules. This would
1033 -- require some re-working of the GHC interface, so we'll leave it
1034 -- as a ToDo for now.
1036 io (GHC.setTargets session targets)
1037 doLoad session False prev_context LoadAllTargets
1039 checkModule :: String -> GHCi ()
1041 let modl = GHC.mkModuleName m
1042 session <- getSession
1043 prev_context <- io $ GHC.getContext session
1044 result <- io (GHC.checkModule session modl False)
1046 Nothing -> io $ putStrLn "Nothing"
1047 Just r -> io $ putStrLn (showSDoc (
1048 case GHC.checkedModuleInfo r of
1049 Just cm | Just scope <- GHC.modInfoTopLevelScope cm ->
1051 (local,global) = partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
1053 (text "global names: " <+> ppr global) $$
1054 (text "local names: " <+> ppr local)
1056 afterLoad (successIf (isJust result)) session False prev_context
1058 reloadModule :: String -> GHCi ()
1060 session <- getSession
1061 prev_context <- io $ GHC.getContext session
1062 doLoad session True prev_context $
1063 if null m then LoadAllTargets
1064 else LoadUpTo (GHC.mkModuleName m)
1067 doLoad :: Session -> Bool -> ([Module],[Module]) -> LoadHowMuch -> GHCi SuccessFlag
1068 doLoad session retain_context prev_context howmuch = do
1069 -- turn off breakpoints before we load: we can't turn them off later, because
1070 -- the ModBreaks will have gone away.
1071 discardActiveBreakPoints
1072 ok <- io (GHC.load session howmuch)
1073 afterLoad ok session retain_context prev_context
1076 afterLoad :: SuccessFlag -> Session -> Bool -> ([Module],[Module]) -> GHCi ()
1077 afterLoad ok session retain_context prev_context = do
1078 io (revertCAFs) -- always revert CAFs on load.
1080 loaded_mod_summaries <- getLoadedModules session
1081 let loaded_mods = map GHC.ms_mod loaded_mod_summaries
1082 loaded_mod_names = map GHC.moduleName loaded_mods
1083 modulesLoadedMsg ok loaded_mod_names
1086 if not retain_context
1088 setGHCiState st{ remembered_ctx = Nothing }
1089 setContextAfterLoad session prev_context loaded_mod_summaries
1091 -- figure out which modules we can keep in the context, which we
1092 -- have to put back, and which we have to remember because they
1093 -- are (temporarily) unavailable. See ghci.prog009, #1873, #1360
1094 let (as,bs) = prev_context
1095 as1 = filter isHomeModule as -- package modules are kept anyway
1096 bs1 = filter isHomeModule bs
1097 (as_ok, as_bad) = partition (`elem` loaded_mods) as1
1098 (bs_ok, bs_bad) = partition (`elem` loaded_mods) bs1
1099 (rem_as, rem_bs) = fromMaybe ([],[]) (remembered_ctx st)
1100 (rem_as_ok, rem_as_bad) = partition (`elem` loaded_mods) rem_as
1101 (rem_bs_ok, rem_bs_bad) = partition (`elem` loaded_mods) rem_bs
1102 as' = nub (as_ok++rem_as_ok)
1103 bs' = nub (bs_ok++rem_bs_ok)
1104 rem_as' = nub (rem_as_bad ++ as_bad)
1105 rem_bs' = nub (rem_bs_bad ++ bs_bad)
1107 -- Put back into the context any modules that we previously had
1108 -- to drop because they weren't available (rem_as_ok, rem_bs_ok).
1109 setContextKeepingPackageModules session prev_context (as',bs')
1111 -- If compilation failed, remember any modules that we are unable
1112 -- to load, so that we can put them back in the context in the future.
1114 Succeeded -> setGHCiState st{ remembered_ctx = Nothing }
1115 Failed -> setGHCiState st{ remembered_ctx = Just (rem_as',rem_bs') }
1119 setContextAfterLoad :: Session -> ([Module],[Module]) -> [GHC.ModSummary] -> GHCi ()
1120 setContextAfterLoad session prev [] = do
1121 prel_mod <- getPrelude
1122 setContextKeepingPackageModules session prev ([], [prel_mod])
1123 setContextAfterLoad session prev ms = do
1124 -- load a target if one is available, otherwise load the topmost module.
1125 targets <- io (GHC.getTargets session)
1126 case [ m | Just m <- map (findTarget ms) targets ] of
1128 let graph' = flattenSCCs (GHC.topSortModuleGraph True ms Nothing) in
1129 load_this (last graph')
1134 = case filter (`matches` t) ms of
1138 summary `matches` Target (TargetModule m) _
1139 = GHC.ms_mod_name summary == m
1140 summary `matches` Target (TargetFile f _) _
1141 | Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
1145 load_this summary | m <- GHC.ms_mod summary = do
1146 b <- io (GHC.moduleIsInterpreted session m)
1147 if b then setContextKeepingPackageModules session prev ([m], [])
1149 prel_mod <- getPrelude
1150 setContextKeepingPackageModules session prev ([],[prel_mod,m])
1152 -- | Keep any package modules (except Prelude) when changing the context.
1153 setContextKeepingPackageModules
1155 -> ([Module],[Module]) -- previous context
1156 -> ([Module],[Module]) -- new context
1158 setContextKeepingPackageModules session prev_context (as,bs) = do
1159 let (_,bs0) = prev_context
1160 prel_mod <- getPrelude
1161 let pkg_modules = filter (\p -> not (isHomeModule p) && p /= prel_mod) bs0
1162 let bs1 = if null as then nub (prel_mod : bs) else bs
1163 io $ GHC.setContext session as (nub (bs1 ++ pkg_modules))
1165 isHomeModule :: Module -> Bool
1166 isHomeModule mod = GHC.modulePackageId mod == mainPackageId
1168 modulesLoadedMsg :: SuccessFlag -> [ModuleName] -> GHCi ()
1169 modulesLoadedMsg ok mods = do
1170 dflags <- getDynFlags
1171 when (verbosity dflags > 0) $ do
1173 | null mods = text "none."
1174 | otherwise = hsep (
1175 punctuate comma (map ppr mods)) <> text "."
1178 io (putStrLn (showSDoc (text "Failed, modules loaded: " <> mod_commas)))
1180 io (putStrLn (showSDoc (text "Ok, modules loaded: " <> mod_commas)))
1183 typeOfExpr :: String -> GHCi ()
1185 = do cms <- getSession
1186 maybe_ty <- io (GHC.exprType cms str)
1188 Nothing -> return ()
1189 Just ty -> do dflags <- getDynFlags
1190 let pefas = dopt Opt_PrintExplicitForalls dflags
1191 printForUser $ text str <+> dcolon
1192 <+> pprTypeForUser pefas ty
1194 kindOfType :: String -> GHCi ()
1196 = do cms <- getSession
1197 maybe_ty <- io (GHC.typeKind cms str)
1199 Nothing -> return ()
1200 Just ty -> printForUser $ text str <+> dcolon <+> ppr ty
1202 quit :: String -> GHCi Bool
1203 quit _ = return True
1205 shellEscape :: String -> GHCi Bool
1206 shellEscape str = io (system str >> return False)
1208 -----------------------------------------------------------------------------
1209 -- Browsing a module's contents
1211 browseCmd :: Bool -> String -> GHCi ()
1214 ['*':s] | looksLikeModuleName s -> do
1215 m <- wantInterpretedModule s
1216 browseModule bang m False
1217 [s] | looksLikeModuleName s -> do
1219 browseModule bang m True
1222 (as,bs) <- io $ GHC.getContext s
1223 -- Guess which module the user wants to browse. Pick
1224 -- modules that are interpreted first. The most
1225 -- recently-added module occurs last, it seems.
1227 (as@(_:_), _) -> browseModule bang (last as) True
1228 ([], bs@(_:_)) -> browseModule bang (last bs) True
1229 ([], []) -> throwDyn (CmdLineError ":browse: no current module")
1230 _ -> throwDyn (CmdLineError "syntax: :browse <module>")
1232 -- without bang, show items in context of their parents and omit children
1233 -- with bang, show class methods and data constructors separately, and
1234 -- indicate import modules, to aid qualifying unqualified names
1235 -- with sorted, sort items alphabetically
1236 browseModule :: Bool -> Module -> Bool -> GHCi ()
1237 browseModule bang modl exports_only = do
1239 -- :browse! reports qualifiers wrt current context
1240 current_unqual <- io (GHC.getPrintUnqual s)
1241 -- Temporarily set the context to the module we're interested in,
1242 -- just so we can get an appropriate PrintUnqualified
1243 (as,bs) <- io (GHC.getContext s)
1244 prel_mod <- getPrelude
1245 io (if exports_only then GHC.setContext s [] [prel_mod,modl]
1246 else GHC.setContext s [modl] [])
1247 target_unqual <- io (GHC.getPrintUnqual s)
1248 io (GHC.setContext s as bs)
1250 let unqual = if bang then current_unqual else target_unqual
1252 mb_mod_info <- io $ GHC.getModuleInfo s modl
1254 Nothing -> throwDyn (CmdLineError ("unknown module: " ++
1255 GHC.moduleNameString (GHC.moduleName modl)))
1257 dflags <- getDynFlags
1259 | exports_only = GHC.modInfoExports mod_info
1260 | otherwise = GHC.modInfoTopLevelScope mod_info
1263 -- sort alphabetically name, but putting
1264 -- locally-defined identifiers first.
1265 -- We would like to improve this; see #1799.
1266 sorted_names = loc_sort local ++ occ_sort external
1268 (local,external) = partition ((==modl) . nameModule) names
1269 occ_sort = sortBy (compare `on` nameOccName)
1270 -- try to sort by src location. If the first name in
1271 -- our list has a good source location, then they all should.
1273 | n:_ <- names, isGoodSrcSpan (nameSrcSpan n)
1274 = sortBy (compare `on` nameSrcSpan) names
1278 mb_things <- io $ mapM (GHC.lookupName s) sorted_names
1279 let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
1281 rdr_env <- io $ GHC.getGRE s
1283 let pefas = dopt Opt_PrintExplicitForalls dflags
1284 things | bang = catMaybes mb_things
1285 | otherwise = filtered_things
1286 pretty | bang = pprTyThing
1287 | otherwise = pprTyThingInContext
1289 labels [] = text "-- not currently imported"
1290 labels l = text $ intercalate "\n" $ map qualifier l
1291 qualifier = maybe "-- defined locally"
1292 (("-- imported via "++) . intercalate ", "
1293 . map GHC.moduleNameString)
1294 importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
1295 modNames = map (importInfo . GHC.getName) things
1297 -- annotate groups of imports with their import modules
1298 -- the default ordering is somewhat arbitrary, so we group
1299 -- by header and sort groups; the names themselves should
1300 -- really come in order of source appearance.. (trac #1799)
1301 annotate mts = concatMap (\(m,ts)->labels m:ts)
1302 $ sortBy cmpQualifiers $ group mts
1303 where cmpQualifiers =
1304 compare `on` (map (fmap (map moduleNameFS)) . fst)
1306 group mts@((m,_):_) = (m,map snd g) : group ng
1307 where (g,ng) = partition ((==m).fst) mts
1309 let prettyThings = map (pretty pefas) things
1310 prettyThings' | bang = annotate $ zip modNames prettyThings
1311 | otherwise = prettyThings
1312 io (putStrLn $ showSDocForUser unqual (vcat prettyThings'))
1313 -- ToDo: modInfoInstances currently throws an exception for
1314 -- package modules. When it works, we can do this:
1315 -- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
1317 -----------------------------------------------------------------------------
1318 -- Setting the module context
1320 setContext :: String -> GHCi ()
1322 | all sensible mods = fn mods
1323 | otherwise = throwDyn (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
1325 (fn, mods) = case str of
1326 '+':stuff -> (addToContext, words stuff)
1327 '-':stuff -> (removeFromContext, words stuff)
1328 stuff -> (newContext, words stuff)
1330 sensible ('*':m) = looksLikeModuleName m
1331 sensible m = looksLikeModuleName m
1333 separate :: Session -> [String] -> [Module] -> [Module]
1334 -> GHCi ([Module],[Module])
1335 separate _ [] as bs = return (as,bs)
1336 separate session (('*':str):ms) as bs = do
1337 m <- wantInterpretedModule str
1338 separate session ms (m:as) bs
1339 separate session (str:ms) as bs = do
1340 m <- lookupModule str
1341 separate session ms as (m:bs)
1343 newContext :: [String] -> GHCi ()
1344 newContext strs = do
1346 (as,bs) <- separate s strs [] []
1347 prel_mod <- getPrelude
1348 let bs' = if null as && prel_mod `notElem` bs then prel_mod:bs else bs
1349 io $ GHC.setContext s as bs'
1352 addToContext :: [String] -> GHCi ()
1353 addToContext strs = do
1355 (as,bs) <- io $ GHC.getContext s
1357 (new_as,new_bs) <- separate s strs [] []
1359 let as_to_add = new_as \\ (as ++ bs)
1360 bs_to_add = new_bs \\ (as ++ bs)
1362 io $ GHC.setContext s (as ++ as_to_add) (bs ++ bs_to_add)
1365 removeFromContext :: [String] -> GHCi ()
1366 removeFromContext strs = do
1368 (as,bs) <- io $ GHC.getContext s
1370 (as_to_remove,bs_to_remove) <- separate s strs [] []
1372 let as' = as \\ (as_to_remove ++ bs_to_remove)
1373 bs' = bs \\ (as_to_remove ++ bs_to_remove)
1375 io $ GHC.setContext s as' bs'
1377 ----------------------------------------------------------------------------
1380 -- set options in the interpreter. Syntax is exactly the same as the
1381 -- ghc command line, except that certain options aren't available (-C,
1384 -- This is pretty fragile: most options won't work as expected. ToDo:
1385 -- figure out which ones & disallow them.
1387 setCmd :: String -> GHCi ()
1389 = do st <- getGHCiState
1390 let opts = options st
1391 io $ putStrLn (showSDoc (
1392 text "options currently set: " <>
1395 else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
1397 dflags <- getDynFlags
1398 io $ putStrLn (showSDoc (
1399 vcat (text "GHCi-specific dynamic flag settings:"
1400 :map (flagSetting dflags) ghciFlags)
1402 io $ putStrLn (showSDoc (
1403 vcat (text "other dynamic, non-language, flag settings:"
1404 :map (flagSetting dflags) nonLanguageDynFlags)
1406 where flagSetting dflags (str,f)
1407 | dopt f dflags = text " " <> text "-f" <> text str
1408 | otherwise = text " " <> text "-fno-" <> text str
1409 (ghciFlags,others) = partition (\(_,f)->f `elem` flags)
1411 nonLanguageDynFlags = filter (\(_,f)->not $ f `elem` map snd xFlags)
1413 flags = [Opt_PrintExplicitForalls
1414 ,Opt_PrintBindResult
1415 ,Opt_BreakOnException
1417 ,Opt_PrintEvldWithShow
1420 = case getCmd str of
1421 Right ("args", rest) ->
1423 Left err -> io (hPutStrLn stderr err)
1424 Right args -> setArgs args
1425 Right ("prog", rest) ->
1427 Right [prog] -> setProg prog
1428 _ -> io (hPutStrLn stderr "syntax: :set prog <progname>")
1429 Right ("prompt", rest) -> setPrompt $ dropWhile isSpace rest
1430 Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
1431 Right ("stop", rest) -> setStop $ dropWhile isSpace rest
1432 _ -> case toArgs str of
1433 Left err -> io (hPutStrLn stderr err)
1434 Right wds -> setOptions wds
1436 setArgs, setOptions :: [String] -> GHCi ()
1437 setProg, setEditor, setStop, setPrompt :: String -> GHCi ()
1441 setGHCiState st{ args = args }
1445 setGHCiState st{ progname = prog }
1449 setGHCiState st{ editor = cmd }
1451 setStop str@(c:_) | isDigit c
1452 = do let (nm_str,rest) = break (not.isDigit) str
1455 let old_breaks = breaks st
1456 if all ((/= nm) . fst) old_breaks
1457 then printForUser (text "Breakpoint" <+> ppr nm <+>
1458 text "does not exist")
1460 let new_breaks = map fn old_breaks
1461 fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
1462 | otherwise = (i,loc)
1463 setGHCiState st{ breaks = new_breaks }
1466 setGHCiState st{ stop = cmd }
1468 setPrompt value = do
1471 then io $ hPutStrLn stderr $ "syntax: :set prompt <prompt>, currently \"" ++ prompt st ++ "\""
1472 else setGHCiState st{ prompt = remQuotes value }
1474 remQuotes ('\"':xs) | not (null xs) && last xs == '\"' = init xs
1478 do -- first, deal with the GHCi opts (+s, +t, etc.)
1479 let (plus_opts, minus_opts) = partitionWith isPlus wds
1480 mapM_ setOpt plus_opts
1481 -- then, dynamic flags
1482 newDynFlags minus_opts
1484 newDynFlags :: [String] -> GHCi ()
1485 newDynFlags minus_opts = do
1486 dflags <- getDynFlags
1487 let pkg_flags = packageFlags dflags
1488 (dflags',leftovers) <- io $ GHC.parseDynamicFlags dflags minus_opts
1490 if (not (null leftovers))
1491 then throwDyn (CmdLineError ("unrecognised flags: " ++
1495 new_pkgs <- setDynFlags dflags'
1497 -- if the package flags changed, we should reset the context
1498 -- and link the new packages.
1499 dflags <- getDynFlags
1500 when (packageFlags dflags /= pkg_flags) $ do
1501 io $ hPutStrLn stderr "package flags have changed, ressetting and loading new packages..."
1502 session <- getSession
1503 io (GHC.setTargets session [])
1504 io (GHC.load session LoadAllTargets)
1505 io (linkPackages dflags new_pkgs)
1506 -- package flags changed, we can't re-use any of the old context
1507 setContextAfterLoad session ([],[]) []
1511 unsetOptions :: String -> GHCi ()
1513 = do -- first, deal with the GHCi opts (+s, +t, etc.)
1514 let opts = words str
1515 (minus_opts, rest1) = partition isMinus opts
1516 (plus_opts, rest2) = partitionWith isPlus rest1
1518 if (not (null rest2))
1519 then io (putStrLn ("unknown option: '" ++ head rest2 ++ "'"))
1522 mapM_ unsetOpt plus_opts
1524 let no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
1525 no_flag f = throwDyn (ProgramError ("don't know how to reverse " ++ f))
1527 no_flags <- mapM no_flag minus_opts
1528 newDynFlags no_flags
1530 isMinus :: String -> Bool
1531 isMinus ('-':_) = True
1534 isPlus :: String -> Either String String
1535 isPlus ('+':opt) = Left opt
1536 isPlus other = Right other
1538 setOpt, unsetOpt :: String -> GHCi ()
1541 = case strToGHCiOpt str of
1542 Nothing -> io (putStrLn ("unknown option: '" ++ str ++ "'"))
1543 Just o -> setOption o
1546 = case strToGHCiOpt str of
1547 Nothing -> io (putStrLn ("unknown option: '" ++ str ++ "'"))
1548 Just o -> unsetOption o
1550 strToGHCiOpt :: String -> (Maybe GHCiOption)
1551 strToGHCiOpt "s" = Just ShowTiming
1552 strToGHCiOpt "t" = Just ShowType
1553 strToGHCiOpt "r" = Just RevertCAFs
1554 strToGHCiOpt _ = Nothing
1556 optToStr :: GHCiOption -> String
1557 optToStr ShowTiming = "s"
1558 optToStr ShowType = "t"
1559 optToStr RevertCAFs = "r"
1561 -- ---------------------------------------------------------------------------
1564 showCmd :: String -> GHCi ()
1568 ["args"] -> io $ putStrLn (show (args st))
1569 ["prog"] -> io $ putStrLn (show (progname st))
1570 ["prompt"] -> io $ putStrLn (show (prompt st))
1571 ["editor"] -> io $ putStrLn (show (editor st))
1572 ["stop"] -> io $ putStrLn (show (stop st))
1573 ["modules" ] -> showModules
1574 ["bindings"] -> showBindings
1575 ["linker"] -> io showLinkerState
1576 ["breaks"] -> showBkptTable
1577 ["context"] -> showContext
1578 ["packages"] -> showPackages
1579 ["languages"] -> showLanguages
1580 _ -> throwDyn (CmdLineError "syntax: :show [args|prog|prompt|editor|stop|modules|bindings|breaks|context]")
1582 showModules :: GHCi ()
1584 session <- getSession
1585 loaded_mods <- getLoadedModules session
1586 -- we want *loaded* modules only, see #1734
1587 let show_one ms = do m <- io (GHC.showModule session ms); io (putStrLn m)
1588 mapM_ show_one loaded_mods
1590 getLoadedModules :: GHC.Session -> GHCi [GHC.ModSummary]
1591 getLoadedModules session = do
1592 graph <- io (GHC.getModuleGraph session)
1593 filterM (io . GHC.isLoaded session . GHC.ms_mod_name) graph
1595 showBindings :: GHCi ()
1598 bindings <- io (GHC.getBindings s)
1599 docs <- io$ pprTypeAndContents s
1600 [ id | AnId id <- sortBy compareTyThings bindings]
1601 printForUserPartWay docs
1603 compareTyThings :: TyThing -> TyThing -> Ordering
1604 t1 `compareTyThings` t2 = getName t1 `compareNames` getName t2
1606 printTyThing :: TyThing -> GHCi ()
1607 printTyThing tyth = do dflags <- getDynFlags
1608 let pefas = dopt Opt_PrintExplicitForalls dflags
1609 printForUser (pprTyThing pefas tyth)
1611 showBkptTable :: GHCi ()
1614 printForUser $ prettyLocations (breaks st)
1616 showContext :: GHCi ()
1618 session <- getSession
1619 resumes <- io $ GHC.getResumeContext session
1620 printForUser $ vcat (map pp_resume (reverse resumes))
1623 ptext SLIT("--> ") <> text (GHC.resumeStmt resume)
1624 $$ nest 2 (ptext SLIT("Stopped at") <+> ppr (GHC.resumeSpan resume))
1626 showPackages :: GHCi ()
1628 pkg_flags <- fmap packageFlags getDynFlags
1629 io $ putStrLn $ showSDoc $ vcat $
1630 text ("active package flags:"++if null pkg_flags then " none" else "")
1631 : map showFlag pkg_flags
1632 pkg_ids <- fmap (preloadPackages . pkgState) getDynFlags
1633 io $ putStrLn $ showSDoc $ vcat $
1634 text "packages currently loaded:"
1635 : map (nest 2 . text . packageIdString) pkg_ids
1636 where showFlag (ExposePackage p) = text $ " -package " ++ p
1637 showFlag (HidePackage p) = text $ " -hide-package " ++ p
1638 showFlag (IgnorePackage p) = text $ " -ignore-package " ++ p
1640 showLanguages :: GHCi ()
1642 dflags <- getDynFlags
1643 io $ putStrLn $ showSDoc $ vcat $
1644 text "active language flags:" :
1645 [text (" -X" ++ str) | (str,f) <- DynFlags.xFlags, dopt f dflags]
1647 -- -----------------------------------------------------------------------------
1650 completeNone :: String -> IO [String]
1651 completeNone _w = return []
1653 completeMacro, completeIdentifier, completeModule,
1654 completeHomeModule, completeSetOptions, completeFilename,
1655 completeHomeModuleOrFile
1656 :: String -> IO [String]
1659 completeWord :: String -> Int -> Int -> IO (Maybe (String, [String]))
1660 completeWord w start end = do
1661 line <- Readline.getLineBuffer
1662 let line_words = words (dropWhile isSpace line)
1664 ':':_ | all isSpace (take (start-1) line) -> wrapCompleter completeCmd w
1666 | ((':':c) : _) <- line_words -> do
1667 completionVars <- lookupCompletionVars c
1668 case completionVars of
1669 (Nothing,complete) -> wrapCompleter complete w
1670 (Just breakChars,complete)
1671 -> let (n,w') = selectWord
1672 (words' (`elem` breakChars) 0 line)
1673 complete' w = do rets <- complete w
1674 return (map (drop n) rets)
1675 in wrapCompleter complete' w'
1676 | ("import" : _) <- line_words ->
1677 wrapCompleter completeModule w
1679 --printf "complete %s, start = %d, end = %d\n" w start end
1680 wrapCompleter completeIdentifier w
1681 where words' _ _ [] = []
1682 words' isBreak n str = let (w,r) = break isBreak str
1683 (s,r') = span isBreak r
1684 in (n,w):words' isBreak (n+length w+length s) r'
1685 -- In a Haskell expression we want to parse 'a-b' as three words
1686 -- where a compiler flag (ie. -fno-monomorphism-restriction) should
1687 -- only be a single word.
1688 selectWord [] = (0,w)
1689 selectWord ((offset,x):xs)
1690 | offset+length x >= start = (start-offset,take (end-offset) x)
1691 | otherwise = selectWord xs
1693 lookupCompletionVars ('!':_) = return (Just filenameWordBreakChars,
1695 lookupCompletionVars c = do
1696 maybe_cmd <- lookupCommand' c
1698 Just (_,_,ws,f) -> return (ws,f)
1699 Nothing -> return (Just filenameWordBreakChars,
1703 completeCmd :: String -> IO [String]
1705 cmds <- readIORef macros_ref
1706 return (filter (w `isPrefixOf`) (map (':':)
1707 (map cmdName (builtin_commands ++ cmds))))
1709 completeMacro w = do
1710 cmds <- readIORef macros_ref
1711 return (filter (w `isPrefixOf`) (map cmdName cmds))
1713 completeIdentifier w = do
1715 rdrs <- GHC.getRdrNamesInScope s
1716 return (filter (w `isPrefixOf`) (map (showSDoc.ppr) rdrs))
1718 completeModule w = do
1720 dflags <- GHC.getSessionDynFlags s
1721 let pkg_mods = allExposedModules dflags
1722 return (filter (w `isPrefixOf`) (map (showSDoc.ppr) pkg_mods))
1724 completeHomeModule w = do
1726 g <- GHC.getModuleGraph s
1727 let home_mods = map GHC.ms_mod_name g
1728 return (filter (w `isPrefixOf`) (map (showSDoc.ppr) home_mods))
1730 completeSetOptions w = do
1731 return (filter (w `isPrefixOf`) options)
1732 where options = "args":"prog":allFlags
1734 completeFilename w = do
1735 ws <- Readline.filenameCompletionFunction w
1737 -- If we only found one result, and it's a directory,
1738 -- add a trailing slash.
1740 isDir <- expandPathIO file >>= doesDirectoryExist
1741 if isDir && last file /= '/'
1742 then return [file ++ "/"]
1747 completeHomeModuleOrFile = unionComplete completeHomeModule completeFilename
1749 unionComplete :: (String -> IO [String]) -> (String -> IO [String]) -> String -> IO [String]
1750 unionComplete f1 f2 w = do
1755 wrapCompleter :: (String -> IO [String]) -> String -> IO (Maybe (String,[String]))
1756 wrapCompleter fun w = do
1759 [] -> Readline.setAttemptedCompletionOver True >> return Nothing
1760 [x] -> -- Add a trailing space, unless it already has an appended slash.
1761 let appended = if last x == '/' then x else x ++ " "
1762 in return (Just (appended,[]))
1763 xs -> case getCommonPrefix xs of
1764 "" -> return (Just ("",xs))
1765 pref -> return (Just (pref,xs))
1767 getCommonPrefix :: [String] -> String
1768 getCommonPrefix [] = ""
1769 getCommonPrefix (s:ss) = foldl common s ss
1770 where common _s "" = ""
1772 common (c:cs) (d:ds)
1773 | c == d = c : common cs ds
1776 allExposedModules :: DynFlags -> [ModuleName]
1777 allExposedModules dflags
1778 = concat (map exposedModules (filter exposed (eltsUFM pkg_db)))
1780 pkg_db = pkgIdMap (pkgState dflags)
1782 completeMacro = completeNone
1783 completeIdentifier = completeNone
1784 completeModule = completeNone
1785 completeHomeModule = completeNone
1786 completeSetOptions = completeNone
1787 completeFilename = completeNone
1788 completeHomeModuleOrFile=completeNone
1791 -- ---------------------------------------------------------------------------
1792 -- User code exception handling
1794 -- This is the exception handler for exceptions generated by the
1795 -- user's code and exceptions coming from children sessions;
1796 -- it normally just prints out the exception. The
1797 -- handler must be recursive, in case showing the exception causes
1798 -- more exceptions to be raised.
1800 -- Bugfix: if the user closed stdout or stderr, the flushing will fail,
1801 -- raising another exception. We therefore don't put the recursive
1802 -- handler arond the flushing operation, so if stderr is closed
1803 -- GHCi will just die gracefully rather than going into an infinite loop.
1804 handler :: Exception -> GHCi Bool
1806 handler exception = do
1808 io installSignalHandlers
1809 ghciHandle handler (showException exception >> return False)
1811 showException :: Exception -> GHCi ()
1812 showException (DynException dyn) =
1813 case fromDynamic dyn of
1814 Nothing -> io (putStrLn ("*** Exception: (unknown)"))
1815 Just Interrupted -> io (putStrLn "Interrupted.")
1816 Just (CmdLineError s) -> io (putStrLn s) -- omit the location for CmdLineError
1817 Just ph@PhaseFailed{} -> io (putStrLn (showGhcException ph "")) -- ditto
1818 Just other_ghc_ex -> io (print other_ghc_ex)
1820 showException other_exception
1821 = io (putStrLn ("*** Exception: " ++ show other_exception))
1823 -----------------------------------------------------------------------------
1824 -- recursive exception handlers
1826 -- Don't forget to unblock async exceptions in the handler, or if we're
1827 -- in an exception loop (eg. let a = error a in a) the ^C exception
1828 -- may never be delivered. Thanks to Marcin for pointing out the bug.
1830 ghciHandle :: (Exception -> GHCi a) -> GHCi a -> GHCi a
1831 ghciHandle h (GHCi m) = GHCi $ \s ->
1832 Exception.catch (m s)
1833 (\e -> unGHCi (ghciUnblock (h e)) s)
1835 ghciUnblock :: GHCi a -> GHCi a
1836 ghciUnblock (GHCi a) = GHCi $ \s -> Exception.unblock (a s)
1839 -- ----------------------------------------------------------------------------
1842 expandPath :: String -> GHCi String
1843 expandPath path = io (expandPathIO path)
1845 expandPathIO :: String -> IO String
1847 case dropWhile isSpace path of
1849 tilde <- getHomeDirectory -- will fail if HOME not defined
1850 return (tilde ++ '/':d)
1854 wantInterpretedModule :: String -> GHCi Module
1855 wantInterpretedModule str = do
1856 session <- getSession
1857 modl <- lookupModule str
1858 is_interpreted <- io (GHC.moduleIsInterpreted session modl)
1859 when (not is_interpreted) $
1860 throwDyn (CmdLineError ("module '" ++ str ++ "' is not interpreted"))
1863 wantNameFromInterpretedModule :: (Name -> SDoc -> GHCi ()) -> String
1864 -> (Name -> GHCi ())
1866 wantNameFromInterpretedModule noCanDo str and_then = do
1867 session <- getSession
1868 names <- io $ GHC.parseName session str
1872 let modl = GHC.nameModule n
1873 if not (GHC.isExternalName n)
1874 then noCanDo n $ ppr n <>
1875 text " is not defined in an interpreted module"
1877 is_interpreted <- io (GHC.moduleIsInterpreted session modl)
1878 if not is_interpreted
1879 then noCanDo n $ text "module " <> ppr modl <>
1880 text " is not interpreted"
1883 -- -----------------------------------------------------------------------------
1884 -- commands for debugger
1886 sprintCmd, printCmd, forceCmd :: String -> GHCi ()
1887 sprintCmd = pprintCommand False False
1888 printCmd = pprintCommand True False
1889 forceCmd = pprintCommand False True
1891 pprintCommand :: Bool -> Bool -> String -> GHCi ()
1892 pprintCommand bind force str = do
1893 session <- getSession
1894 io $ pprintClosureCommand session bind force str
1896 stepCmd :: String -> GHCi ()
1897 stepCmd [] = doContinue (const True) GHC.SingleStep
1898 stepCmd expression = do runStmt expression GHC.SingleStep; return ()
1900 stepLocalCmd :: String -> GHCi ()
1901 stepLocalCmd [] = do
1902 mb_span <- getCurrentBreakSpan
1904 Nothing -> stepCmd []
1906 Just mod <- getCurrentBreakModule
1907 current_toplevel_decl <- enclosingTickSpan mod loc
1908 doContinue (`isSubspanOf` current_toplevel_decl) GHC.SingleStep
1910 stepLocalCmd expression = stepCmd expression
1912 stepModuleCmd :: String -> GHCi ()
1913 stepModuleCmd [] = do
1914 mb_span <- getCurrentBreakSpan
1916 Nothing -> stepCmd []
1918 Just span <- getCurrentBreakSpan
1919 let f some_span = optSrcSpanFileName span == optSrcSpanFileName some_span
1920 doContinue f GHC.SingleStep
1922 stepModuleCmd expression = stepCmd expression
1924 -- | Returns the span of the largest tick containing the srcspan given
1925 enclosingTickSpan :: Module -> SrcSpan -> GHCi SrcSpan
1926 enclosingTickSpan mod src = do
1927 ticks <- getTickArray mod
1928 let line = srcSpanStartLine src
1929 ASSERT (inRange (bounds ticks) line) do
1930 let enclosing_spans = [ span | (_,span) <- ticks ! line
1931 , srcSpanEnd span >= srcSpanEnd src]
1932 return . head . sortBy leftmost_largest $ enclosing_spans
1934 traceCmd :: String -> GHCi ()
1935 traceCmd [] = doContinue (const True) GHC.RunAndLogSteps
1936 traceCmd expression = do runStmt expression GHC.RunAndLogSteps; return ()
1938 continueCmd :: String -> GHCi ()
1939 continueCmd = noArgs $ doContinue (const True) GHC.RunToCompletion
1941 -- doContinue :: SingleStep -> GHCi ()
1942 doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
1943 doContinue pred step = do
1944 session <- getSession
1945 runResult <- io $ GHC.resume session step
1946 afterRunStmt pred runResult
1949 abandonCmd :: String -> GHCi ()
1950 abandonCmd = noArgs $ do
1952 b <- io $ GHC.abandon s -- the prompt will change to indicate the new context
1953 when (not b) $ io $ putStrLn "There is no computation running."
1956 deleteCmd :: String -> GHCi ()
1957 deleteCmd argLine = do
1958 deleteSwitch $ words argLine
1960 deleteSwitch :: [String] -> GHCi ()
1962 io $ putStrLn "The delete command requires at least one argument."
1963 -- delete all break points
1964 deleteSwitch ("*":_rest) = discardActiveBreakPoints
1965 deleteSwitch idents = do
1966 mapM_ deleteOneBreak idents
1968 deleteOneBreak :: String -> GHCi ()
1970 | all isDigit str = deleteBreak (read str)
1971 | otherwise = return ()
1973 historyCmd :: String -> GHCi ()
1975 | null arg = history 20
1976 | all isDigit arg = history (read arg)
1977 | otherwise = io $ putStrLn "Syntax: :history [num]"
1981 resumes <- io $ GHC.getResumeContext s
1983 [] -> io $ putStrLn "Not stopped at a breakpoint"
1985 let hist = GHC.resumeHistory r
1986 (took,rest) = splitAt num hist
1988 [] -> io $ putStrLn $
1989 "Empty history. Perhaps you forgot to use :trace?"
1991 spans <- mapM (io . GHC.getHistorySpan s) took
1992 let nums = map (printf "-%-3d:") [(1::Int)..]
1993 names = map GHC.historyEnclosingDecl took
1994 printForUser (vcat(zipWith3
1995 (\x y z -> x <+> y <+> z)
1997 (map (bold . ppr) names)
1998 (map (parens . ppr) spans)))
1999 io $ putStrLn $ if null rest then "<end of history>" else "..."
2001 bold :: SDoc -> SDoc
2002 bold c | do_bold = text start_bold <> c <> text end_bold
2005 backCmd :: String -> GHCi ()
2006 backCmd = noArgs $ do
2008 (names, _, span) <- io $ GHC.back s
2009 printForUser $ ptext SLIT("Logged breakpoint at") <+> ppr span
2010 printTypeOfNames s names
2011 -- run the command set with ":set stop <cmd>"
2013 enqueueCommands [stop st]
2015 forwardCmd :: String -> GHCi ()
2016 forwardCmd = noArgs $ do
2018 (names, ix, span) <- io $ GHC.forward s
2019 printForUser $ (if (ix == 0)
2020 then ptext SLIT("Stopped at")
2021 else ptext SLIT("Logged breakpoint at")) <+> ppr span
2022 printTypeOfNames s names
2023 -- run the command set with ":set stop <cmd>"
2025 enqueueCommands [stop st]
2027 -- handle the "break" command
2028 breakCmd :: String -> GHCi ()
2029 breakCmd argLine = do
2030 session <- getSession
2031 breakSwitch session $ words argLine
2033 breakSwitch :: Session -> [String] -> GHCi ()
2034 breakSwitch _session [] = do
2035 io $ putStrLn "The break command requires at least one argument."
2036 breakSwitch session (arg1:rest)
2037 | looksLikeModuleName arg1 = do
2038 mod <- wantInterpretedModule arg1
2039 breakByModule mod rest
2040 | all isDigit arg1 = do
2041 (toplevel, _) <- io $ GHC.getContext session
2043 (mod : _) -> breakByModuleLine mod (read arg1) rest
2045 io $ putStrLn "Cannot find default module for breakpoint."
2046 io $ putStrLn "Perhaps no modules are loaded for debugging?"
2047 | otherwise = do -- try parsing it as an identifier
2048 wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
2049 let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
2050 if GHC.isGoodSrcLoc loc
2051 then findBreakAndSet (GHC.nameModule name) $
2052 findBreakByCoord (Just (GHC.srcLocFile loc))
2053 (GHC.srcLocLine loc,
2055 else noCanDo name $ text "can't find its location: " <> ppr loc
2057 noCanDo n why = printForUser $
2058 text "cannot set breakpoint on " <> ppr n <> text ": " <> why
2060 breakByModule :: Module -> [String] -> GHCi ()
2061 breakByModule mod (arg1:rest)
2062 | all isDigit arg1 = do -- looks like a line number
2063 breakByModuleLine mod (read arg1) rest
2067 breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
2068 breakByModuleLine mod line args
2069 | [] <- args = findBreakAndSet mod $ findBreakByLine line
2070 | [col] <- args, all isDigit col =
2071 findBreakAndSet mod $ findBreakByCoord Nothing (line, read col)
2072 | otherwise = breakSyntax
2075 breakSyntax = throwDyn (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
2077 findBreakAndSet :: Module -> (TickArray -> Maybe (Int, SrcSpan)) -> GHCi ()
2078 findBreakAndSet mod lookupTickTree = do
2079 tickArray <- getTickArray mod
2080 (breakArray, _) <- getModBreak mod
2081 case lookupTickTree tickArray of
2082 Nothing -> io $ putStrLn $ "No breakpoints found at that location."
2083 Just (tick, span) -> do
2084 success <- io $ setBreakFlag True breakArray tick
2088 recordBreak $ BreakLocation
2095 text "Breakpoint " <> ppr nm <>
2097 then text " was already set at " <> ppr span
2098 else text " activated at " <> ppr span
2100 printForUser $ text "Breakpoint could not be activated at"
2103 -- When a line number is specified, the current policy for choosing
2104 -- the best breakpoint is this:
2105 -- - the leftmost complete subexpression on the specified line, or
2106 -- - the leftmost subexpression starting on the specified line, or
2107 -- - the rightmost subexpression enclosing the specified line
2109 findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,SrcSpan)
2110 findBreakByLine line arr
2111 | not (inRange (bounds arr) line) = Nothing
2113 listToMaybe (sortBy (leftmost_largest `on` snd) complete) `mplus`
2114 listToMaybe (sortBy (leftmost_smallest `on` snd) incomplete) `mplus`
2115 listToMaybe (sortBy (rightmost `on` snd) ticks)
2119 starts_here = [ tick | tick@(_,span) <- ticks,
2120 GHC.srcSpanStartLine span == line ]
2122 (complete,incomplete) = partition ends_here starts_here
2123 where ends_here (_,span) = GHC.srcSpanEndLine span == line
2125 findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
2126 -> Maybe (BreakIndex,SrcSpan)
2127 findBreakByCoord mb_file (line, col) arr
2128 | not (inRange (bounds arr) line) = Nothing
2130 listToMaybe (sortBy (rightmost `on` snd) contains ++
2131 sortBy (leftmost_smallest `on` snd) after_here)
2135 -- the ticks that span this coordinate
2136 contains = [ tick | tick@(_,span) <- ticks, span `spans` (line,col),
2137 is_correct_file span ]
2139 is_correct_file span
2140 | Just f <- mb_file = GHC.srcSpanFile span == f
2143 after_here = [ tick | tick@(_,span) <- ticks,
2144 GHC.srcSpanStartLine span == line,
2145 GHC.srcSpanStartCol span >= col ]
2147 -- For now, use ANSI bold on terminals that we know support it.
2148 -- Otherwise, we add a line of carets under the active expression instead.
2149 -- In particular, on Windows and when running the testsuite (which sets
2150 -- TERM to vt100 for other reasons) we get carets.
2151 -- We really ought to use a proper termcap/terminfo library.
2153 do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
2154 where mTerm = System.Environment.getEnv "TERM"
2155 `Exception.catch` \_ -> return "TERM not set"
2157 start_bold :: String
2158 start_bold = "\ESC[1m"
2160 end_bold = "\ESC[0m"
2162 listCmd :: String -> GHCi ()
2164 mb_span <- getCurrentBreakSpan
2167 printForUser $ text "Not stopped at a breakpoint; nothing to list"
2169 | GHC.isGoodSrcSpan span -> io $ listAround span True
2172 resumes <- io $ GHC.getResumeContext s
2174 [] -> panic "No resumes"
2176 do let traceIt = case GHC.resumeHistory r of
2177 [] -> text "rerunning with :trace,"
2179 doWhat = traceIt <+> text ":back then :list"
2180 printForUser (text "Unable to list source for" <+>
2182 $$ text "Try" <+> doWhat)
2183 listCmd str = list2 (words str)
2185 list2 :: [String] -> GHCi ()
2186 list2 [arg] | all isDigit arg = do
2187 session <- getSession
2188 (toplevel, _) <- io $ GHC.getContext session
2190 [] -> io $ putStrLn "No module to list"
2191 (mod : _) -> listModuleLine mod (read arg)
2192 list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
2193 mod <- wantInterpretedModule arg1
2194 listModuleLine mod (read arg2)
2196 wantNameFromInterpretedModule noCanDo arg $ \name -> do
2197 let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
2198 if GHC.isGoodSrcLoc loc
2200 tickArray <- getTickArray (GHC.nameModule name)
2201 let mb_span = findBreakByCoord (Just (GHC.srcLocFile loc))
2202 (GHC.srcLocLine loc, GHC.srcLocCol loc)
2205 Nothing -> io $ listAround (GHC.srcLocSpan loc) False
2206 Just (_,span) -> io $ listAround span False
2208 noCanDo name $ text "can't find its location: " <>
2211 noCanDo n why = printForUser $
2212 text "cannot list source code for " <> ppr n <> text ": " <> why
2214 io $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
2216 listModuleLine :: Module -> Int -> GHCi ()
2217 listModuleLine modl line = do
2218 session <- getSession
2219 graph <- io (GHC.getModuleGraph session)
2220 let this = filter ((== modl) . GHC.ms_mod) graph
2222 [] -> panic "listModuleLine"
2224 let filename = fromJust (ml_hs_file (GHC.ms_location summ))
2225 loc = GHC.mkSrcLoc (mkFastString (filename)) line 0
2226 io $ listAround (GHC.srcLocSpan loc) False
2228 -- | list a section of a source file around a particular SrcSpan.
2229 -- If the highlight flag is True, also highlight the span using
2230 -- start_bold/end_bold.
2231 listAround :: SrcSpan -> Bool -> IO ()
2232 listAround span do_highlight = do
2233 contents <- BS.readFile (unpackFS file)
2235 lines = BS.split '\n' contents
2236 these_lines = take (line2 - line1 + 1 + pad_before + pad_after) $
2237 drop (line1 - 1 - pad_before) $ lines
2238 fst_line = max 1 (line1 - pad_before)
2239 line_nos = [ fst_line .. ]
2241 highlighted | do_highlight = zipWith highlight line_nos these_lines
2242 | otherwise = [\p -> BS.concat[p,l] | l <- these_lines]
2244 bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
2245 prefixed = zipWith ($) highlighted bs_line_nos
2247 BS.putStrLn (BS.intercalate (BS.pack "\n") prefixed)
2249 file = GHC.srcSpanFile span
2250 line1 = GHC.srcSpanStartLine span
2251 col1 = GHC.srcSpanStartCol span
2252 line2 = GHC.srcSpanEndLine span
2253 col2 = GHC.srcSpanEndCol span
2255 pad_before | line1 == 1 = 0
2259 highlight | do_bold = highlight_bold
2260 | otherwise = highlight_carets
2262 highlight_bold no line prefix
2263 | no == line1 && no == line2
2264 = let (a,r) = BS.splitAt col1 line
2265 (b,c) = BS.splitAt (col2-col1) r
2267 BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
2269 = let (a,b) = BS.splitAt col1 line in
2270 BS.concat [prefix, a, BS.pack start_bold, b]
2272 = let (a,b) = BS.splitAt col2 line in
2273 BS.concat [prefix, a, BS.pack end_bold, b]
2274 | otherwise = BS.concat [prefix, line]
2276 highlight_carets no line prefix
2277 | no == line1 && no == line2
2278 = BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
2279 BS.replicate (col2-col1) '^']
2281 = BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
2284 = BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
2286 | otherwise = BS.concat [prefix, line]
2288 indent = BS.pack (" " ++ replicate (length (show no)) ' ')
2289 nl = BS.singleton '\n'
2291 -- --------------------------------------------------------------------------
2294 getTickArray :: Module -> GHCi TickArray
2295 getTickArray modl = do
2297 let arrmap = tickarrays st
2298 case lookupModuleEnv arrmap modl of
2299 Just arr -> return arr
2301 (_breakArray, ticks) <- getModBreak modl
2302 let arr = mkTickArray (assocs ticks)
2303 setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
2306 discardTickArrays :: GHCi ()
2307 discardTickArrays = do
2309 setGHCiState st{tickarrays = emptyModuleEnv}
2311 mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
2313 = accumArray (flip (:)) [] (1, max_line)
2314 [ (line, (nm,span)) | (nm,span) <- ticks,
2315 line <- srcSpanLines span ]
2317 max_line = foldr max 0 (map GHC.srcSpanEndLine (map snd ticks))
2318 srcSpanLines span = [ GHC.srcSpanStartLine span ..
2319 GHC.srcSpanEndLine span ]
2321 lookupModule :: String -> GHCi Module
2322 lookupModule modName
2323 = do session <- getSession
2324 io (GHC.findModule session (GHC.mkModuleName modName) Nothing)
2326 -- don't reset the counter back to zero?
2327 discardActiveBreakPoints :: GHCi ()
2328 discardActiveBreakPoints = do
2330 mapM (turnOffBreak.snd) (breaks st)
2331 setGHCiState $ st { breaks = [] }
2333 deleteBreak :: Int -> GHCi ()
2334 deleteBreak identity = do
2336 let oldLocations = breaks st
2337 (this,rest) = partition (\loc -> fst loc == identity) oldLocations
2339 then printForUser (text "Breakpoint" <+> ppr identity <+>
2340 text "does not exist")
2342 mapM (turnOffBreak.snd) this
2343 setGHCiState $ st { breaks = rest }
2345 turnOffBreak :: BreakLocation -> GHCi Bool
2346 turnOffBreak loc = do
2347 (arr, _) <- getModBreak (breakModule loc)
2348 io $ setBreakFlag False arr (breakTick loc)
2350 getModBreak :: Module -> GHCi (GHC.BreakArray, Array Int SrcSpan)
2351 getModBreak mod = do
2352 session <- getSession
2353 Just mod_info <- io $ GHC.getModuleInfo session mod
2354 let modBreaks = GHC.modInfoModBreaks mod_info
2355 let array = GHC.modBreaks_flags modBreaks
2356 let ticks = GHC.modBreaks_locs modBreaks
2357 return (array, ticks)
2359 setBreakFlag :: Bool -> GHC.BreakArray -> Int -> IO Bool
2360 setBreakFlag toggle array index
2361 | toggle = GHC.setBreakOn array index
2362 | otherwise = GHC.setBreakOff array index