Debian Codegraph @

src-bin-861/Clash/GHCi/UI.hs

raw
1 {-# OPTIONS_GHC -Wno-name-shadowing #-}
2 {-# LANGUAGE CPP #-}
3 {-# LANGUAGE LambdaCase #-}
4 {-# LANGUAGE MultiWayIf #-}
5 {-# LANGUAGE NondecreasingIndentation #-}
6 {-# LANGUAGE OverloadedStrings #-}
7 {-# LANGUAGE RecordWildCards #-}
8
9 {-# OPTIONS -fno-cse #-}
10 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
11
12 -----------------------------------------------------------------------------
13 --
14 -- GHC Interactive User Interface
15 --
16 -- (c) The GHC Team 2005-2006
17 --
18 -----------------------------------------------------------------------------
19
20 module Clash.GHCi.UI (
21 interactiveUI,
22 GhciSettings(..),
23 defaultGhciSettings,
24 ghciCommands,
25 ghciWelcomeMsg,
26 makeHDL
27 ) where
28
29 #include "HsVersions.h"
30
31 -- GHCi
32 import qualified Clash.GHCi.UI.Monad as GhciMonad ( args, runStmt, runDecls )
33 import Clash.GHCi.UI.Monad hiding ( args, runStmt, runDecls )
34 import Clash.GHCi.UI.Tags
35 import Clash.GHCi.UI.Info
36 import Debugger
37
38 -- The GHC interface
39 import GHCi
40 import GHCi.RemoteTypes
41 import GHCi.BreakArray
42 import DynFlags
43 import ErrUtils hiding (traceCmd)
44 import Finder
45 import GhcMonad ( modifySession )
46 import qualified GHC
47 import GHC ( LoadHowMuch(..), Target(..), TargetId(..), InteractiveImport(..),
48 TyThing(..), Phase, BreakIndex, Resume, SingleStep, Ghc,
49 GetDocsFailure(..),
50 getModuleGraph, handleSourceError )
51 import HsImpExp
52 import HsSyn
53 import HscTypes ( tyThingParent_maybe, handleFlagWarnings, getSafeMode, hsc_IC,
54 setInteractivePrintName, hsc_dflags, msObjFilePath )
55 import Module
56 import Name
57 import Packages ( trusted, getPackageDetails, getInstalledPackageDetails,
58 listVisibleModuleNames, pprFlag )
59 import IfaceSyn ( showToHeader )
60 import PprTyThing
61 import PrelNames
62 import RdrName ( getGRE_NameQualifier_maybes, getRdrName )
63 import SrcLoc
64 import qualified Lexer
65
66 import StringBuffer
67 import Outputable hiding ( printForUser, printForUserPartWay )
68
69 import DynamicLoading ( initializePlugins )
70
71 -- Other random utilities
72 import BasicTypes hiding ( isTopLevel )
73 import Digraph
74 import Encoding
75 import FastString
76 import Linker
77 import Maybes ( orElse, expectJust )
78 import NameSet
79 import Panic hiding ( showException )
80 import Util
81 import qualified GHC.LanguageExtensions as LangExt
82
83 -- Haskell Libraries
84 import System.Console.Haskeline as Haskeline
85
86 import Control.Applicative hiding (empty)
87 import Control.DeepSeq (deepseq)
88 import Control.Monad as Monad
89 import Control.Monad.IO.Class
90 import Control.Monad.Trans.Class
91 import Control.Monad.Trans.Except
92
93 import Data.Array
94 import qualified Data.ByteString.Char8 as BS
95 import Data.Char
96 import Data.Function
97 import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
98 import Data.List ( find, group, intercalate, intersperse, isPrefixOf, nub,
99 partition, sort, sortBy )
100 import Data.Proxy
101 import qualified Data.Set as S
102 import Data.Maybe
103 import Data.Map (Map)
104 import qualified Data.Map as M
105 import Data.Time.LocalTime ( getZonedTime )
106 import Data.Time.Format ( formatTime, defaultTimeLocale )
107 import Data.Version ( showVersion )
108 import Prelude hiding ((<>))
109
110 import Exception hiding (catch)
111 import Foreign hiding (void)
112 import GHC.Stack hiding (SrcLoc(..))
113
114 import System.Directory
115 import System.Environment
116 import System.Exit ( exitWith, ExitCode(..) )
117 import System.FilePath
118 import System.Info
119 import System.IO
120 import System.IO.Error
121 import System.IO.Unsafe ( unsafePerformIO )
122 import System.Process
123 import Text.Printf
124 import Text.Read ( readMaybe )
125 import Text.Read.Lex (isSymbolChar)
126
127 import Unsafe.Coerce
128
129 #if !defined(mingw32_HOST_OS)
130 import System.Posix hiding ( getEnv )
131 #else
132 import qualified System.Win32
133 #endif
134
135 import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
136 import GHC.IO.Handle ( hFlushAll )
137 import GHC.TopHandler ( topHandler )
138
139 import Clash.GHCi.Leak
140
141 -- clash additions
142 import Clash.Backend (Backend(initBackend, hdlKind, primDirs))
143 import Clash.Backend.SystemVerilog (SystemVerilogState)
144 import Clash.Backend.VHDL (VHDLState)
145 import Clash.Backend.Verilog (VerilogState)
146 import qualified Clash.Driver
147 import Clash.Driver.Bool (fromGhcOverridingBool)
148 import Clash.Driver.Types (ClashOpts(..), ClashEnv(..), ClashDesign(..))
149
150 import Clash.GHC.PartialEval
151 import Clash.GHC.Evaluator
152
153 import Clash.GHC.GenerateBindings
154 import Clash.GHC.NetlistTypes
155 import Clash.GHCi.Common
156 import Clash.Util (clashLibVersion, reportTimeDiff)
157 import qualified Data.Time.Clock as Clock
158 import qualified Paths_clash_ghc
159
160 -----------------------------------------------------------------------------
161
162 data GhciSettings = GhciSettings {
163 availableCommands :: [Command],
164 shortHelpText :: String,
165 fullHelpText :: String,
166 defPrompt :: PromptFunction,
167 defPromptCont :: PromptFunction
168 }
169
170 defaultGhciSettings :: IORef ClashOpts -> GhciSettings
171 defaultGhciSettings opts =
172 GhciSettings {
173 availableCommands = ghciCommands opts,
174 shortHelpText = defShortHelpText,
175 defPrompt = default_prompt,
176 defPromptCont = default_prompt_cont,
177 fullHelpText = defFullHelpText
178 }
179
180 ghciWelcomeMsg :: String
181 ghciWelcomeMsg = "Clashi, version " ++ Data.Version.showVersion Paths_clash_ghc.version ++
182 " (using clash-lib, version " ++ Data.Version.showVersion clashLibVersion ++
183 "):\nhttps://clash-lang.org/ :? for help"
184
185 ghciCommands :: IORef ClashOpts -> [Command]
186 ghciCommands opts = map mkCmd [
187 -- Hugs users are accustomed to :e, so make sure it doesn't overlap
188 ("?", keepGoing help, noCompletion),
189 ("add", keepGoingPaths addModule, completeFilename),
190 ("abandon", keepGoing abandonCmd, noCompletion),
191 ("break", keepGoing breakCmd, completeIdentifier),
192 ("back", keepGoing backCmd, noCompletion),
193 ("browse", keepGoing' (browseCmd False), completeModule),
194 ("browse!", keepGoing' (browseCmd True), completeModule),
195 ("cd", keepGoing' changeDirectory, completeFilename),
196 ("check", keepGoing' checkModule, completeHomeModule),
197 ("continue", keepGoing continueCmd, noCompletion),
198 ("cmd", keepGoing cmdCmd, completeExpression),
199 ("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
200 ("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
201 ("def", keepGoing (defineMacro False), completeExpression),
202 ("def!", keepGoing (defineMacro True), completeExpression),
203 ("delete", keepGoing deleteCmd, noCompletion),
204 ("doc", keepGoing' docCmd, completeIdentifier),
205 ("edit", keepGoing' editFile, completeFilename),
206 ("etags", keepGoing createETagsFileCmd, completeFilename),
207 ("force", keepGoing forceCmd, completeExpression),
208 ("forward", keepGoing forwardCmd, noCompletion),
209 ("help", keepGoing help, noCompletion),
210 ("history", keepGoing historyCmd, noCompletion),
211 ("info", keepGoing' (info False), completeIdentifier),
212 ("info!", keepGoing' (info True), completeIdentifier),
213 ("issafe", keepGoing' isSafeCmd, completeModule),
214 ("kind", keepGoing' (kindOfType False), completeIdentifier),
215 ("kind!", keepGoing' (kindOfType True), completeIdentifier),
216 ("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
217 ("load!", keepGoingPaths loadModuleDefer, completeHomeModuleOrFile),
218 ("list", keepGoing' listCmd, noCompletion),
219 ("module", keepGoing moduleCmd, completeSetModule),
220 ("main", keepGoing runMain, completeFilename),
221 ("print", keepGoing printCmd, completeExpression),
222 ("quit", quit, noCompletion),
223 ("reload", keepGoing' reloadModule, noCompletion),
224 ("reload!", keepGoing' reloadModuleDefer, noCompletion),
225 ("run", keepGoing runRun, completeFilename),
226 ("script", keepGoing' scriptCmd, completeFilename),
227 ("set", keepGoing setCmd, completeSetOptions),
228 ("seti", keepGoing setiCmd, completeSeti),
229 ("show", keepGoing showCmd, completeShowOptions),
230 ("showi", keepGoing showiCmd, completeShowiOptions),
231 ("sprint", keepGoing sprintCmd, completeExpression),
232 ("step", keepGoing stepCmd, completeIdentifier),
233 ("steplocal", keepGoing stepLocalCmd, completeIdentifier),
234 ("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
235 ("type", keepGoing' typeOfExpr, completeExpression),
236 ("trace", keepGoing traceCmd, completeExpression),
237 ("unadd", keepGoingPaths unAddModule, completeFilename),
238 ("undef", keepGoing undefineMacro, completeMacro),
239 ("unset", keepGoing unsetOptions, completeSetOptions),
240 ("where", keepGoing whereCmd, noCompletion),
241 ("vhdl", keepGoingPaths (makeVHDL opts), completeHomeModuleOrFile),
242 ("verilog", keepGoingPaths (makeVerilog opts), completeHomeModuleOrFile),
243 ("systemverilog", keepGoingPaths (makeSystemVerilog opts), completeHomeModuleOrFile)
244 ] ++ map mkCmdHidden [ -- hidden commands
245 ("all-types", keepGoing' allTypesCmd),
246 ("complete", keepGoing completeCmd),
247 ("loc-at", keepGoing' locAtCmd),
248 ("type-at", keepGoing' typeAtCmd),
249 ("uses", keepGoing' usesCmd)
250 ]
251 where
252 mkCmd (n,a,c) = Command { cmdName = n
253 , cmdAction = a
254 , cmdHidden = False
255 , cmdCompletionFunc = c
256 }
257
258 mkCmdHidden (n,a) = Command { cmdName = n
259 , cmdAction = a
260 , cmdHidden = True
261 , cmdCompletionFunc = noCompletion
262 }
263
264 -- We initialize readline (in the interactiveUI function) to use
265 -- word_break_chars as the default set of completion word break characters.
266 -- This can be overridden for a particular command (for example, filename
267 -- expansion shouldn't consider '/' to be a word break) by setting the third
268 -- entry in the Command tuple above.
269 --
270 -- NOTE: in order for us to override the default correctly, any custom entry
271 -- must be a SUBSET of word_break_chars.
272 word_break_chars :: String
273 word_break_chars = spaces ++ specials ++ symbols
274
275 symbols, specials, spaces :: String
276 symbols = "!#$%&*+/<=>?@\\^|-~"
277 specials = "(),;[]`{}"
278 spaces = " \t\n"
279
280 flagWordBreakChars :: String
281 flagWordBreakChars = " \t\n"
282
283
284 keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
285 keepGoing a str = keepGoing' (lift . a) str
286
287 keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
288 keepGoing' a str = a str >> return False
289
290 keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
291 keepGoingPaths a str
292 = do case toArgs str of
293 Left err -> liftIO $ hPutStrLn stderr err
294 Right args -> a args
295 return False
296
297 defShortHelpText :: String
298 defShortHelpText = "use :? for help.\n"
299
300 defFullHelpText :: String
301 defFullHelpText =
302 " Commands available from the prompt:\n" ++
303 "\n" ++
304 " <statement> evaluate/run <statement>\n" ++
305 " : repeat last command\n" ++
306 " :{\\n ..lines.. \\n:}\\n multiline command\n" ++
307 " :add [*]<module> ... add module(s) to the current target set\n" ++
308 " :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
309 " (!: more details; *: all top-level names)\n" ++
310 " :cd <dir> change directory to <dir>\n" ++
311 " :cmd <expr> run the commands returned by <expr>::IO String\n" ++
312 " :complete <dom> [<rng>] <s> list completions for partial input string\n" ++
313 " :ctags[!] [<file>] create tags file <file> for Vi (default: \"tags\")\n" ++
314 " (!: use regex instead of line number)\n" ++
315 " :def <cmd> <expr> define command :<cmd> (later defined command has\n" ++
316 " precedence, ::<cmd> is always a builtin command)\n" ++
317 " :doc <name> display docs for the given name (experimental)\n" ++
318 " :edit <file> edit file\n" ++
319 " :edit edit last module\n" ++
320 " :etags [<file>] create tags file <file> for Emacs (default: \"TAGS\")\n" ++
321 " :help, :? display this list of commands\n" ++
322 " :info[!] [<name> ...] display information about the given names\n" ++
323 " (!: do not filter instances)\n" ++
324 " :issafe [<mod>] display safe haskell information of module <mod>\n" ++
325 " :kind[!] <type> show the kind of <type>\n" ++
326 " (!: also print the normalised type)\n" ++
327 " :load[!] [*]<module> ... load module(s) and their dependents\n" ++
328 " (!: defer type errors)\n" ++
329 " :main [<arguments> ...] run the main function with the given arguments\n" ++
330 " :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
331 " :quit exit GHCi\n" ++
332 " :reload[!] reload the current module set\n" ++
333 " (!: defer type errors)\n" ++
334 " :run function [<arguments> ...] run the function with the given arguments\n" ++
335 " :script <file> run the script <file>\n" ++
336 " :type <expr> show the type of <expr>\n" ++
337 " :type +d <expr> show the type of <expr>, defaulting type variables\n" ++
338 " :type +v <expr> show the type of <expr>, with its specified tyvars\n" ++
339 " :unadd <module> ... remove module(s) from the current target set\n" ++
340 " :undef <cmd> undefine user-defined command :<cmd>\n" ++
341 " :!<command> run the shell command <command>\n" ++
342 " :vhdl synthesize currently loaded module to vhdl\n" ++
343 " :vhdl [<module>] synthesize specified modules/files to vhdl\n" ++
344 " :verilog synthesize currently loaded module to verilog\n" ++
345 " :verilog [<module>] synthesize specified modules/files to verilog\n" ++
346 " :systemverilog synthesize currently loaded module to systemverilog\n" ++
347 " :systemverilog [<module>] synthesize specified modules/files to systemverilog\n" ++
348 "\n" ++
349 " -- Commands for debugging:\n" ++
350 "\n" ++
351 " :abandon at a breakpoint, abandon current computation\n" ++
352 " :back [<n>] go back in the history N steps (after :trace)\n" ++
353 " :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
354 " :break <name> set a breakpoint on the specified function\n" ++
355 " :continue resume after a breakpoint\n" ++
356 " :delete <number> delete the specified breakpoint\n" ++
357 " :delete * delete all breakpoints\n" ++
358 " :force <expr> print <expr>, forcing unevaluated parts\n" ++
359 " :forward [<n>] go forward in the history N step s(after :back)\n" ++
360 " :history [<n>] after :trace, show the execution history\n" ++
361 " :list show the source code around current breakpoint\n" ++
362 " :list <identifier> show the source code for <identifier>\n" ++
363 " :list [<module>] <line> show the source code around line number <line>\n" ++
364 " :print [<name> ...] show a value without forcing its computation\n" ++
365 " :sprint [<name> ...] simplified version of :print\n" ++
366 " :step single-step after stopping at a breakpoint\n"++
367 " :step <expr> single-step into <expr>\n"++
368 " :steplocal single-step within the current top-level binding\n"++
369 " :stepmodule single-step restricted to the current module\n"++
370 " :trace trace after stopping at a breakpoint\n"++
371 " :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
372
373 "\n" ++
374 " -- Commands for changing settings:\n" ++
375 "\n" ++
376 " :set <option> ... set options\n" ++
377 " :seti <option> ... set options for interactive evaluation only\n" ++
378 " :set args <arg> ... set the arguments returned by System.getArgs\n" ++
379 " :set prog <progname> set the value returned by System.getProgName\n" ++
380 " :set prompt <prompt> set the prompt used in GHCi\n" ++
381 " :set prompt-cont <prompt> set the continuation prompt used in GHCi\n" ++
382 " :set prompt-function <expr> set the function to handle the prompt\n" ++
383 " :set prompt-cont-function <expr>" ++
384 "set the function to handle the continuation prompt\n" ++
385 " :set editor <cmd> set the command used for :edit\n" ++
386 " :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
387 " :unset <option> ... unset options\n" ++
388 "\n" ++
389 " Options for ':set' and ':unset':\n" ++
390 "\n" ++
391 " +m allow multiline commands\n" ++
392 " +r revert top-level expressions after each evaluation\n" ++
393 " +s print timing/memory stats after each evaluation\n" ++
394 " +t print type after evaluation\n" ++
395 " +c collect type/location info after loading modules\n" ++
396 " -<flags> most GHC command line flags can also be set here\n" ++
397 " (eg. -v2, -XFlexibleInstances, etc.)\n" ++
398 " for GHCi-specific flags, see User's Guide,\n"++
399 " Flag reference, Interactive-mode options\n" ++
400 "\n" ++
401 " -- Commands for displaying information:\n" ++
402 "\n" ++
403 " :show bindings show the current bindings made at the prompt\n" ++
404 " :show breaks show the active breakpoints\n" ++
405 " :show context show the breakpoint context\n" ++
406 " :show imports show the current imports\n" ++
407 " :show linker show current linker state\n" ++
408 " :show modules show the currently loaded modules\n" ++
409 " :show packages show the currently active package flags\n" ++
410 " :show paths show the currently active search paths\n" ++
411 " :show language show the currently active language flags\n" ++
412 " :show targets show the current set of targets\n" ++
413 " :show <setting> show value of <setting>, which is one of\n" ++
414 " [args, prog, editor, stop]\n" ++
415 " :showi language show language flags for interactive evaluation\n" ++
416 "\n"
417
418 findEditor :: IO String
419 findEditor = do
420 getEnv "EDITOR"
421 `catchIO` \_ -> do
422 #if defined(mingw32_HOST_OS)
423 win <- System.Win32.getWindowsDirectory
424 return (win </> "notepad.exe")
425 #else
426 return ""
427 #endif
428
429 default_progname, default_stop :: String
430 default_progname = "<interactive>"
431 default_stop = ""
432
433 default_prompt, default_prompt_cont :: PromptFunction
434 default_prompt = generatePromptFunctionFromString "%s> "
435 default_prompt_cont = generatePromptFunctionFromString "%s| "
436
437 default_args :: [String]
438 default_args = []
439
440 interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
441 -> Ghc ()
442 interactiveUI config srcs maybe_exprs = do
443 -- HACK! If we happen to get into an infinite loop (eg the user
444 -- types 'let x=x in x' at the prompt), then the thread will block
445 -- on a blackhole, and become unreachable during GC. The GC will
446 -- detect that it is unreachable and send it the NonTermination
447 -- exception. However, since the thread is unreachable, everything
448 -- it refers to might be finalized, including the standard Handles.
449 -- This sounds like a bug, but we don't have a good solution right
450 -- now.
451 _ <- liftIO $ newStablePtr stdin
452 _ <- liftIO $ newStablePtr stdout
453 _ <- liftIO $ newStablePtr stderr
454
455 -- Initialise buffering for the *interpreted* I/O system
456 (nobuffering, flush) <- initInterpBuffering
457
458 -- The initial set of DynFlags used for interactive evaluation is the same
459 -- as the global DynFlags, plus -XExtendedDefaultRules and
460 -- -XNoMonomorphismRestriction.
461 dflags <- getDynFlags
462 let dflags' = (`xopt_set` LangExt.ExtendedDefaultRules)
463 . (`xopt_unset` LangExt.MonomorphismRestriction)
464 $ dflags
465 GHC.setInteractiveDynFlags dflags'
466
467 lastErrLocationsRef <- liftIO $ newIORef []
468 progDynFlags <- GHC.getProgramDynFlags
469 _ <- GHC.setProgramDynFlags $
470 progDynFlags { log_action = ghciLogAction lastErrLocationsRef }
471
472 when (isNothing maybe_exprs) $ do
473 -- Only for GHCi (not runghc and ghc -e):
474
475 -- Turn buffering off for the compiled program's stdout/stderr
476 turnOffBuffering_ nobuffering
477 -- Turn buffering off for GHCi's stdout
478 liftIO $ hFlush stdout
479 liftIO $ hSetBuffering stdout NoBuffering
480 -- We don't want the cmd line to buffer any input that might be
481 -- intended for the program, so unbuffer stdin.
482 liftIO $ hSetBuffering stdin NoBuffering
483 liftIO $ hSetBuffering stderr NoBuffering
484 #if defined(mingw32_HOST_OS)
485 -- On Unix, stdin will use the locale encoding. The IO library
486 -- doesn't do this on Windows (yet), so for now we use UTF-8,
487 -- for consistency with GHC 6.10 and to make the tests work.
488 liftIO $ hSetEncoding stdin utf8
489 #endif
490
491 default_editor <- liftIO $ findEditor
492 eval_wrapper <- mkEvalWrapper default_progname default_args
493 let prelude_import = simpleImportDecl preludeModuleName
494 startGHCi (runGHCi srcs maybe_exprs)
495 GHCiState{ progname = default_progname,
496 args = default_args,
497 evalWrapper = eval_wrapper,
498 prompt = default_prompt,
499 prompt_cont = default_prompt_cont,
500 stop = default_stop,
501 editor = default_editor,
502 options = [],
503 -- We initialize line number as 0, not 1, because we use
504 -- current line number while reporting errors which is
505 -- incremented after reading a line.
506 line_number = 0,
507 break_ctr = 0,
508 breaks = [],
509 tickarrays = emptyModuleEnv,
510 ghci_commands = availableCommands config,
511 ghci_macros = [],
512 last_command = Nothing,
513 cmdqueue = [],
514 remembered_ctx = [],
515 transient_ctx = [],
516 extra_imports = [],
517 prelude_imports = [prelude_import],
518 ghc_e = isJust maybe_exprs,
519 short_help = shortHelpText config,
520 long_help = fullHelpText config,
521 lastErrorLocations = lastErrLocationsRef,
522 mod_infos = M.empty,
523 flushStdHandles = flush,
524 noBuffering = nobuffering
525 }
526
527 return ()
528
529 resetLastErrorLocations :: GHCi ()
530 resetLastErrorLocations = do
531 st <- getGHCiState
532 liftIO $ writeIORef (lastErrorLocations st) []
533
534 ghciLogAction :: IORef [(FastString, Int)] -> LogAction
535 ghciLogAction lastErrLocations dflags flag severity srcSpan style msg = do
536 defaultLogAction dflags flag severity srcSpan style msg
537 case severity of
538 SevError -> case srcSpan of
539 RealSrcSpan rsp -> modifyIORef lastErrLocations
540 (++ [(srcLocFile (realSrcSpanStart rsp), srcLocLine (realSrcSpanStart rsp))])
541 _ -> return ()
542 _ -> return ()
543
544 withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
545 withGhcAppData right left = do
546 either_dir <- tryIO (getAppUserDataDirectory "clash")
547 case either_dir of
548 Right dir ->
549 do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
550 right dir
551 _ -> left
552
553 runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
554 runGHCi paths maybe_exprs = do
555 dflags <- getDynFlags
556 let
557 ignore_dot_ghci = gopt Opt_IgnoreDotGhci dflags
558
559 current_dir = return (Just ".clashi")
560
561 app_user_dir = liftIO $ withGhcAppData
562 (\dir -> return (Just (dir </> "clashi.conf")))
563 (return Nothing)
564
565 home_dir = do
566 either_dir <- liftIO $ tryIO (getEnv "HOME")
567 case either_dir of
568 Right home -> return (Just (home </> ".clashi"))
569 _ -> return Nothing
570
571 canonicalizePath' :: FilePath -> IO (Maybe FilePath)
572 canonicalizePath' fp = liftM Just (canonicalizePath fp)
573 `catchIO` \_ -> return Nothing
574
575 sourceConfigFile :: FilePath -> GHCi ()
576 sourceConfigFile file = do
577 exists <- liftIO $ doesFileExist file
578 when exists $ do
579 either_hdl <- liftIO $ tryIO (openFile file ReadMode)
580 case either_hdl of
581 Left _e -> return ()
582 -- NOTE: this assumes that runInputT won't affect the terminal;
583 -- can we assume this will always be the case?
584 -- This would be a good place for runFileInputT.
585 Right hdl ->
586 do runInputTWithPrefs defaultPrefs defaultSettings $
587 runCommands $ fileLoop hdl
588 liftIO (hClose hdl `catchIO` \_ -> return ())
589 -- Don't print a message if this is really ghc -e (#11478).
590 -- Also, let the user silence the message with -v0
591 -- (the default verbosity in GHCi is 1).
592 when (isNothing maybe_exprs && verbosity dflags > 0) $
593 liftIO $ putStrLn ("Loaded Clashi configuration from " ++ file)
594
595 --
596
597 setGHCContextFromGHCiState
598
599 dot_cfgs <- if ignore_dot_ghci then return [] else do
600 dot_files <- catMaybes <$> sequence [ current_dir, app_user_dir, home_dir ]
601 liftIO $ filterM checkFileAndDirPerms dot_files
602 mdot_cfgs <- liftIO $ mapM canonicalizePath' dot_cfgs
603
604 let arg_cfgs = reverse $ ghciScripts dflags
605 -- -ghci-script are collected in reverse order
606 -- We don't require that a script explicitly added by -ghci-script
607 -- is owned by the current user. (#6017)
608 mapM_ sourceConfigFile $ nub $ (catMaybes mdot_cfgs) ++ arg_cfgs
609 -- nub, because we don't want to read .ghci twice if the CWD is $HOME.
610
611 -- Perform a :load for files given on the GHCi command line
612 -- When in -e mode, if the load fails then we want to stop
613 -- immediately rather than going on to evaluate the expression.
614 when (not (null paths)) $ do
615 ok <- ghciHandle (\e -> do showException e; return Failed) $
616 -- TODO: this is a hack.
617 runInputTWithPrefs defaultPrefs defaultSettings $
618 loadModule paths
619 when (isJust maybe_exprs && failed ok) $
620 liftIO (exitWith (ExitFailure 1))
621
622 installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
623
624 -- if verbosity is greater than 0, or we are connected to a
625 -- terminal, display the prompt in the interactive loop.
626 is_tty <- liftIO (hIsTerminalDevice stdin)
627 let show_prompt = verbosity dflags > 0 || is_tty
628
629 -- reset line number
630 modifyGHCiState $ \st -> st{line_number=0}
631
632 case maybe_exprs of
633 Nothing ->
634 do
635 -- Set different defaulting rules (See #280)
636 runGHCiExpressions
637 ["default ((), [], Prelude.Integer, Prelude.Int, Prelude.Double, Prelude.String)"]
638
639 -- enter the interactive loop
640 runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
641 Just exprs -> do
642 -- just evaluate the expression we were given
643 runGHCiExpressions exprs
644
645 -- and finally, exit
646 liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving Clashi."
647
648 runGHCiExpressions :: [String] -> GHCi ()
649 runGHCiExpressions exprs = do
650 enqueueCommands exprs
651 let hdle e = do st <- getGHCiState
652 -- flush the interpreter's stdout/stderr on exit (#3890)
653 flushInterpBuffers
654 -- Jump through some hoops to get the
655 -- current progname in the exception text:
656 -- <progname>: <exception>
657 liftIO $ withProgName (progname st)
658 $ topHandler e
659 -- this used to be topHandlerFastExit, see #2228
660 runInputTWithPrefs defaultPrefs defaultSettings $ do
661 -- make `ghc -e` exit nonzero on invalid input, see Trac #7962
662 _ <- runCommands' hdle
663 (Just $ hdle (toException $ ExitFailure 1) >> return ())
664 (return Nothing)
665 return ()
666
667 runGHCiInput :: InputT GHCi a -> GHCi a
668 runGHCiInput f = do
669 dflags <- getDynFlags
670 let ghciHistory = gopt Opt_GhciHistory dflags
671 let localGhciHistory = gopt Opt_LocalGhciHistory dflags
672 currentDirectory <- liftIO $ getCurrentDirectory
673
674 histFile <- case (ghciHistory, localGhciHistory) of
675 (True, True) -> return (Just (currentDirectory </> ".clashi_history"))
676 (True, _) -> liftIO $ withGhcAppData
677 (\dir -> return (Just (dir </> "clashi_history"))) (return Nothing)
678 _ -> return Nothing
679
680 runInputT
681 (setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
682 f
683
684 -- | How to get the next input line from the user
685 nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
686 nextInputLine show_prompt is_tty
687 | is_tty = do
688 prmpt <- if show_prompt then lift mkPrompt else return ""
689 r <- getInputLine prmpt
690 incrementLineNo
691 return r
692 | otherwise = do
693 when show_prompt $ lift mkPrompt >>= liftIO . putStr
694 fileLoop stdin
695
696 -- NOTE: We only read .ghci files if they are owned by the current user,
697 -- and aren't world writable (files owned by root are ok, see #9324).
698 -- Otherwise, we could be accidentally running code planted by
699 -- a malicious third party.
700
701 -- Furthermore, We only read ./.ghci if . is owned by the current user
702 -- and isn't writable by anyone else. I think this is sufficient: we
703 -- don't need to check .. and ../.. etc. because "." always refers to
704 -- the same directory while a process is running.
705
706 checkFileAndDirPerms :: FilePath -> IO Bool
707 checkFileAndDirPerms file = do
708 file_ok <- checkPerms file
709 -- Do not check dir perms when .ghci doesn't exist, otherwise GHCi will
710 -- print some confusing and useless warnings in some cases (e.g. in
711 -- travis). Note that we can't add a test for this, as all ghci tests should
712 -- run with -ignore-dot-ghci, which means we never get here.
713 if file_ok then checkPerms (getDirectory file) else return False
714 where
715 getDirectory f = case takeDirectory f of
716 "" -> "."
717 d -> d
718
719 checkPerms :: FilePath -> IO Bool
720 #if defined(mingw32_HOST_OS)
721 checkPerms _ = return True
722 #else
723 checkPerms file =
724 handleIO (\_ -> return False) $ do
725 st <- getFileStatus file
726 me <- getRealUserID
727 let mode = System.Posix.fileMode st
728 ok = (fileOwner st == me || fileOwner st == 0) &&
729 groupWriteMode /= mode `intersectFileModes` groupWriteMode &&
730 otherWriteMode /= mode `intersectFileModes` otherWriteMode
731 unless ok $
732 -- #8248: Improving warning to include a possible fix.
733 putStrLn $ "*** WARNING: " ++ file ++
734 " is writable by someone else, IGNORING!" ++
735 "\nSuggested fix: execute 'chmod go-w " ++ file ++ "'"
736 return ok
737 #endif
738
739 incrementLineNo :: InputT GHCi ()
740 incrementLineNo = modifyGHCiState incLineNo
741 where
742 incLineNo st = st { line_number = line_number st + 1 }
743
744 fileLoop :: Handle -> InputT GHCi (Maybe String)
745 fileLoop hdl = do
746 l <- liftIO $ tryIO $ hGetLine hdl
747 case l of
748 Left e | isEOFError e -> return Nothing
749 | -- as we share stdin with the program, the program
750 -- might have already closed it, so we might get a
751 -- handle-closed exception. We therefore catch that
752 -- too.
753 isIllegalOperation e -> return Nothing
754 | InvalidArgument <- etype -> return Nothing
755 | otherwise -> liftIO $ ioError e
756 where etype = ioeGetErrorType e
757 -- treat InvalidArgument in the same way as EOF:
758 -- this can happen if the user closed stdin, or
759 -- perhaps did getContents which closes stdin at
760 -- EOF.
761 Right l' -> do
762 incrementLineNo
763 return (Just l')
764
765 formatCurrentTime :: String -> IO String
766 formatCurrentTime format =
767 getZonedTime >>= return . (formatTime defaultTimeLocale format)
768
769 getUserName :: IO String
770 getUserName = do
771 #if defined(mingw32_HOST_OS)
772 getEnv "USERNAME"
773 `catchIO` \e -> do
774 putStrLn $ show e
775 return ""
776 #else
777 getLoginName
778 #endif
779
780 getInfoForPrompt :: GHCi (SDoc, [String], Int)
781 getInfoForPrompt = do
782 st <- getGHCiState
783 imports <- GHC.getContext
784 resumes <- GHC.getResumeContext
785
786 context_bit <-
787 case resumes of
788 [] -> return empty
789 r:_ -> do
790 let ix = GHC.resumeHistoryIx r
791 if ix == 0
792 then return (brackets (ppr (GHC.resumeSpan r)) <> space)
793 else do
794 let hist = GHC.resumeHistory r !! (ix-1)
795 pan <- GHC.getHistorySpan hist
796 return (brackets (ppr (negate ix) <> char ':'
797 <+> ppr pan) <> space)
798
799 let
800 dots | _:rs <- resumes, not (null rs) = text "... "
801 | otherwise = empty
802
803 rev_imports = reverse imports -- rightmost are the most recent
804
805 myIdeclName d | Just m <- ideclAs d = unLoc m
806 | otherwise = unLoc (ideclName d)
807
808 modules_names =
809 ['*':(moduleNameString m) | IIModule m <- rev_imports] ++
810 [moduleNameString (myIdeclName d) | IIDecl d <- rev_imports]
811 line = 1 + line_number st
812
813 return (dots <> context_bit, modules_names, line)
814
815 parseCallEscape :: String -> (String, String)
816 parseCallEscape s
817 | not (all isSpace beforeOpen) = ("", "")
818 | null sinceOpen = ("", "")
819 | null sinceClosed = ("", "")
820 | null cmd = ("", "")
821 | otherwise = (cmd, tail sinceClosed)
822 where
823 (beforeOpen, sinceOpen) = span (/='(') s
824 (cmd, sinceClosed) = span (/=')') (tail sinceOpen)
825
826 checkPromptStringForErrors :: String -> Maybe String
827 checkPromptStringForErrors ('%':'c':'a':'l':'l':xs) =
828 case parseCallEscape xs of
829 ("", "") -> Just ("Incorrect %call syntax. " ++
830 "Should be %call(a command and arguments).")
831 (_, afterClosed) -> checkPromptStringForErrors afterClosed
832 checkPromptStringForErrors ('%':'%':xs) = checkPromptStringForErrors xs
833 checkPromptStringForErrors (_:xs) = checkPromptStringForErrors xs
834 checkPromptStringForErrors "" = Nothing
835
836 generatePromptFunctionFromString :: String -> PromptFunction
837 generatePromptFunctionFromString promptS modules_names line =
838 processString promptS
839 where
840 processString :: String -> GHCi SDoc
841 processString ('%':'s':xs) =
842 liftM2 (<>) (return modules_list) (processString xs)
843 where
844 modules_list = hsep $ map text modules_names
845 processString ('%':'l':xs) =
846 liftM2 (<>) (return $ ppr line) (processString xs)
847 processString ('%':'d':xs) =
848 liftM2 (<>) (liftM text formatted_time) (processString xs)
849 where
850 formatted_time = liftIO $ formatCurrentTime "%a %b %d"
851 processString ('%':'t':xs) =
852 liftM2 (<>) (liftM text formatted_time) (processString xs)
853 where
854 formatted_time = liftIO $ formatCurrentTime "%H:%M:%S"
855 processString ('%':'T':xs) = do
856 liftM2 (<>) (liftM text formatted_time) (processString xs)
857 where
858 formatted_time = liftIO $ formatCurrentTime "%I:%M:%S"
859 processString ('%':'@':xs) = do
860 liftM2 (<>) (liftM text formatted_time) (processString xs)
861 where
862 formatted_time = liftIO $ formatCurrentTime "%I:%M %P"
863 processString ('%':'A':xs) = do
864 liftM2 (<>) (liftM text formatted_time) (processString xs)
865 where
866 formatted_time = liftIO $ formatCurrentTime "%H:%M"
867 processString ('%':'u':xs) =
868 liftM2 (<>) (liftM text user_name) (processString xs)
869 where
870 user_name = liftIO $ getUserName
871 processString ('%':'w':xs) =
872 liftM2 (<>) (liftM text current_directory) (processString xs)
873 where
874 current_directory = liftIO $ getCurrentDirectory
875 processString ('%':'o':xs) =
876 liftM ((text os) <>) (processString xs)
877 processString ('%':'a':xs) =
878 liftM ((text arch) <>) (processString xs)
879 processString ('%':'N':xs) =
880 liftM ((text compilerName) <>) (processString xs)
881 processString ('%':'V':xs) =
882 liftM ((text $ showVersion compilerVersion) <>) (processString xs)
883 processString ('%':'c':'a':'l':'l':xs) = do
884 respond <- liftIO $ do
885 (code, out, err) <-
886 readProcessWithExitCode
887 (head list_words) (tail list_words) ""
888 `catchIO` \e -> return (ExitFailure 1, "", show e)
889 case code of
890 ExitSuccess -> return out
891 _ -> do
892 hPutStrLn stderr err
893 return ""
894 liftM ((text respond) <>) (processString afterClosed)
895 where
896 (cmd, afterClosed) = parseCallEscape xs
897 list_words = words cmd
898 processString ('%':'%':xs) =
899 liftM ((char '%') <>) (processString xs)
900 processString (x:xs) =
901 liftM (char x <>) (processString xs)
902 processString "" =
903 return empty
904
905 mkPrompt :: GHCi String
906 mkPrompt = do
907 st <- getGHCiState
908 dflags <- getDynFlags
909 (context, modules_names, line) <- getInfoForPrompt
910
911 prompt_string <- (prompt st) modules_names line
912 let prompt_doc = context <> prompt_string
913
914 return (showSDoc dflags prompt_doc)
915
916 queryQueue :: GHCi (Maybe String)
917 queryQueue = do
918 st <- getGHCiState
919 case cmdqueue st of
920 [] -> return Nothing
921 c:cs -> do setGHCiState st{ cmdqueue = cs }
922 return (Just c)
923
924 -- Reconfigurable pretty-printing Ticket #5461
925 installInteractivePrint :: Maybe String -> Bool -> GHCi ()
926 installInteractivePrint Nothing _ = return ()
927 installInteractivePrint (Just ipFun) exprmode = do
928 ok <- trySuccess $ do
929 name <- head <$> GHC.parseName ipFun
930 modifySession (\he -> let new_ic = setInteractivePrintName (hsc_IC he) name
931 in he{hsc_IC = new_ic})
932 return Succeeded
933
934 when (failed ok && exprmode) $ liftIO (exitWith (ExitFailure 1))
935
936 -- | The main read-eval-print loop
937 runCommands :: InputT GHCi (Maybe String) -> InputT GHCi ()
938 runCommands gCmd = runCommands' handler Nothing gCmd >> return ()
939
940 runCommands' :: (SomeException -> GHCi Bool) -- ^ Exception handler
941 -> Maybe (GHCi ()) -- ^ Source error handler
942 -> InputT GHCi (Maybe String)
943 -> InputT GHCi (Maybe Bool)
944 -- We want to return () here, but have to return (Maybe Bool)
945 -- because gmask is not polymorphic enough: we want to use
946 -- unmask at two different types.
947 runCommands' eh sourceErrorHandler gCmd = gmask $ \unmask -> do
948 b <- ghandle (\e -> case fromException e of
949 Just UserInterrupt -> return $ Just False
950 _ -> case fromException e of
951 Just ghce ->
952 do liftIO (print (ghce :: GhcException))
953 return Nothing
954 _other ->
955 liftIO (Exception.throwIO e))
956 (unmask $ runOneCommand eh gCmd)
957 case b of
958 Nothing -> return Nothing
959 Just success -> do
960 unless success $ maybe (return ()) lift sourceErrorHandler
961 unmask $ runCommands' eh sourceErrorHandler gCmd
962
963 -- | Evaluate a single line of user input (either :<command> or Haskell code).
964 -- A result of Nothing means there was no more input to process.
965 -- Otherwise the result is Just b where b is True if the command succeeded;
966 -- this is relevant only to ghc -e, which will exit with status 1
967 -- if the command was unsuccessful. GHCi will continue in either case.
968 runOneCommand :: (SomeException -> GHCi Bool) -> InputT GHCi (Maybe String)
969 -> InputT GHCi (Maybe Bool)
970 runOneCommand eh gCmd = do
971 -- run a previously queued command if there is one, otherwise get new
972 -- input from user
973 mb_cmd0 <- noSpace (lift queryQueue)
974 mb_cmd1 <- maybe (noSpace gCmd) (return . Just) mb_cmd0
975 case mb_cmd1 of
976 Nothing -> return Nothing
977 Just c -> ghciHandle (\e -> lift $ eh e >>= return . Just) $
978 handleSourceError printErrorAndFail
979 (doCommand c)
980 -- source error's are handled by runStmt
981 -- is the handler necessary here?
982 where
983 printErrorAndFail err = do
984 GHC.printException err
985 return $ Just False -- Exit ghc -e, but not GHCi
986
987 noSpace q = q >>= maybe (return Nothing)
988 (\c -> case removeSpaces c of
989 "" -> noSpace q
990 ":{" -> multiLineCmd q
991 _ -> return (Just c) )
992 multiLineCmd q = do
993 st <- getGHCiState
994 let p = prompt st
995 setGHCiState st{ prompt = prompt_cont st }
996 mb_cmd <- collectCommand q "" `GHC.gfinally`
997 modifyGHCiState (\st' -> st' { prompt = p })
998 return mb_cmd
999 -- we can't use removeSpaces for the sublines here, so
1000 -- multiline commands are somewhat more brittle against
1001 -- fileformat errors (such as \r in dos input on unix),
1002 -- we get rid of any extra spaces for the ":}" test;
1003 -- we also avoid silent failure if ":}" is not found;
1004 -- and since there is no (?) valid occurrence of \r (as
1005 -- opposed to its String representation, "\r") inside a
1006 -- ghci command, we replace any such with ' ' (argh:-(
1007 collectCommand q c = q >>=
1008 maybe (liftIO (ioError collectError))
1009 (\l->if removeSpaces l == ":}"
1010 then return (Just c)
1011 else collectCommand q (c ++ "\n" ++ map normSpace l))
1012 where normSpace '\r' = ' '
1013 normSpace x = x
1014 -- SDM (2007-11-07): is userError the one to use here?
1015 collectError = userError "unterminated multiline command :{ .. :}"
1016
1017 -- | Handle a line of input
1018 doCommand :: String -> InputT GHCi (Maybe Bool)
1019
1020 -- command
1021 doCommand stmt | (':' : cmd) <- removeSpaces stmt = do
1022 result <- specialCommand cmd
1023 case result of
1024 True -> return Nothing
1025 _ -> return $ Just True
1026
1027 -- haskell
1028 doCommand stmt = do
1029 -- if 'stmt' was entered via ':{' it will contain '\n's
1030 let stmt_nl_cnt = length [ () | '\n' <- stmt ]
1031 ml <- lift $ isOptionSet Multiline
1032 if ml && stmt_nl_cnt == 0 -- don't trigger automatic multi-line mode for ':{'-multiline input
1033 then do
1034 fst_line_num <- line_number <$> getGHCiState
1035 mb_stmt <- checkInputForLayout stmt gCmd
1036 case mb_stmt of
1037 Nothing -> return $ Just True
1038 Just ml_stmt -> do
1039 -- temporarily compensate line-number for multi-line input
1040 result <- timeIt runAllocs $ lift $
1041 runStmtWithLineNum fst_line_num ml_stmt GHC.RunToCompletion
1042 return $ Just (runSuccess result)
1043 else do -- single line input and :{ - multiline input
1044 last_line_num <- line_number <$> getGHCiState
1045 -- reconstruct first line num from last line num and stmt
1046 let fst_line_num | stmt_nl_cnt > 0 = last_line_num - (stmt_nl_cnt2 + 1)
1047 | otherwise = last_line_num -- single line input
1048 stmt_nl_cnt2 = length [ () | '\n' <- stmt' ]
1049 stmt' = dropLeadingWhiteLines stmt -- runStmt doesn't like leading empty lines
1050 -- temporarily compensate line-number for multi-line input
1051 result <- timeIt runAllocs $ lift $
1052 runStmtWithLineNum fst_line_num stmt' GHC.RunToCompletion
1053 return $ Just (runSuccess result)
1054
1055 -- runStmt wrapper for temporarily overridden line-number
1056 runStmtWithLineNum :: Int -> String -> SingleStep
1057 -> GHCi (Maybe GHC.ExecResult)
1058 runStmtWithLineNum lnum stmt step = do
1059 st0 <- getGHCiState
1060 setGHCiState st0 { line_number = lnum }
1061 result <- runStmt stmt step
1062 -- restore original line_number
1063 getGHCiState >>= \st -> setGHCiState st { line_number = line_number st0 }
1064 return result
1065
1066 -- note: this is subtly different from 'unlines . dropWhile (all isSpace) . lines'
1067 dropLeadingWhiteLines s | (l0,'\n':r) <- break (=='\n') s
1068 , all isSpace l0 = dropLeadingWhiteLines r
1069 | otherwise = s
1070
1071
1072 -- #4316
1073 -- lex the input. If there is an unclosed layout context, request input
1074 checkInputForLayout :: String -> InputT GHCi (Maybe String)
1075 -> InputT GHCi (Maybe String)
1076 checkInputForLayout stmt getStmt = do
1077 dflags' <- getDynFlags
1078 let dflags = xopt_set dflags' LangExt.AlternativeLayoutRule
1079 st0 <- getGHCiState
1080 let buf' = stringToStringBuffer stmt
1081 loc = mkRealSrcLoc (fsLit (progname st0)) (line_number st0) 1
1082 pstate = Lexer.mkPState dflags buf' loc
1083 case Lexer.unP goToEnd pstate of
1084 (Lexer.POk _ False) -> return $ Just stmt
1085 _other -> do
1086 st1 <- getGHCiState
1087 let p = prompt st1
1088 setGHCiState st1{ prompt = prompt_cont st1 }
1089 mb_stmt <- ghciHandle (\ex -> case fromException ex of
1090 Just UserInterrupt -> return Nothing
1091 _ -> case fromException ex of
1092 Just ghce ->
1093 do liftIO (print (ghce :: GhcException))
1094 return Nothing
1095 _other -> liftIO (Exception.throwIO ex))
1096 getStmt
1097 modifyGHCiState (\st' -> st' { prompt = p })
1098 -- the recursive call does not recycle parser state
1099 -- as we use a new string buffer
1100 case mb_stmt of
1101 Nothing -> return Nothing
1102 Just str -> if str == ""
1103 then return $ Just stmt
1104 else do
1105 checkInputForLayout (stmt++"\n"++str) getStmt
1106 where goToEnd = do
1107 eof <- Lexer.nextIsEOF
1108 if eof
1109 then Lexer.activeContext
1110 else Lexer.lexer False return >> goToEnd
1111
1112 enqueueCommands :: [String] -> GHCi ()
1113 enqueueCommands cmds = do
1114 -- make sure we force any exceptions in the commands while we're
1115 -- still inside the exception handler, otherwise bad things will
1116 -- happen (see #10501)
1117 cmds `deepseq` return ()
1118 modifyGHCiState $ \st -> st{ cmdqueue = cmds ++ cmdqueue st }
1119
1120 -- | Entry point to execute some haskell code from user.
1121 -- The return value True indicates success, as in `runOneCommand`.
1122 runStmt :: String -> SingleStep -> GHCi (Maybe GHC.ExecResult)
1123 runStmt stmt step = do
1124 dflags <- GHC.getInteractiveDynFlags
1125 -- In GHCi, we disable `-fdefer-type-errors`, as well as `-fdefer-type-holes`
1126 -- and `-fdefer-out-of-scope-variables` for **naked expressions**. The
1127 -- declarations and statements are not affected.
1128 -- See Note [Deferred type errors in GHCi] in typecheck/TcRnDriver.hs
1129 if | GHC.isStmt dflags stmt -> run_stmt
1130 | GHC.isImport dflags stmt -> run_import
1131 -- Every import declaration should be handled by `run_import`. As GHCi
1132 -- in general only accepts one command at a time, we simply throw an
1133 -- exception when the input contains multiple commands of which at least
1134 -- one is an import command (see #10663).
1135 | GHC.hasImport dflags stmt -> throwGhcException
1136 (CmdLineError "error: expecting a single import declaration")
1137 -- Note: `GHC.isDecl` returns False on input like
1138 -- `data Infix a b = a :@: b; infixl 4 :@:`
1139 -- and should therefore not be used here.
1140 | otherwise -> run_decl
1141
1142 where
1143 run_import = do
1144 addImportToContext stmt
1145 return (Just (GHC.ExecComplete (Right []) 0))
1146
1147 run_decl =
1148 do _ <- liftIO $ tryIO $ hFlushAll stdin
1149 m_result <- GhciMonad.runDecls stmt
1150 case m_result of
1151 Nothing -> return Nothing
1152 Just result ->
1153 Just <$> afterRunStmt (const True)
1154 (GHC.ExecComplete (Right result) 0)
1155
1156 run_stmt =
1157 do -- In the new IO library, read handles buffer data even if the Handle
1158 -- is set to NoBuffering. This causes problems for GHCi where there
1159 -- are really two stdin Handles. So we flush any bufferred data in
1160 -- GHCi's stdin Handle here (only relevant if stdin is attached to
1161 -- a file, otherwise the read buffer can't be flushed).
1162 _ <- liftIO $ tryIO $ hFlushAll stdin
1163 m_result <- GhciMonad.runStmt stmt step
1164 case m_result of
1165 Nothing -> return Nothing
1166 Just result -> Just <$> afterRunStmt (const True) result
1167
1168 -- | Clean up the GHCi environment after a statement has run
1169 afterRunStmt :: (SrcSpan -> Bool) -> GHC.ExecResult -> GHCi GHC.ExecResult
1170 afterRunStmt step_here run_result = do
1171 resumes <- GHC.getResumeContext
1172 case run_result of
1173 GHC.ExecComplete{..} ->
1174 case execResult of
1175 Left ex -> liftIO $ Exception.throwIO ex
1176 Right names -> do
1177 show_types <- isOptionSet ShowType
1178 when show_types $ printTypeOfNames names
1179 GHC.ExecBreak names mb_info
1180 | isNothing mb_info ||
1181 step_here (GHC.resumeSpan $ head resumes) -> do
1182 mb_id_loc <- toBreakIdAndLocation mb_info
1183 let bCmd = maybe "" ( \(_,l) -> onBreakCmd l ) mb_id_loc
1184 if (null bCmd)
1185 then printStoppedAtBreakInfo (head resumes) names
1186 else enqueueCommands [bCmd]
1187 -- run the command set with ":set stop <cmd>"
1188 st <- getGHCiState
1189 enqueueCommands [stop st]
1190 return ()
1191 | otherwise -> resume step_here GHC.SingleStep >>=
1192 afterRunStmt step_here >> return ()
1193
1194 flushInterpBuffers
1195 withSignalHandlers $ do
1196 b <- isOptionSet RevertCAFs
1197 when b revertCAFs
1198
1199 return run_result
1200
1201 runSuccess :: Maybe GHC.ExecResult -> Bool
1202 runSuccess run_result
1203 | Just (GHC.ExecComplete { execResult = Right _ }) <- run_result = True
1204 | otherwise = False
1205
1206 runAllocs :: Maybe GHC.ExecResult -> Maybe Integer
1207 runAllocs m = do
1208 res <- m
1209 case res of
1210 GHC.ExecComplete{..} -> Just (fromIntegral execAllocation)
1211 _ -> Nothing
1212
1213 toBreakIdAndLocation ::
1214 Maybe GHC.BreakInfo -> GHCi (Maybe (Int, BreakLocation))
1215 toBreakIdAndLocation Nothing = return Nothing
1216 toBreakIdAndLocation (Just inf) = do
1217 let md = GHC.breakInfo_module inf
1218 nm = GHC.breakInfo_number inf
1219 st <- getGHCiState
1220 return $ listToMaybe [ id_loc | id_loc@(_,loc) <- breaks st,
1221 breakModule loc == md,
1222 breakTick loc == nm ]
1223
1224 printStoppedAtBreakInfo :: Resume -> [Name] -> GHCi ()
1225 printStoppedAtBreakInfo res names = do
1226 printForUser $ pprStopped res
1227 -- printTypeOfNames session names
1228 let namesSorted = sortBy compareNames names
1229 tythings <- catMaybes `liftM` mapM GHC.lookupName namesSorted
1230 docs <- mapM pprTypeAndContents [i | AnId i <- tythings]
1231 printForUserPartWay $ vcat docs
1232
1233 printTypeOfNames :: [Name] -> GHCi ()
1234 printTypeOfNames names
1235 = mapM_ (printTypeOfName ) $ sortBy compareNames names
1236
1237 compareNames :: Name -> Name -> Ordering
1238 n1 `compareNames` n2 = compareWith n1 `compare` compareWith n2
1239 where compareWith n = (getOccString n, getSrcSpan n)
1240
1241 printTypeOfName :: Name -> GHCi ()
1242 printTypeOfName n
1243 = do maybe_tything <- GHC.lookupName n
1244 case maybe_tything of
1245 Nothing -> return ()
1246 Just thing -> printTyThing thing
1247
1248
1249 data MaybeCommand = GotCommand Command | BadCommand | NoLastCommand
1250
1251 -- | Entry point for execution a ':<command>' input from user
1252 specialCommand :: String -> InputT GHCi Bool
1253 specialCommand ('!':str) = lift $ shellEscape (dropWhile isSpace str)
1254 specialCommand str = do
1255 let (cmd,rest) = break isSpace str
1256 maybe_cmd <- lift $ lookupCommand cmd
1257 htxt <- short_help <$> getGHCiState
1258 case maybe_cmd of
1259 GotCommand cmd -> (cmdAction cmd) (dropWhile isSpace rest)
1260 BadCommand ->
1261 do liftIO $ hPutStr stdout ("unknown command ':" ++ cmd ++ "'\n"
1262 ++ htxt)
1263 return False
1264 NoLastCommand ->
1265 do liftIO $ hPutStr stdout ("there is no last command to perform\n"
1266 ++ htxt)
1267 return False
1268
1269 shellEscape :: String -> GHCi Bool
1270 shellEscape str = liftIO (system str >> return False)
1271
1272 lookupCommand :: String -> GHCi (MaybeCommand)
1273 lookupCommand "" = do
1274 st <- getGHCiState
1275 case last_command st of
1276 Just c -> return $ GotCommand c
1277 Nothing -> return NoLastCommand
1278 lookupCommand str = do
1279 mc <- lookupCommand' str
1280 modifyGHCiState (\st -> st { last_command = mc })
1281 return $ case mc of
1282 Just c -> GotCommand c
1283 Nothing -> BadCommand
1284
1285 lookupCommand' :: String -> GHCi (Maybe Command)
1286 lookupCommand' ":" = return Nothing
1287 lookupCommand' str' = do
1288 macros <- ghci_macros <$> getGHCiState
1289 ghci_cmds <- ghci_commands <$> getGHCiState
1290
1291 let ghci_cmds_nohide = filter (not . cmdHidden) ghci_cmds
1292
1293 let (str, xcmds) = case str' of
1294 ':' : rest -> (rest, []) -- "::" selects a builtin command
1295 _ -> (str', macros) -- otherwise include macros in lookup
1296
1297 lookupExact s = find $ (s ==) . cmdName
1298 lookupPrefix s = find $ (s `isPrefixOf`) . cmdName
1299
1300 -- hidden commands can only be matched exact
1301 builtinPfxMatch = lookupPrefix str ghci_cmds_nohide
1302
1303 -- first, look for exact match (while preferring macros); then, look
1304 -- for first prefix match (preferring builtins), *unless* a macro
1305 -- overrides the builtin; see #8305 for motivation
1306 return $ lookupExact str xcmds <|>
1307 lookupExact str ghci_cmds <|>
1308 (builtinPfxMatch >>= \c -> lookupExact (cmdName c) xcmds) <|>
1309 builtinPfxMatch <|>
1310 lookupPrefix str xcmds
1311
1312 getCurrentBreakSpan :: GHCi (Maybe SrcSpan)
1313 getCurrentBreakSpan = do
1314 resumes <- GHC.getResumeContext
1315 case resumes of
1316 [] -> return Nothing
1317 (r:_) -> do
1318 let ix = GHC.resumeHistoryIx r
1319 if ix == 0
1320 then return (Just (GHC.resumeSpan r))
1321 else do
1322 let hist = GHC.resumeHistory r !! (ix-1)
1323 pan <- GHC.getHistorySpan hist
1324 return (Just pan)
1325
1326 getCallStackAtCurrentBreakpoint :: GHCi (Maybe [String])
1327 getCallStackAtCurrentBreakpoint = do
1328 resumes <- GHC.getResumeContext
1329 case resumes of
1330 [] -> return Nothing
1331 (r:_) -> do
1332 hsc_env <- GHC.getSession
1333 Just <$> liftIO (costCentreStackInfo hsc_env (GHC.resumeCCS r))
1334
1335 getCurrentBreakModule :: GHCi (Maybe Module)
1336 getCurrentBreakModule = do
1337 resumes <- GHC.getResumeContext
1338 case resumes of
1339 [] -> return Nothing
1340 (r:_) -> do
1341 let ix = GHC.resumeHistoryIx r
1342 if ix == 0
1343 then return (GHC.breakInfo_module `liftM` GHC.resumeBreakInfo r)
1344 else do
1345 let hist = GHC.resumeHistory r !! (ix-1)
1346 return $ Just $ GHC.getHistoryModule hist
1347
1348 -----------------------------------------------------------------------------
1349 --
1350 -- Commands
1351 --
1352 -----------------------------------------------------------------------------
1353
1354 noArgs :: GHCi () -> String -> GHCi ()
1355 noArgs m "" = m
1356 noArgs _ _ = liftIO $ putStrLn "This command takes no arguments"
1357
1358 withSandboxOnly :: String -> GHCi () -> GHCi ()
1359 withSandboxOnly cmd this = do
1360 dflags <- getDynFlags
1361 if not (gopt Opt_GhciSandbox dflags)
1362 then printForUser (text cmd <+>
1363 ptext (sLit "is not supported with -fno-ghci-sandbox"))
1364 else this
1365
1366 -----------------------------------------------------------------------------
1367 -- :help
1368
1369 help :: String -> GHCi ()
1370 help _ = do
1371 txt <- long_help `fmap` getGHCiState
1372 liftIO $ putStr txt
1373
1374 -----------------------------------------------------------------------------
1375 -- :info
1376
1377 info :: Bool -> String -> InputT GHCi ()
1378 info _ "" = throwGhcException (CmdLineError "syntax: ':i <thing-you-want-info-about>'")
1379 info allInfo s = handleSourceError GHC.printException $ do
1380 unqual <- GHC.getPrintUnqual
1381 dflags <- getDynFlags
1382 sdocs <- mapM (infoThing allInfo) (words s)
1383 mapM_ (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs
1384
1385 infoThing :: GHC.GhcMonad m => Bool -> String -> m SDoc
1386 infoThing allInfo str = do
1387 names <- GHC.parseName str
1388 mb_stuffs <- mapM (GHC.getInfo allInfo) names
1389 let filtered = filterOutChildren (\(t,_f,_ci,_fi,_sd) -> t)
1390 (catMaybes mb_stuffs)
1391 return $ vcat (intersperse (text "") $ map pprInfo filtered)
1392
1393 -- Filter out names whose parent is also there Good
1394 -- example is '[]', which is both a type and data
1395 -- constructor in the same type
1396 filterOutChildren :: (a -> TyThing) -> [a] -> [a]
1397 filterOutChildren get_thing xs
1398 = filterOut has_parent xs
1399 where
1400 all_names = mkNameSet (map (getName . get_thing) xs)
1401 has_parent x = case tyThingParent_maybe (get_thing x) of
1402 Just p -> getName p `elemNameSet` all_names
1403 Nothing -> False
1404
1405 pprInfo :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
1406 pprInfo (thing, fixity, cls_insts, fam_insts, docs)
1407 = docs
1408 $$ pprTyThingInContextLoc thing
1409 $$ show_fixity
1410 $$ vcat (map GHC.pprInstance cls_insts)
1411 $$ vcat (map GHC.pprFamInst fam_insts)
1412 where
1413 show_fixity
1414 | fixity == GHC.defaultFixity = empty
1415 | otherwise = ppr fixity <+> pprInfixName (GHC.getName thing)
1416
1417 -----------------------------------------------------------------------------
1418 -- :main
1419
1420 runMain :: String -> GHCi ()
1421 runMain s = case toArgs s of
1422 Left err -> liftIO (hPutStrLn stderr err)
1423 Right args ->
1424 do dflags <- getDynFlags
1425 let main = fromMaybe "main" (mainFunIs dflags)
1426 -- Wrap the main function in 'void' to discard its value instead
1427 -- of printing it (#9086). See Haskell 2010 report Chapter 5.
1428 doWithArgs args $ "Control.Monad.void (" ++ main ++ ")"
1429
1430 -----------------------------------------------------------------------------
1431 -- :run
1432
1433 runRun :: String -> GHCi ()
1434 runRun s = case toCmdArgs s of
1435 Left err -> liftIO (hPutStrLn stderr err)
1436 Right (cmd, args) -> doWithArgs args cmd
1437
1438 doWithArgs :: [String] -> String -> GHCi ()
1439 doWithArgs args cmd = enqueueCommands ["System.Environment.withArgs " ++
1440 show args ++ " (" ++ cmd ++ ")"]
1441
1442 -----------------------------------------------------------------------------
1443 -- :cd
1444
1445 changeDirectory :: String -> InputT GHCi ()
1446 changeDirectory "" = do
1447 -- :cd on its own changes to the user's home directory
1448 either_dir <- liftIO $ tryIO getHomeDirectory
1449 case either_dir of
1450 Left _e -> return ()
1451 Right dir -> changeDirectory dir
1452 changeDirectory dir = do
1453 graph <- GHC.getModuleGraph
1454 when (not (null $ GHC.mgModSummaries graph)) $
1455 liftIO $ putStrLn "Warning: changing directory causes all loaded modules to be unloaded,\nbecause the search path has changed."
1456 GHC.setTargets []
1457 _ <- GHC.load LoadAllTargets
1458 lift $ setContextAfterLoad False []
1459 GHC.workingDirectoryChanged
1460 dir' <- expandPath dir
1461 liftIO $ setCurrentDirectory dir'
1462 dflags <- getDynFlags
1463 -- With -fexternal-interpreter, we have to change the directory of the subprocess too.
1464 -- (this gives consistent behavior with and without -fexternal-interpreter)
1465 when (gopt Opt_ExternalInterpreter dflags) $
1466 lift $ enqueueCommands ["System.Directory.setCurrentDirectory " ++ show dir']
1467
1468 trySuccess :: GHC.GhcMonad m => m SuccessFlag -> m SuccessFlag
1469 trySuccess act =
1470 handleSourceError (\e -> do GHC.printException e
1471 return Failed) $ do
1472 act
1473
1474 -----------------------------------------------------------------------------
1475 -- :edit
1476
1477 editFile :: String -> InputT GHCi ()
1478 editFile str =
1479 do file <- if null str then lift chooseEditFile else expandPath str
1480 st <- getGHCiState
1481 errs <- liftIO $ readIORef $ lastErrorLocations st
1482 let cmd = editor st
1483 when (null cmd)
1484 $ throwGhcException (CmdLineError "editor not set, use :set editor")
1485 lineOpt <- liftIO $ do
1486 let sameFile p1 p2 = liftA2 (==) (canonicalizePath p1) (canonicalizePath p2)
1487 `catchIO` (\_ -> return False)
1488
1489 curFileErrs <- filterM (\(f, _) -> unpackFS f `sameFile` file) errs
1490 return $ case curFileErrs of
1491 (_, line):_ -> " +" ++ show line
1492 _ -> ""
1493 let cmdArgs = ' ':(file ++ lineOpt)
1494 code <- liftIO $ system (cmd ++ cmdArgs)
1495
1496 when (code == ExitSuccess)
1497 $ reloadModule ""
1498
1499 -- The user didn't specify a file so we pick one for them.
1500 -- Our strategy is to pick the first module that failed to load,
1501 -- or otherwise the first target.
1502 --
1503 -- XXX: Can we figure out what happened if the depndecy analysis fails
1504 -- (e.g., because the porgrammeer mistyped the name of a module)?
1505 -- XXX: Can we figure out the location of an error to pass to the editor?
1506 -- XXX: if we could figure out the list of errors that occured during the
1507 -- last load/reaload, then we could start the editor focused on the first
1508 -- of those.
1509 chooseEditFile :: GHCi String
1510 chooseEditFile =
1511 do let hasFailed x = fmap not $ GHC.isLoaded $ GHC.ms_mod_name x
1512
1513 graph <- GHC.getModuleGraph
1514 failed_graph <-
1515 GHC.mkModuleGraph <$> filterM hasFailed (GHC.mgModSummaries graph)
1516 let order g = flattenSCCs $ GHC.topSortModuleGraph True g Nothing
1517 pick xs = case xs of
1518 x : _ -> GHC.ml_hs_file (GHC.ms_location x)
1519 _ -> Nothing
1520
1521 case pick (order failed_graph) of
1522 Just file -> return file
1523 Nothing ->
1524 do targets <- GHC.getTargets
1525 case msum (map fromTarget targets) of
1526 Just file -> return file
1527 Nothing -> throwGhcException (CmdLineError "No files to edit.")
1528
1529 where fromTarget (GHC.Target (GHC.TargetFile f _) _ _) = Just f
1530 fromTarget _ = Nothing -- when would we get a module target?
1531
1532
1533 -----------------------------------------------------------------------------
1534 -- :def
1535
1536 defineMacro :: Bool{-overwrite-} -> String -> GHCi ()
1537 defineMacro _ (':':_) =
1538 liftIO $ putStrLn "macro name cannot start with a colon"
1539 defineMacro overwrite s = do
1540 let (macro_name, definition) = break isSpace s
1541 macros <- ghci_macros <$> getGHCiState
1542 let defined = map cmdName macros
1543 if null macro_name
1544 then if null defined
1545 then liftIO $ putStrLn "no macros defined"
1546 else liftIO $ putStr ("the following macros are defined:\n" ++
1547 unlines defined)
1548 else do
1549 if (not overwrite && macro_name `elem` defined)
1550 then throwGhcException (CmdLineError
1551 ("macro '" ++ macro_name ++ "' is already defined"))
1552 else do
1553
1554 -- compile the expression
1555 handleSourceError GHC.printException $ do
1556 step <- getGhciStepIO
1557 expr <- GHC.parseExpr definition
1558 -- > ghciStepIO . definition :: String -> IO String
1559 let stringTy = nlHsTyVar stringTy_RDR
1560 ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
1561 body = nlHsVar compose_RDR `mkHsApp` (nlHsPar step)
1562 `mkHsApp` (nlHsPar expr)
1563 tySig = mkLHsSigWcType (stringTy `nlHsFunTy` ioM)
1564 new_expr = L (getLoc expr) $ ExprWithTySig tySig body
1565 hv <- GHC.compileParsedExprRemote new_expr
1566
1567 let newCmd = Command { cmdName = macro_name
1568 , cmdAction = lift . runMacro hv
1569 , cmdHidden = False
1570 , cmdCompletionFunc = noCompletion
1571 }
1572
1573 -- later defined macros have precedence
1574 modifyGHCiState $ \s ->
1575 let filtered = [ cmd | cmd <- macros, cmdName cmd /= macro_name ]
1576 in s { ghci_macros = newCmd : filtered }
1577
1578 runMacro :: GHC.ForeignHValue{-String -> IO String-} -> String -> GHCi Bool
1579 runMacro fun s = do
1580 hsc_env <- GHC.getSession
1581 str <- liftIO $ evalStringToIOString hsc_env fun s
1582 enqueueCommands (lines str)
1583 return False
1584
1585
1586 -----------------------------------------------------------------------------
1587 -- :undef
1588
1589 undefineMacro :: String -> GHCi ()
1590 undefineMacro str = mapM_ undef (words str)
1591 where undef macro_name = do
1592 cmds <- ghci_macros <$> getGHCiState
1593 if (macro_name `notElem` map cmdName cmds)
1594 then throwGhcException (CmdLineError
1595 ("macro '" ++ macro_name ++ "' is not defined"))
1596 else do
1597 -- This is a tad racy but really, it's a shell
1598 modifyGHCiState $ \s ->
1599 s { ghci_macros = filter ((/= macro_name) . cmdName)
1600 (ghci_macros s) }
1601
1602
1603 -----------------------------------------------------------------------------
1604 -- :cmd
1605
1606 cmdCmd :: String -> GHCi ()
1607 cmdCmd str = handleSourceError GHC.printException $ do
1608 step <- getGhciStepIO
1609 expr <- GHC.parseExpr str
1610 -- > ghciStepIO str :: IO String
1611 let new_expr = step `mkHsApp` expr
1612 hv <- GHC.compileParsedExprRemote new_expr
1613
1614 hsc_env <- GHC.getSession
1615 cmds <- liftIO $ evalString hsc_env hv
1616 enqueueCommands (lines cmds)
1617
1618 -- | Generate a typed ghciStepIO expression
1619 -- @ghciStepIO :: Ty String -> IO String@.
1620 getGhciStepIO :: GHCi (LHsExpr GhcPs)
1621 getGhciStepIO = do
1622 ghciTyConName <- GHC.getGHCiMonad
1623 let stringTy = nlHsTyVar stringTy_RDR
1624 ghciM = nlHsTyVar (getRdrName ghciTyConName) `nlHsAppTy` stringTy
1625 ioM = nlHsTyVar (getRdrName ioTyConName) `nlHsAppTy` stringTy
1626 body = nlHsVar (getRdrName ghciStepIoMName)
1627 tySig = mkLHsSigWcType (ghciM `nlHsFunTy` ioM)
1628 return $ noLoc $ ExprWithTySig tySig body
1629
1630 -----------------------------------------------------------------------------
1631 -- :check
1632
1633 checkModule :: String -> InputT GHCi ()
1634 checkModule m = do
1635 let modl = GHC.mkModuleName m
1636 ok <- handleSourceError (\e -> GHC.printException e >> return False) $ do
1637 r <- GHC.typecheckModule =<< GHC.parseModule =<< GHC.getModSummary modl
1638 dflags <- getDynFlags
1639 liftIO $ putStrLn $ showSDoc dflags $
1640 case GHC.moduleInfo r of
1641 cm | Just scope <- GHC.modInfoTopLevelScope cm ->
1642 let
1643 (loc, glob) = ASSERT( all isExternalName scope )
1644 partition ((== modl) . GHC.moduleName . GHC.nameModule) scope
1645 in
1646 (text "global names: " <+> ppr glob) $$
1647 (text "local names: " <+> ppr loc)
1648 _ -> empty
1649 return True
1650 afterLoad (successIf ok) False
1651
1652 -----------------------------------------------------------------------------
1653 -- :doc
1654
1655 docCmd :: String -> InputT GHCi ()
1656 docCmd "" =
1657 throwGhcException (CmdLineError "syntax: ':doc <thing-you-want-docs-for>'")
1658 docCmd s = do
1659 -- TODO: Maybe also get module headers for module names
1660 names <- GHC.parseName s
1661 e_docss <- mapM GHC.getDocs names
1662 sdocs <- mapM (either handleGetDocsFailure (pure . pprDocs)) e_docss
1663 let sdocs' = vcat (intersperse (text "") sdocs)
1664 unqual <- GHC.getPrintUnqual
1665 dflags <- getDynFlags
1666 (liftIO . putStrLn . showSDocForUser dflags unqual) sdocs'
1667
1668 -- TODO: also print arg docs.
1669 pprDocs :: (Maybe HsDocString, Map Int HsDocString) -> SDoc
1670 pprDocs (mb_decl_docs, _arg_docs) =
1671 maybe
1672 (text "<has no documentation>")
1673 (text . unpackHDS)
1674 mb_decl_docs
1675
1676 handleGetDocsFailure :: GHC.GhcMonad m => GetDocsFailure -> m SDoc
1677 handleGetDocsFailure no_docs = do
1678 dflags <- getDynFlags
1679 let msg = showPpr dflags no_docs
1680 throwGhcException $ case no_docs of
1681 NameHasNoModule {} -> Sorry msg
1682 NoDocsInIface {} -> InstallationError msg
1683 InteractiveName -> ProgramError msg
1684
1685 -----------------------------------------------------------------------------
1686 -- :load, :add, :reload
1687
1688 -- | Sets '-fdefer-type-errors' if 'defer' is true, executes 'load' and unsets
1689 -- '-fdefer-type-errors' again if it has not been set before.
1690 wrapDeferTypeErrors :: InputT GHCi a -> InputT GHCi a
1691 wrapDeferTypeErrors load =
1692 gbracket
1693 (do
1694 -- Force originalFlags to avoid leaking the associated HscEnv
1695 !originalFlags <- getDynFlags
1696 void $ GHC.setProgramDynFlags $
1697 setGeneralFlag' Opt_DeferTypeErrors originalFlags
1698 return originalFlags)
1699 (\originalFlags -> void $ GHC.setProgramDynFlags originalFlags)
1700 (\_ -> load)
1701
1702 loadModule :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
1703 loadModule fs = timeIt (const Nothing) (loadModule' fs)
1704
1705 -- | @:load@ command
1706 loadModule_ :: [FilePath] -> InputT GHCi ()
1707 loadModule_ fs = void $ loadModule (zip fs (repeat Nothing))
1708
1709 loadModuleDefer :: [FilePath] -> InputT GHCi ()
1710 loadModuleDefer = wrapDeferTypeErrors . loadModule_
1711
1712 loadModule' :: [(FilePath, Maybe Phase)] -> InputT GHCi SuccessFlag
1713 loadModule' files = do
1714 let (filenames, phases) = unzip files
1715 exp_filenames <- mapM expandPath filenames
1716 let files' = zip exp_filenames phases
1717 targets <- mapM (uncurry GHC.guessTarget) files'
1718
1719 -- NOTE: we used to do the dependency anal first, so that if it
1720 -- fails we didn't throw away the current set of modules. This would
1721 -- require some re-working of the GHC interface, so we'll leave it
1722 -- as a ToDo for now.
1723
1724 hsc_env <- GHC.getSession
1725
1726 -- Grab references to the currently loaded modules so that we can
1727 -- see if they leak.
1728 leak_indicators <- if gopt Opt_GhciLeakCheck (hsc_dflags hsc_env)
1729 then liftIO $ getLeakIndicators hsc_env
1730 else return (panic "no leak indicators")
1731
1732 -- unload first
1733 _ <- GHC.abandonAll
1734 lift discardActiveBreakPoints
1735 GHC.setTargets []
1736 _ <- GHC.load LoadAllTargets
1737
1738 GHC.setTargets targets
1739 success <- doLoadAndCollectInfo False LoadAllTargets
1740 when (gopt Opt_GhciLeakCheck (hsc_dflags hsc_env)) $
1741 liftIO $ checkLeakIndicators (hsc_dflags hsc_env) leak_indicators
1742 return success
1743
1744 -- | @:add@ command
1745 addModule :: [FilePath] -> InputT GHCi ()
1746 addModule files = do
1747 lift revertCAFs -- always revert CAFs on load/add.
1748 files' <- mapM expandPath files
1749 targets <- mapM (\m -> GHC.guessTarget m Nothing) files'
1750 targets' <- filterM checkTarget targets
1751 -- remove old targets with the same id; e.g. for :add *M
1752 mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets' ]
1753 mapM_ GHC.addTarget targets'
1754 _ <- doLoadAndCollectInfo False LoadAllTargets
1755 return ()
1756 where
1757 checkTarget :: Target -> InputT GHCi Bool
1758 checkTarget (Target (TargetModule m) _ _) = checkTargetModule m
1759 checkTarget (Target (TargetFile f _) _ _) = liftIO $ checkTargetFile f
1760
1761 checkTargetModule :: ModuleName -> InputT GHCi Bool
1762 checkTargetModule m = do
1763 hsc_env <- GHC.getSession
1764 result <- liftIO $
1765 Finder.findImportedModule hsc_env m (Just (fsLit "this"))
1766 case result of
1767 Found _ _ -> return True
1768 _ -> (liftIO $ putStrLn $
1769 "Module " ++ moduleNameString m ++ " not found") >> return False
1770
1771 checkTargetFile :: String -> IO Bool
1772 checkTargetFile f = do
1773 exists <- (doesFileExist f) :: IO Bool
1774 unless exists $ putStrLn $ "File " ++ f ++ " not found"
1775 return exists
1776
1777 -- | @:unadd@ command
1778 unAddModule :: [FilePath] -> InputT GHCi ()
1779 unAddModule files = do
1780 files' <- mapM expandPath files
1781 targets <- mapM (\m -> GHC.guessTarget m Nothing) files'
1782 mapM_ GHC.removeTarget [ tid | Target tid _ _ <- targets ]
1783 _ <- doLoadAndCollectInfo False LoadAllTargets
1784 return ()
1785
1786 -- | @:reload@ command
1787 reloadModule :: String -> InputT GHCi ()
1788 reloadModule m = void $ doLoadAndCollectInfo True loadTargets
1789 where
1790 loadTargets | null m = LoadAllTargets
1791 | otherwise = LoadUpTo (GHC.mkModuleName m)
1792
1793 reloadModuleDefer :: String -> InputT GHCi ()
1794 reloadModuleDefer = wrapDeferTypeErrors . reloadModule
1795
1796 -- | Load/compile targets and (optionally) collect module-info
1797 --
1798 -- This collects the necessary SrcSpan annotated type information (via
1799 -- 'collectInfo') required by the @:all-types@, @:loc-at@, @:type-at@,
1800 -- and @:uses@ commands.
1801 --
1802 -- Meta-info collection is not enabled by default and needs to be
1803 -- enabled explicitly via @:set +c@. The reason is that collecting
1804 -- the type-information for all sub-spans can be quite expensive, and
1805 -- since those commands are designed to be used by editors and
1806 -- tooling, it's useless to collect this data for normal GHCi
1807 -- sessions.
1808 doLoadAndCollectInfo :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
1809 doLoadAndCollectInfo retain_context howmuch = do
1810 doCollectInfo <- lift (isOptionSet CollectInfo)
1811
1812 doLoad retain_context howmuch >>= \case
1813 Succeeded | doCollectInfo -> do
1814 mod_summaries <- GHC.mgModSummaries <$> getModuleGraph
1815 loaded <- filterM GHC.isLoaded $ map GHC.ms_mod_name mod_summaries
1816 v <- mod_infos <$> getGHCiState
1817 !newInfos <- collectInfo v loaded
1818 modifyGHCiState (\st -> st { mod_infos = newInfos })
1819 return Succeeded
1820 flag -> return flag
1821
1822 doLoad :: Bool -> LoadHowMuch -> InputT GHCi SuccessFlag
1823 doLoad retain_context howmuch = do
1824 -- turn off breakpoints before we load: we can't turn them off later, because
1825 -- the ModBreaks will have gone away.
1826 lift discardActiveBreakPoints
1827
1828 lift resetLastErrorLocations
1829 -- Enable buffering stdout and stderr as we're compiling. Keeping these
1830 -- handles unbuffered will just slow the compilation down, especially when
1831 -- compiling in parallel.
1832 gbracket (liftIO $ do hSetBuffering stdout LineBuffering
1833 hSetBuffering stderr LineBuffering)
1834 (\_ ->
1835 liftIO $ do hSetBuffering stdout NoBuffering
1836 hSetBuffering stderr NoBuffering) $ \_ -> do
1837 ok <- trySuccess $ GHC.load howmuch
1838 afterLoad ok retain_context
1839 return ok
1840
1841
1842 afterLoad :: SuccessFlag
1843 -> Bool -- keep the remembered_ctx, as far as possible (:reload)
1844 -> InputT GHCi ()
1845 afterLoad ok retain_context = do
1846 lift revertCAFs -- always revert CAFs on load.
1847 lift discardTickArrays
1848 loaded_mods <- getLoadedModules
1849 modulesLoadedMsg ok loaded_mods
1850 lift $ setContextAfterLoad retain_context loaded_mods
1851
1852 setContextAfterLoad :: Bool -> [GHC.ModSummary] -> GHCi ()
1853 setContextAfterLoad keep_ctxt [] = do
1854 setContextKeepingPackageModules keep_ctxt []
1855 setContextAfterLoad keep_ctxt ms = do
1856 -- load a target if one is available, otherwise load the topmost module.
1857 targets <- GHC.getTargets
1858 case [ m | Just m <- map (findTarget ms) targets ] of
1859 [] ->
1860 let graph = GHC.mkModuleGraph ms
1861 graph' = flattenSCCs (GHC.topSortModuleGraph True graph Nothing)
1862 in load_this (last graph')
1863 (m:_) ->
1864 load_this m
1865 where
1866 findTarget mds t
1867 = case filter (`matches` t) mds of
1868 [] -> Nothing
1869 (m:_) -> Just m
1870
1871 summary `matches` Target (TargetModule m) _ _
1872 = GHC.ms_mod_name summary == m
1873 summary `matches` Target (TargetFile f _) _ _
1874 | Just f' <- GHC.ml_hs_file (GHC.ms_location summary) = f == f'
1875 _ `matches` _
1876 = False
1877
1878 load_this summary | m <- GHC.ms_mod summary = do
1879 is_interp <- GHC.moduleIsInterpreted m
1880 dflags <- getDynFlags
1881 let star_ok = is_interp && not (safeLanguageOn dflags)
1882 -- We import the module with a * iff
1883 -- - it is interpreted, and
1884 -- - -XSafe is off (it doesn't allow *-imports)
1885 let new_ctx | star_ok = [mkIIModule (GHC.moduleName m)]
1886 | otherwise = [mkIIDecl (GHC.moduleName m)]
1887 setContextKeepingPackageModules keep_ctxt new_ctx
1888
1889
1890 -- | Keep any package modules (except Prelude) when changing the context.
1891 setContextKeepingPackageModules
1892 :: Bool -- True <=> keep all of remembered_ctx
1893 -- False <=> just keep package imports
1894 -> [InteractiveImport] -- new context
1895 -> GHCi ()
1896
1897 setContextKeepingPackageModules keep_ctx trans_ctx = do
1898
1899 st <- getGHCiState
1900 let rem_ctx = remembered_ctx st
1901 new_rem_ctx <- if keep_ctx then return rem_ctx
1902 else keepPackageImports rem_ctx
1903 setGHCiState st{ remembered_ctx = new_rem_ctx,
1904 transient_ctx = filterSubsumed new_rem_ctx trans_ctx }
1905 setGHCContextFromGHCiState
1906
1907 -- | Filters a list of 'InteractiveImport', clearing out any home package
1908 -- imports so only imports from external packages are preserved. ('IIModule'
1909 -- counts as a home package import, because we are only able to bring a
1910 -- full top-level into scope when the source is available.)
1911 keepPackageImports :: [InteractiveImport] -> GHCi [InteractiveImport]
1912 keepPackageImports = filterM is_pkg_import
1913 where
1914 is_pkg_import :: InteractiveImport -> GHCi Bool
1915 is_pkg_import (IIModule _) = return False
1916 is_pkg_import (IIDecl d)
1917 = do e <- gtry $ GHC.findModule mod_name (fmap sl_fs $ ideclPkgQual d)
1918 case e :: Either SomeException Module of
1919 Left _ -> return False
1920 Right m -> return (not (isHomeModule m))
1921 where
1922 mod_name = unLoc (ideclName d)
1923
1924
1925 modulesLoadedMsg :: SuccessFlag -> [GHC.ModSummary] -> InputT GHCi ()
1926 modulesLoadedMsg ok mods = do
1927 dflags <- getDynFlags
1928 unqual <- GHC.getPrintUnqual
1929
1930 msg <- if gopt Opt_ShowLoadedModules dflags
1931 then do
1932 mod_names <- mapM mod_name mods
1933 let mod_commas
1934 | null mods = text "none."
1935 | otherwise = hsep (punctuate comma mod_names) <> text "."
1936 return $ status <> text ", modules loaded:" <+> mod_commas
1937 else do
1938 return $ status <> text ","
1939 <+> speakNOf (length mods) (text "module") <+> "loaded."
1940
1941 when (verbosity dflags > 0) $
1942 liftIO $ putStrLn $ showSDocForUser dflags unqual msg
1943 where
1944 status = case ok of
1945 Failed -> text "Failed"
1946 Succeeded -> text "Ok"
1947
1948 mod_name mod = do
1949 is_interpreted <- GHC.moduleIsBootOrNotObjectLinkable mod
1950 return $ if is_interpreted
1951 then ppr (GHC.ms_mod mod)
1952 else ppr (GHC.ms_mod mod)
1953 <+> parens (text $ normalise $ msObjFilePath mod)
1954 -- Fix #9887
1955
1956 -- | Run an 'ExceptT' wrapped 'GhcMonad' while handling source errors
1957 -- and printing 'throwE' strings to 'stderr'
1958 runExceptGhcMonad :: GHC.GhcMonad m => ExceptT SDoc m () -> m ()
1959 runExceptGhcMonad act = handleSourceError GHC.printException $
1960 either handleErr pure =<<
1961 runExceptT act
1962 where
1963 handleErr sdoc = do
1964 dflags <- getDynFlags
1965 liftIO . hPutStrLn stderr . showSDocForUser dflags alwaysQualify $ sdoc
1966
1967 -- | Inverse of 'runExceptT' for \"pure\" computations
1968 -- (c.f. 'except' for 'Except')
1969 exceptT :: Applicative m => Either e a -> ExceptT e m a
1970 exceptT = ExceptT . pure
1971
1972 makeHDL'
1973 :: forall backend
1974 . Backend backend
1975 => Proxy backend
1976 -> IORef ClashOpts
1977 -> [FilePath]
1978 -> InputT GHCi ()
1979 makeHDL' backend opts lst = go =<< case lst of
1980 srcs@(_:_) -> return srcs
1981 [] -> do
1982 modGraph <- GHC.getModuleGraph
1983 let sortedGraph = GHC.topSortModuleGraph False modGraph Nothing
1984 return $ case (reverse sortedGraph) of
1985 ((AcyclicSCC top) : _) -> maybeToList $ (GHC.ml_hs_file . GHC.ms_location) top
1986 _ -> []
1987 where
1988 go srcs = do
1989 dflags <- GHC.getSessionDynFlags
1990 goX dflags srcs `gfinally` recover dflags
1991
1992 goX dflags srcs = do
1993 -- Issue #439 step 1
1994 (dflagsX,_,_) <- parseDynamicFlagsCmdLine dflags
1995 [ noLoc "-fobject-code" -- For #439
1996 , noLoc "-fforce-recomp" -- Actually compile to object-code
1997 , noLoc "-keep-tmp-files" -- To prevent linker errors from
1998 -- multiple calls to :hdl command
1999 ]
2000 _ <- GHC.setSessionDynFlags dflagsX
2001 reloadModule ""
2002 -- Issue #439 step 2
2003 -- Unload any object files
2004 -- This fixes: https://github.com/clash-lang/clash-compiler/issues/439#issuecomment-522015868
2005 env <- GHC.getSession
2006 liftIO (unload env [])
2007 -- Finally generate the HDL
2008 makeHDL backend (return ()) opts srcs
2009
2010 recover dflags = do
2011 _ <- GHC.setSessionDynFlags dflags
2012 reloadModule ""
2013
2014 makeHDL
2015 :: forall backend m
2016 . (GHC.GhcMonad m, Backend backend)
2017 => Proxy backend
2018 -> GHC.Ghc ()
2019 -> IORef ClashOpts
2020 -> [FilePath]
2021 -> m ()
2022 makeHDL Proxy startAction optsRef srcs = do
2023 dflags <- GHC.getSessionDynFlags
2024 liftIO $ do startTime <- Clock.getCurrentTime
2025 opts0 <- readIORef optsRef
2026 let opts1 = opts0 { opt_color = fromGhcOverridingBool (useColor dflags) }
2027 iw = opt_intWidth opts1
2028 hdl = hdlKind backend
2029 -- determine whether `-outputdir` was used
2030 outputDir = do odir <- objectDir dflags
2031 hidir <- hiDir dflags
2032 sdir <- stubDir dflags
2033 ddir <- dumpDir dflags
2034 if all (== odir) [hidir,sdir,ddir]
2035 then Just odir
2036 else Nothing
2037 idirs = importPaths dflags
2038 opts2 = opts1 { opt_hdlDir = maybe outputDir Just (opt_hdlDir opts1)
2039 , opt_importPaths = idirs}
2040 backend = initBackend @backend opts2
2041
2042 checkMonoLocalBinds dflags
2043 checkImportDirs opts0 idirs
2044
2045 primDirs_ <- primDirs backend
2046
2047 forM_ srcs $ \src -> do
2048 -- Generate bindings:
2049 let dbs = reverse [p | PackageDB (PkgConfFile p) <- packageDBFlags dflags]
2050 (clashEnv, clashDesign) <- generateBindings opts2 startAction primDirs_ idirs dbs hdl src (Just dflags)
2051 let getMain = getMainTopEntity src clashDesign
2052 mainTopEntity <- traverse getMain (GHC.mainFunIs dflags)
2053 prepTime <- startTime `deepseq` designBindings clashDesign `deepseq` envTyConMap clashEnv `deepseq` Clock.getCurrentTime
2054 let prepStartDiff = reportTimeDiff prepTime startTime
2055 putStrLn $ "GHC+Clash: Loading modules cumulatively took " ++ prepStartDiff
2056
2057 -- Generate HDL:
2058 Clash.Driver.generateHDL
2059 clashEnv
2060 clashDesign
2061 (Just backend)
2062 (ghcTypeToHWType iw)
2063 ghcEvaluator
2064 evaluator
2065 mainTopEntity
2066 startTime
2067
2068 makeVHDL :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
2069 makeVHDL = makeHDL' (Proxy @VHDLState)
2070
2071 makeVerilog :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
2072 makeVerilog = makeHDL' (Proxy @VerilogState)
2073
2074 makeSystemVerilog :: IORef ClashOpts -> [FilePath] -> InputT GHCi ()
2075 makeSystemVerilog = makeHDL' (Proxy @SystemVerilogState)
2076
2077 -----------------------------------------------------------------------------
2078 -- | @:type@ command. See also Note [TcRnExprMode] in TcRnDriver.
2079
2080 typeOfExpr :: String -> InputT GHCi ()
2081 typeOfExpr str = handleSourceError GHC.printException $ do
2082 let (mode, expr_str) = case break isSpace str of
2083 ("+d", rest) -> (GHC.TM_Default, dropWhile isSpace rest)
2084 ("+v", rest) -> (GHC.TM_NoInst, dropWhile isSpace rest)
2085 _ -> (GHC.TM_Inst, str)
2086 ty <- GHC.exprType mode expr_str
2087 printForUser $ sep [text expr_str, nest 2 (dcolon <+> pprTypeForUser ty)]
2088
2089 -----------------------------------------------------------------------------
2090 -- | @:type-at@ command
2091
2092 typeAtCmd :: String -> InputT GHCi ()
2093 typeAtCmd str = runExceptGhcMonad $ do
2094 (span',sample) <- exceptT $ parseSpanArg str
2095 infos <- mod_infos <$> getGHCiState
2096 (info, ty) <- findType infos span' sample
2097 lift $ printForUserModInfo (modinfoInfo info)
2098 (sep [text sample,nest 2 (dcolon <+> ppr ty)])
2099
2100 -----------------------------------------------------------------------------
2101 -- | @:uses@ command
2102
2103 usesCmd :: String -> InputT GHCi ()
2104 usesCmd str = runExceptGhcMonad $ do
2105 (span',sample) <- exceptT $ parseSpanArg str
2106 infos <- mod_infos <$> getGHCiState
2107 uses <- findNameUses infos span' sample
2108 forM_ uses (liftIO . putStrLn . showSrcSpan)
2109
2110 -----------------------------------------------------------------------------
2111 -- | @:loc-at@ command
2112
2113 locAtCmd :: String -> InputT GHCi ()
2114 locAtCmd str = runExceptGhcMonad $ do
2115 (span',sample) <- exceptT $ parseSpanArg str
2116 infos <- mod_infos <$> getGHCiState
2117 (_,_,sp) <- findLoc infos span' sample
2118 liftIO . putStrLn . showSrcSpan $ sp
2119
2120 -----------------------------------------------------------------------------
2121 -- | @:all-types@ command
2122
2123 allTypesCmd :: String -> InputT GHCi ()
2124 allTypesCmd _ = runExceptGhcMonad $ do
2125 infos <- mod_infos <$> getGHCiState
2126 forM_ (M.elems infos) $ \mi ->
2127 forM_ (modinfoSpans mi) (lift . printSpan)
2128 where
2129 printSpan span'
2130 | Just ty <- spaninfoType span' = do
2131 df <- getDynFlags
2132 let tyInfo = unwords . words $
2133 showSDocForUser df alwaysQualify (pprTypeForUser ty)
2134 liftIO . putStrLn $
2135 showRealSrcSpan (spaninfoSrcSpan span') ++ ": " ++ tyInfo
2136 | otherwise = return ()
2137
2138 -----------------------------------------------------------------------------
2139 -- Helpers for locAtCmd/typeAtCmd/usesCmd
2140
2141 -- | Parse a span: <module-name/filepath> <sl> <sc> <el> <ec> <string>
2142 parseSpanArg :: String -> Either SDoc (RealSrcSpan,String)
2143 parseSpanArg s = do
2144 (fp,s0) <- readAsString (skipWs s)
2145 s0' <- skipWs1 s0
2146 (sl,s1) <- readAsInt s0'
2147 s1' <- skipWs1 s1
2148 (sc,s2) <- readAsInt s1'
2149 s2' <- skipWs1 s2
2150 (el,s3) <- readAsInt s2'
2151 s3' <- skipWs1 s3
2152 (ec,s4) <- readAsInt s3'
2153
2154 trailer <- case s4 of
2155 [] -> Right ""
2156 _ -> skipWs1 s4
2157
2158 let fs = mkFastString fp
2159 span' = mkRealSrcSpan (mkRealSrcLoc fs sl sc)
2160 (mkRealSrcLoc fs el ec)
2161
2162 return (span',trailer)
2163 where
2164 readAsInt :: String -> Either SDoc (Int,String)
2165 readAsInt "" = Left "Premature end of string while expecting Int"
2166 readAsInt s0 = case reads s0 of
2167 [s_rest] -> Right s_rest
2168 _ -> Left ("Couldn't read" <+> text (show s0) <+> "as Int")
2169
2170 readAsString :: String -> Either SDoc (String,String)
2171 readAsString s0
2172 | '"':_ <- s0 = case reads s0 of
2173 [s_rest] -> Right s_rest
2174 _ -> leftRes
2175 | s_rest@(_:_,_) <- breakWs s0 = Right s_rest
2176 | otherwise = leftRes
2177 where
2178 leftRes = Left ("Couldn't read" <+> text (show s0) <+> "as String")
2179
2180 skipWs1 :: String -> Either SDoc String
2181 skipWs1 (c:cs) | isWs c = Right (skipWs cs)
2182 skipWs1 s0 = Left ("Expected whitespace in" <+> text (show s0))
2183
2184 isWs = (`elem` [' ','\t'])
2185 skipWs = dropWhile isWs
2186 breakWs = break isWs
2187
2188
2189 -- | Pretty-print \"real\" 'SrcSpan's as
2190 -- @<filename>:(<line>,<col>)-(<line-end>,<col-end>)@
2191 -- while simply unpacking 'UnhelpfulSpan's
2192 showSrcSpan :: SrcSpan -> String
2193 showSrcSpan (UnhelpfulSpan s) = unpackFS s
2194 showSrcSpan (RealSrcSpan spn) = showRealSrcSpan spn
2195
2196 -- | Variant of 'showSrcSpan' for 'RealSrcSpan's
2197 showRealSrcSpan :: RealSrcSpan -> String
2198 showRealSrcSpan spn = concat [ fp, ":(", show sl, ",", show sc
2199 , ")-(", show el, ",", show ec, ")"
2200 ]
2201 where
2202 fp = unpackFS (srcSpanFile spn)
2203 sl = srcSpanStartLine spn
2204 sc = srcSpanStartCol spn
2205 el = srcSpanEndLine spn
2206 ec = srcSpanEndCol spn
2207
2208 -----------------------------------------------------------------------------
2209 -- | @:kind@ command
2210
2211 kindOfType :: Bool -> String -> InputT GHCi ()
2212 kindOfType norm str = handleSourceError GHC.printException $ do
2213 (ty, kind) <- GHC.typeKind norm str
2214 printForUser $ vcat [ text str <+> dcolon <+> pprTypeForUser kind
2215 , ppWhen norm $ equals <+> pprTypeForUser ty ]
2216
2217 -----------------------------------------------------------------------------
2218 -- :quit
2219
2220 quit :: String -> InputT GHCi Bool
2221 quit _ = return True
2222
2223
2224 -----------------------------------------------------------------------------
2225 -- :script
2226
2227 -- running a script file #1363
2228
2229 scriptCmd :: String -> InputT GHCi ()
2230 scriptCmd ws = do
2231 case words ws of
2232 [s] -> runScript s
2233 _ -> throwGhcException (CmdLineError "syntax: :script <filename>")
2234
2235 runScript :: String -- ^ filename
2236 -> InputT GHCi ()
2237 runScript filename = do
2238 filename' <- expandPath filename
2239 either_script <- liftIO $ tryIO (openFile filename' ReadMode)
2240 case either_script of
2241 Left _err -> throwGhcException (CmdLineError $ "IO error: \""++filename++"\" "
2242 ++(ioeGetErrorString _err))
2243 Right script -> do
2244 st <- getGHCiState
2245 let prog = progname st
2246 line = line_number st
2247 setGHCiState st{progname=filename',line_number=0}
2248 scriptLoop script
2249 liftIO $ hClose script
2250 new_st <- getGHCiState
2251 setGHCiState new_st{progname=prog,line_number=line}
2252 where scriptLoop script = do
2253 res <- runOneCommand handler $ fileLoop script
2254 case res of
2255 Nothing -> return ()
2256 Just s -> if s
2257 then scriptLoop script
2258 else return ()
2259
2260 -----------------------------------------------------------------------------
2261 -- :issafe
2262
2263 -- Displaying Safe Haskell properties of a module
2264
2265 isSafeCmd :: String -> InputT GHCi ()
2266 isSafeCmd m =
2267 case words m of
2268 [s] | looksLikeModuleName s -> do
2269 md <- lift $ lookupModule s
2270 isSafeModule md
2271 [] -> do md <- guessCurrentModule "issafe"
2272 isSafeModule md
2273 _ -> throwGhcException (CmdLineError "syntax: :issafe <module>")
2274
2275 isSafeModule :: Module -> InputT GHCi ()
2276 isSafeModule m = do
2277 mb_mod_info <- GHC.getModuleInfo m
2278 when (isNothing mb_mod_info)
2279 (throwGhcException $ CmdLineError $ "unknown module: " ++ mname)
2280
2281 dflags <- getDynFlags
2282 let iface = GHC.modInfoIface $ fromJust mb_mod_info
2283 when (isNothing iface)
2284 (throwGhcException $ CmdLineError $ "can't load interface file for module: " ++
2285 (GHC.moduleNameString $ GHC.moduleName m))
2286
2287 (msafe, pkgs) <- GHC.moduleTrustReqs m
2288 let trust = showPpr dflags $ getSafeMode $ GHC.mi_trust $ fromJust iface
2289 pkg = if packageTrusted dflags m then "trusted" else "untrusted"
2290 (good, bad) = tallyPkgs dflags pkgs
2291
2292 -- print info to user...
2293 liftIO $ putStrLn $ "Trust type is (Module: " ++ trust ++ ", Package: " ++ pkg ++ ")"
2294 liftIO $ putStrLn $ "Package Trust: " ++ (if packageTrustOn dflags then "On" else "Off")
2295 when (not $ S.null good)
2296 (liftIO $ putStrLn $ "Trusted package dependencies (trusted): " ++
2297 (intercalate ", " $ map (showPpr dflags) (S.toList good)))
2298 case msafe && S.null bad of
2299 True -> liftIO $ putStrLn $ mname ++ " is trusted!"
2300 False -> do
2301 when (not $ null bad)
2302 (liftIO $ putStrLn $ "Trusted package dependencies (untrusted): "
2303 ++ (intercalate ", " $ map (showPpr dflags) (S.toList bad)))
2304 liftIO $ putStrLn $ mname ++ " is NOT trusted!"
2305
2306 where
2307 mname = GHC.moduleNameString $ GHC.moduleName m
2308
2309 packageTrusted dflags md
2310 | thisPackage dflags == moduleUnitId md = True
2311 | otherwise = trusted $ getPackageDetails dflags (moduleUnitId md)
2312
2313 tallyPkgs dflags deps | not (packageTrustOn dflags) = (S.empty, S.empty)
2314 | otherwise = S.partition part deps
2315 where part pkg = trusted $ getInstalledPackageDetails dflags pkg
2316
2317 -----------------------------------------------------------------------------
2318 -- :browse
2319
2320 -- Browsing a module's contents
2321
2322 browseCmd :: Bool -> String -> InputT GHCi ()
2323 browseCmd bang m =
2324 case words m of
2325 ['*':s] | looksLikeModuleName s -> do
2326 md <- lift $ wantInterpretedModule s
2327 browseModule bang md False
2328 [s] | looksLikeModuleName s -> do
2329 md <- lift $ lookupModule s
2330 browseModule bang md True
2331 [] -> do md <- guessCurrentModule ("browse" ++ if bang then "!" else "")
2332 browseModule bang md True
2333 _ -> throwGhcException (CmdLineError "syntax: :browse <module>")
2334
2335 guessCurrentModule :: String -> InputT GHCi Module
2336 -- Guess which module the user wants to browse. Pick
2337 -- modules that are interpreted first. The most
2338 -- recently-added module occurs last, it seems.
2339 guessCurrentModule cmd
2340 = do imports <- GHC.getContext
2341 when (null imports) $ throwGhcException $
2342 CmdLineError (':' : cmd ++ ": no current module")
2343 case (head imports) of
2344 IIModule m -> GHC.findModule m Nothing
2345 IIDecl d -> GHC.findModule (unLoc (ideclName d))
2346 (fmap sl_fs $ ideclPkgQual d)
2347
2348 -- without bang, show items in context of their parents and omit children
2349 -- with bang, show class methods and data constructors separately, and
2350 -- indicate import modules, to aid qualifying unqualified names
2351 -- with sorted, sort items alphabetically
2352 browseModule :: Bool -> Module -> Bool -> InputT GHCi ()
2353 browseModule bang modl exports_only = do
2354 -- :browse reports qualifiers wrt current context
2355 unqual <- GHC.getPrintUnqual
2356
2357 mb_mod_info <- GHC.getModuleInfo modl
2358 case mb_mod_info of
2359 Nothing -> throwGhcException (CmdLineError ("unknown module: " ++
2360 GHC.moduleNameString (GHC.moduleName modl)))
2361 Just mod_info -> do
2362 dflags <- getDynFlags
2363 let names
2364 | exports_only = GHC.modInfoExports mod_info
2365 | otherwise = GHC.modInfoTopLevelScope mod_info
2366 `orElse` []
2367
2368 -- sort alphabetically name, but putting locally-defined
2369 -- identifiers first. We would like to improve this; see #1799.
2370 sorted_names = loc_sort local ++ occ_sort external
2371 where
2372 (local,external) = ASSERT( all isExternalName names )
2373 partition ((==modl) . nameModule) names
2374 occ_sort = sortBy (compare `on` nameOccName)
2375 -- try to sort by src location. If the first name in our list
2376 -- has a good source location, then they all should.
2377 loc_sort ns
2378 | n:_ <- ns, isGoodSrcSpan (nameSrcSpan n)
2379 = sortBy (compare `on` nameSrcSpan) ns
2380 | otherwise
2381 = occ_sort ns
2382
2383 mb_things <- mapM GHC.lookupName sorted_names
2384 let filtered_things = filterOutChildren (\t -> t) (catMaybes mb_things)
2385
2386 rdr_env <- GHC.getGRE
2387
2388 let things | bang = catMaybes mb_things
2389 | otherwise = filtered_things
2390 pretty | bang = pprTyThing showToHeader
2391 | otherwise = pprTyThingInContext showToHeader
2392
2393 labels [] = text "-- not currently imported"
2394 labels l = text $ intercalate "\n" $ map qualifier l
2395
2396 qualifier :: Maybe [ModuleName] -> String
2397 qualifier = maybe "-- defined locally"
2398 (("-- imported via "++) . intercalate ", "
2399 . map GHC.moduleNameString)
2400 importInfo = RdrName.getGRE_NameQualifier_maybes rdr_env
2401
2402 modNames :: [[Maybe [ModuleName]]]
2403 modNames = map (importInfo . GHC.getName) things
2404
2405 -- annotate groups of imports with their import modules
2406 -- the default ordering is somewhat arbitrary, so we group
2407 -- by header and sort groups; the names themselves should
2408 -- really come in order of source appearance.. (trac #1799)
2409 annotate mts = concatMap (\(m,ts)->labels m:ts)
2410 $ sortBy cmpQualifiers $ grp mts
2411 where cmpQualifiers =
2412 compare `on` (map (fmap (map moduleNameFS)) . fst)
2413 grp [] = []
2414 grp mts@((m,_):_) = (m,map snd g) : grp ng
2415 where (g,ng) = partition ((==m).fst) mts
2416
2417 let prettyThings, prettyThings' :: [SDoc]
2418 prettyThings = map pretty things
2419 prettyThings' | bang = annotate $ zip modNames prettyThings
2420 | otherwise = prettyThings
2421 liftIO $ putStrLn $ showSDocForUser dflags unqual (vcat prettyThings')
2422 -- ToDo: modInfoInstances currently throws an exception for
2423 -- package modules. When it works, we can do this:
2424 -- $$ vcat (map GHC.pprInstance (GHC.modInfoInstances mod_info))
2425
2426
2427 -----------------------------------------------------------------------------
2428 -- :module
2429
2430 -- Setting the module context. For details on context handling see
2431 -- "remembered_ctx" and "transient_ctx" in GhciMonad.
2432
2433 moduleCmd :: String -> GHCi ()
2434 moduleCmd str
2435 | all sensible strs = cmd
2436 | otherwise = throwGhcException (CmdLineError "syntax: :module [+/-] [*]M1 ... [*]Mn")
2437 where
2438 (cmd, strs) =
2439 case str of
2440 '+':stuff -> rest addModulesToContext stuff
2441 '-':stuff -> rest remModulesFromContext stuff
2442 stuff -> rest setContext stuff
2443
2444 rest op stuff = (op as bs, stuffs)
2445 where (as,bs) = partitionWith starred stuffs
2446 stuffs = words stuff
2447
2448 sensible ('*':m) = looksLikeModuleName m
2449 sensible m = looksLikeModuleName m
2450
2451 starred ('*':m) = Left (GHC.mkModuleName m)
2452 starred m = Right (GHC.mkModuleName m)
2453
2454
2455 -- -----------------------------------------------------------------------------
2456 -- Four ways to manipulate the context:
2457 -- (a) :module +<stuff>: addModulesToContext
2458 -- (b) :module -<stuff>: remModulesFromContext
2459 -- (c) :module <stuff>: setContext
2460 -- (d) import <module>...: addImportToContext
2461
2462 addModulesToContext :: [ModuleName] -> [ModuleName] -> GHCi ()
2463 addModulesToContext starred unstarred = restoreContextOnFailure $ do
2464 addModulesToContext_ starred unstarred
2465
2466 addModulesToContext_ :: [ModuleName] -> [ModuleName] -> GHCi ()
2467 addModulesToContext_ starred unstarred = do
2468 mapM_ addII (map mkIIModule starred ++ map mkIIDecl unstarred)
2469 setGHCContextFromGHCiState
2470
2471 remModulesFromContext :: [ModuleName] -> [ModuleName] -> GHCi ()
2472 remModulesFromContext starred unstarred = do
2473 -- we do *not* call restoreContextOnFailure here. If the user
2474 -- is trying to fix up a context that contains errors by removing
2475 -- modules, we don't want GHC to silently put them back in again.
2476 mapM_ rm (starred ++ unstarred)
2477 setGHCContextFromGHCiState
2478 where
2479 rm :: ModuleName -> GHCi ()
2480 rm str = do
2481 m <- moduleName <$> lookupModuleName str
2482 let filt = filter ((/=) m . iiModuleName)
2483 modifyGHCiState $ \st ->
2484 st { remembered_ctx = filt (remembered_ctx st)
2485 , transient_ctx = filt (transient_ctx st) }
2486
2487 setContext :: [ModuleName] -> [ModuleName] -> GHCi ()
2488 setContext starred unstarred = restoreContextOnFailure $ do
2489 modifyGHCiState $ \st -> st { remembered_ctx = [], transient_ctx = [] }
2490 -- delete the transient context
2491 addModulesToContext_ starred unstarred
2492
2493 addImportToContext :: String -> GHCi ()
2494 addImportToContext str = restoreContextOnFailure $ do
2495 idecl <- GHC.parseImportDecl str
2496 addII (IIDecl idecl) -- #5836
2497 setGHCContextFromGHCiState
2498
2499 -- Util used by addImportToContext and addModulesToContext
2500 addII :: InteractiveImport -> GHCi ()
2501 addII iidecl = do
2502 checkAdd iidecl
2503 modifyGHCiState $ \st ->
2504 st { remembered_ctx = addNotSubsumed iidecl (remembered_ctx st)
2505 , transient_ctx = filter (not . (iidecl `iiSubsumes`))
2506 (transient_ctx st)
2507 }
2508
2509 -- Sometimes we can't tell whether an import is valid or not until
2510 -- we finally call 'GHC.setContext'. e.g.
2511 --
2512 -- import System.IO (foo)
2513 --
2514 -- will fail because System.IO does not export foo. In this case we
2515 -- don't want to store the import in the context permanently, so we
2516 -- catch the failure from 'setGHCContextFromGHCiState' and set the
2517 -- context back to what it was.
2518 --
2519 -- See #6007
2520 --
2521 restoreContextOnFailure :: GHCi a -> GHCi a
2522 restoreContextOnFailure do_this = do
2523 st <- getGHCiState
2524 let rc = remembered_ctx st; tc = transient_ctx st
2525 do_this `gonException` (modifyGHCiState $ \st' ->
2526 st' { remembered_ctx = rc, transient_ctx = tc })
2527
2528 -- -----------------------------------------------------------------------------
2529 -- Validate a module that we want to add to the context
2530
2531 checkAdd :: InteractiveImport -> GHCi ()
2532 checkAdd ii = do
2533 dflags <- getDynFlags
2534 let safe = safeLanguageOn dflags
2535 case ii of
2536 IIModule modname
2537 | safe -> throwGhcException $ CmdLineError "can't use * imports with Safe Haskell"
2538 | otherwise -> wantInterpretedModuleName modname >> return ()
2539
2540 IIDecl d -> do
2541 let modname = unLoc (ideclName d)
2542 pkgqual = ideclPkgQual d
2543 m <- GHC.lookupModule modname (fmap sl_fs pkgqual)
2544 when safe $ do
2545 t <- GHC.isModuleTrusted m
2546 when (not t) $ throwGhcException $ ProgramError $ ""
2547
2548 -- -----------------------------------------------------------------------------
2549 -- Update the GHC API's view of the context
2550
2551 -- | Sets the GHC context from the GHCi state. The GHC context is
2552 -- always set this way, we never modify it incrementally.
2553 --
2554 -- We ignore any imports for which the ModuleName does not currently
2555 -- exist. This is so that the remembered_ctx can contain imports for
2556 -- modules that are not currently loaded, perhaps because we just did
2557 -- a :reload and encountered errors.
2558 --
2559 -- Prelude is added if not already present in the list. Therefore to
2560 -- override the implicit Prelude import you can say 'import Prelude ()'
2561 -- at the prompt, just as in Haskell source.
2562 --
2563 setGHCContextFromGHCiState :: GHCi ()
2564 setGHCContextFromGHCiState = do
2565 st <- getGHCiState
2566 -- re-use checkAdd to check whether the module is valid. If the
2567 -- module does not exist, we do *not* want to print an error
2568 -- here, we just want to silently keep the module in the context
2569 -- until such time as the module reappears again. So we ignore
2570 -- the actual exception thrown by checkAdd, using tryBool to
2571 -- turn it into a Bool.
2572 iidecls <- filterM (tryBool.checkAdd) (transient_ctx st ++ remembered_ctx st)
2573
2574 prel_iidecls <- getImplicitPreludeImports iidecls
2575 valid_prel_iidecls <- filterM (tryBool . checkAdd) prel_iidecls
2576
2577 extra_imports <- filterM (tryBool . checkAdd) (map IIDecl (extra_imports st))
2578
2579 GHC.setContext $ iidecls ++ extra_imports ++ valid_prel_iidecls
2580
2581
2582 getImplicitPreludeImports :: [InteractiveImport] -> GHCi [InteractiveImport]
2583 getImplicitPreludeImports iidecls = do
2584 -- allow :seti to override -XNoImplicitPrelude
2585 st <- getGHCiState
2586
2587 -- We add the prelude imports if there are no *-imports, and we also
2588 -- allow each prelude import to be subsumed by another explicit import
2589 -- of the same module. This means that you can override the prelude import
2590 -- with "import Prelude hiding (map)", for example.
2591 let prel_iidecls =
2592 if not (any isIIModule iidecls)
2593 then [ IIDecl imp
2594 | imp <- prelude_imports st
2595 , not (any (sameImpModule imp) iidecls) ]
2596 else []
2597
2598 return prel_iidecls
2599
2600 -- -----------------------------------------------------------------------------
2601 -- Utils on InteractiveImport
2602
2603 mkIIModule :: ModuleName -> InteractiveImport
2604 mkIIModule = IIModule
2605
2606 mkIIDecl :: ModuleName -> InteractiveImport
2607 mkIIDecl = IIDecl . simpleImportDecl
2608
2609 iiModules :: [InteractiveImport] -> [ModuleName]
2610 iiModules is = [m | IIModule m <- is]
2611
2612 isIIModule :: InteractiveImport -> Bool
2613 isIIModule (IIModule _) = True
2614 isIIModule _ = False
2615
2616 iiModuleName :: InteractiveImport -> ModuleName
2617 iiModuleName (IIModule m) = m
2618 iiModuleName (IIDecl d) = unLoc (ideclName d)
2619
2620 preludeModuleName :: ModuleName
2621 preludeModuleName = GHC.mkModuleName "Clash.Prelude"
2622
2623 sameImpModule :: ImportDecl GhcPs -> InteractiveImport -> Bool
2624 sameImpModule _ (IIModule _) = False -- we only care about imports here
2625 sameImpModule imp (IIDecl d) = unLoc (ideclName d) == unLoc (ideclName imp)
2626
2627 addNotSubsumed :: InteractiveImport
2628 -> [InteractiveImport] -> [InteractiveImport]
2629 addNotSubsumed i is
2630 | any (`iiSubsumes` i) is = is
2631 | otherwise = i : filter (not . (i `iiSubsumes`)) is
2632
2633 -- | @filterSubsumed is js@ returns the elements of @js@ not subsumed
2634 -- by any of @is@.
2635 filterSubsumed :: [InteractiveImport] -> [InteractiveImport]
2636 -> [InteractiveImport]
2637 filterSubsumed is js = filter (\j -> not (any (`iiSubsumes` j) is)) js
2638
2639 -- | Returns True if the left import subsumes the right one. Doesn't
2640 -- need to be 100% accurate, conservatively returning False is fine.
2641 -- (EXCEPT: (IIModule m) *must* subsume itself, otherwise a panic in
2642 -- plusProv will ensue (#5904))
2643 --
2644 -- Note that an IIModule does not necessarily subsume an IIDecl,
2645 -- because e.g. a module might export a name that is only available
2646 -- qualified within the module itself.
2647 --
2648 -- Note that 'import M' does not necessarily subsume 'import M(foo)',
2649 -- because M might not export foo and we want an error to be produced
2650 -- in that case.
2651 --
2652 iiSubsumes :: InteractiveImport -> InteractiveImport -> Bool
2653 iiSubsumes (IIModule m1) (IIModule m2) = m1==m2
2654 iiSubsumes (IIDecl d1) (IIDecl d2) -- A bit crude
2655 = unLoc (ideclName d1) == unLoc (ideclName d2)
2656 && ideclAs d1 == ideclAs d2
2657 && (not (ideclQualified d1) || ideclQualified d2)
2658 && (ideclHiding d1 `hidingSubsumes` ideclHiding d2)
2659 where
2660 _ `hidingSubsumes` Just (False,L _ []) = True
2661 Just (False, L _ xs) `hidingSubsumes` Just (False,L _ ys)
2662 = all (`elem` xs) ys
2663 h1 `hidingSubsumes` h2 = h1 == h2
2664 iiSubsumes _ _ = False
2665
2666
2667 ----------------------------------------------------------------------------
2668 -- :set
2669
2670 -- set options in the interpreter. Syntax is exactly the same as the
2671 -- ghc command line, except that certain options aren't available (-C,
2672 -- -E etc.)
2673 --
2674 -- This is pretty fragile: most options won't work as expected. ToDo:
2675 -- figure out which ones & disallow them.
2676
2677 setCmd :: String -> GHCi ()
2678 setCmd "" = showOptions False
2679 setCmd "-a" = showOptions True
2680 setCmd str
2681 = case getCmd str of
2682 Right ("args", rest) ->
2683 case toArgs rest of
2684 Left err -> liftIO (hPutStrLn stderr err)
2685 Right args -> setArgs args
2686 Right ("prog", rest) ->
2687 case toArgs rest of
2688 Right [prog] -> setProg prog
2689 _ -> liftIO (hPutStrLn stderr "syntax: :set prog <progname>")
2690
2691 Right ("prompt", rest) ->
2692 setPromptString setPrompt (dropWhile isSpace rest)
2693 "syntax: set prompt <string>"
2694 Right ("prompt-function", rest) ->
2695 setPromptFunc setPrompt $ dropWhile isSpace rest
2696 Right ("prompt-cont", rest) ->
2697 setPromptString setPromptCont (dropWhile isSpace rest)
2698 "syntax: :set prompt-cont <string>"
2699 Right ("prompt-cont-function", rest) ->
2700 setPromptFunc setPromptCont $ dropWhile isSpace rest
2701
2702 Right ("editor", rest) -> setEditor $ dropWhile isSpace rest
2703 Right ("stop", rest) -> setStop $ dropWhile isSpace rest
2704 _ -> case toArgs str of
2705 Left err -> liftIO (hPutStrLn stderr err)
2706 Right wds -> setOptions wds
2707
2708 setiCmd :: String -> GHCi ()
2709 setiCmd "" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags False
2710 setiCmd "-a" = GHC.getInteractiveDynFlags >>= liftIO . showDynFlags True
2711 setiCmd str =
2712 case toArgs str of
2713 Left err -> liftIO (hPutStrLn stderr err)
2714 Right wds -> newDynFlags True wds
2715
2716 showOptions :: Bool -> GHCi ()
2717 showOptions show_all
2718 = do st <- getGHCiState
2719 dflags <- getDynFlags
2720 let opts = options st
2721 liftIO $ putStrLn (showSDoc dflags (
2722 text "options currently set: " <>
2723 if null opts
2724 then text "none."
2725 else hsep (map (\o -> char '+' <> text (optToStr o)) opts)
2726 ))
2727 getDynFlags >>= liftIO . showDynFlags show_all
2728
2729
2730 showDynFlags :: Bool -> DynFlags -> IO ()
2731 showDynFlags show_all dflags = do
2732 showLanguages' show_all dflags
2733 putStrLn $ showSDoc dflags $
2734 text "GHCi-specific dynamic flag settings:" $$
2735 nest 2 (vcat (map (setting "-f" "-fno-" gopt) ghciFlags))
2736 putStrLn $ showSDoc dflags $
2737 text "other dynamic, non-language, flag settings:" $$
2738 nest 2 (vcat (map (setting "-f" "-fno-" gopt) others))
2739 putStrLn $ showSDoc dflags $
2740 text "warning settings:" $$
2741 nest 2 (vcat (map (setting "-W" "-Wno-" wopt) DynFlags.wWarningFlags))
2742 where
2743 setting prefix noPrefix test flag
2744 | quiet = empty
2745 | is_on = text prefix <> text name
2746 | otherwise = text noPrefix <> text name
2747 where name = flagSpecName flag
2748 f = flagSpecFlag flag
2749 is_on = test f dflags
2750 quiet = not show_all && test f default_dflags == is_on
2751
2752 llvmConfig = (llvmTargets dflags, llvmPasses dflags)
2753
2754 default_dflags = defaultDynFlags (settings dflags) llvmConfig
2755
2756 (ghciFlags,others) = partition (\f -> flagSpecFlag f `elem` flgs)
2757 DynFlags.fFlags
2758 flgs = [ Opt_PrintExplicitForalls
2759 , Opt_PrintExplicitKinds
2760 , Opt_PrintUnicodeSyntax
2761 , Opt_PrintBindResult
2762 , Opt_BreakOnException
2763 , Opt_BreakOnError
2764 , Opt_PrintEvldWithShow
2765 ]
2766
2767 setArgs, setOptions :: [String] -> GHCi ()
2768 setProg, setEditor, setStop :: String -> GHCi ()
2769
2770 setArgs args = do
2771 st <- getGHCiState
2772 wrapper <- mkEvalWrapper (progname st) args
2773 setGHCiState st { GhciMonad.args = args, evalWrapper = wrapper }
2774
2775 setProg prog = do
2776 st <- getGHCiState
2777 wrapper <- mkEvalWrapper prog (GhciMonad.args st)
2778 setGHCiState st { progname = prog, evalWrapper = wrapper }
2779
2780 setEditor cmd = modifyGHCiState (\st -> st { editor = cmd })
2781
2782 setStop str@(c:_) | isDigit c
2783 = do let (nm_str,rest) = break (not.isDigit) str
2784 nm = read nm_str
2785 st <- getGHCiState
2786 let old_breaks = breaks st
2787 if all ((/= nm) . fst) old_breaks
2788 then printForUser (text "Breakpoint" <+> ppr nm <+>
2789 text "does not exist")
2790 else do
2791 let new_breaks = map fn old_breaks
2792 fn (i,loc) | i == nm = (i,loc { onBreakCmd = dropWhile isSpace rest })
2793 | otherwise = (i,loc)
2794 setGHCiState st{ breaks = new_breaks }
2795 setStop cmd = modifyGHCiState (\st -> st { stop = cmd })
2796
2797 setPrompt :: PromptFunction -> GHCi ()
2798 setPrompt v = modifyGHCiState (\st -> st {prompt = v})
2799
2800 setPromptCont :: PromptFunction -> GHCi ()
2801 setPromptCont v = modifyGHCiState (\st -> st {prompt_cont = v})
2802
2803 setPromptFunc :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
2804 setPromptFunc fSetPrompt s = do
2805 -- We explicitly annotate the type of the expression to ensure
2806 -- that unsafeCoerce# is passed the exact type necessary rather
2807 -- than a more general one
2808 let exprStr = "(" ++ s ++ ") :: [String] -> Int -> IO String"
2809 (HValue funValue) <- GHC.compileExpr exprStr
2810 fSetPrompt (convertToPromptFunction $ unsafeCoerce funValue)
2811 where
2812 convertToPromptFunction :: ([String] -> Int -> IO String)
2813 -> PromptFunction
2814 convertToPromptFunction func = (\mods line -> liftIO $
2815 liftM text (func mods line))
2816
2817 setPromptString :: (PromptFunction -> GHCi ()) -> String -> String -> GHCi ()
2818 setPromptString fSetPrompt value err = do
2819 if null value
2820 then liftIO $ hPutStrLn stderr $ err
2821 else case value of
2822 ('\"':_) ->
2823 case reads value of
2824 [(value', xs)] | all isSpace xs ->
2825 setParsedPromptString fSetPrompt value'
2826 _ -> liftIO $ hPutStrLn stderr
2827 "Can't parse prompt string. Use Haskell syntax."
2828 _ ->
2829 setParsedPromptString fSetPrompt value
2830
2831 setParsedPromptString :: (PromptFunction -> GHCi ()) -> String -> GHCi ()
2832 setParsedPromptString fSetPrompt s = do
2833 case (checkPromptStringForErrors s) of
2834 Just err ->
2835 liftIO $ hPutStrLn stderr err
2836 Nothing ->
2837 fSetPrompt $ generatePromptFunctionFromString s
2838
2839 setOptions wds =
2840 do -- first, deal with the GHCi opts (+s, +t, etc.)
2841 let (plus_opts, minus_opts) = partitionWith isPlus wds
2842 mapM_ setOpt plus_opts
2843 -- then, dynamic flags
2844 when (not (null minus_opts)) $ newDynFlags False minus_opts
2845
2846 newDynFlags :: Bool -> [String] -> GHCi ()
2847 newDynFlags interactive_only minus_opts = do
2848 let lopts = map noLoc minus_opts
2849
2850 idflags0 <- GHC.getInteractiveDynFlags
2851 (idflags1, leftovers, warns) <- GHC.parseDynamicFlags idflags0 lopts
2852
2853 liftIO $ handleFlagWarnings idflags1 warns
2854 when (not $ null leftovers)
2855 (throwGhcException . CmdLineError
2856 $ "Some flags have not been recognized: "
2857 ++ (concat . intersperse ", " $ map unLoc leftovers))
2858
2859 when (interactive_only && packageFlagsChanged idflags1 idflags0) $ do
2860 liftIO $ hPutStrLn stderr "cannot set package flags with :seti; use :set"
2861 -- Load any new plugins
2862 hsc_env0 <- GHC.getSession
2863 idflags2 <- liftIO (initializePlugins hsc_env0 idflags1)
2864 GHC.setInteractiveDynFlags idflags2
2865 installInteractivePrint (interactivePrint idflags1) False
2866
2867 dflags0 <- getDynFlags
2868 when (not interactive_only) $ do
2869 (dflags1, _, _) <- liftIO $ GHC.parseDynamicFlags dflags0 lopts
2870 new_pkgs <- GHC.setProgramDynFlags dflags1
2871
2872 -- if the package flags changed, reset the context and link
2873 -- the new packages.
2874 hsc_env <- GHC.getSession
2875 let dflags2 = hsc_dflags hsc_env
2876 when (packageFlagsChanged dflags2 dflags0) $ do
2877 when (verbosity dflags2 > 0) $
2878 liftIO . putStrLn $
2879 "package flags have changed, resetting and loading new packages..."
2880 GHC.setTargets []
2881 _ <- GHC.load LoadAllTargets
2882 liftIO $ linkPackages hsc_env new_pkgs
2883 -- package flags changed, we can't re-use any of the old context
2884 setContextAfterLoad False []
2885 -- and copy the package state to the interactive DynFlags
2886 idflags <- GHC.getInteractiveDynFlags
2887 GHC.setInteractiveDynFlags
2888 idflags{ pkgState = pkgState dflags2
2889 , pkgDatabase = pkgDatabase dflags2
2890 , packageFlags = packageFlags dflags2 }
2891
2892 let ld0length = length $ ldInputs dflags0
2893 fmrk0length = length $ cmdlineFrameworks dflags0
2894
2895 newLdInputs = drop ld0length (ldInputs dflags2)
2896 newCLFrameworks = drop fmrk0length (cmdlineFrameworks dflags2)
2897
2898 hsc_env' = hsc_env { hsc_dflags =
2899 dflags2 { ldInputs = newLdInputs
2900 , cmdlineFrameworks = newCLFrameworks } }
2901
2902 when (not (null newLdInputs && null newCLFrameworks)) $
2903 liftIO $ linkCmdLineLibs hsc_env'
2904
2905 return ()
2906
2907
2908 unsetOptions :: String -> GHCi ()
2909 unsetOptions str
2910 = -- first, deal with the GHCi opts (+s, +t, etc.)
2911 let opts = words str
2912 (minus_opts, rest1) = partition isMinus opts
2913 (plus_opts, rest2) = partitionWith isPlus rest1
2914 (other_opts, rest3) = partition (`elem` map fst defaulters) rest2
2915
2916 defaulters =
2917 [ ("args" , setArgs default_args)
2918 , ("prog" , setProg default_progname)
2919 , ("prompt" , setPrompt default_prompt)
2920 , ("prompt-cont", setPromptCont default_prompt_cont)
2921 , ("editor" , liftIO findEditor >>= setEditor)
2922 , ("stop" , setStop default_stop)
2923 ]
2924
2925 no_flag ('-':'f':rest) = return ("-fno-" ++ rest)
2926 no_flag ('-':'X':rest) = return ("-XNo" ++ rest)
2927 no_flag f = throwGhcException (ProgramError ("don't know how to reverse " ++ f))
2928
2929 in if (not (null rest3))
2930 then liftIO (putStrLn ("unknown option: '" ++ head rest3 ++ "'"))
2931 else do
2932 mapM_ (fromJust.flip lookup defaulters) other_opts
2933
2934 mapM_ unsetOpt plus_opts
2935
2936 no_flags <- mapM no_flag minus_opts
2937 when (not (null no_flags)) $ newDynFlags False no_flags
2938
2939 isMinus :: String -> Bool
2940 isMinus ('-':_) = True
2941 isMinus _ = False
2942
2943 isPlus :: String -> Either String String
2944 isPlus ('+':opt) = Left opt
2945 isPlus other = Right other
2946
2947 setOpt, unsetOpt :: String -> GHCi ()
2948
2949 setOpt str
2950 = case strToGHCiOpt str of
2951 Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
2952 Just o -> setOption o
2953
2954 unsetOpt str
2955 = case strToGHCiOpt str of
2956 Nothing -> liftIO (putStrLn ("unknown option: '" ++ str ++ "'"))
2957 Just o -> unsetOption o
2958
2959 strToGHCiOpt :: String -> (Maybe GHCiOption)
2960 strToGHCiOpt "m" = Just Multiline
2961 strToGHCiOpt "s" = Just ShowTiming
2962 strToGHCiOpt "t" = Just ShowType
2963 strToGHCiOpt "r" = Just RevertCAFs
2964 strToGHCiOpt "c" = Just CollectInfo
2965 strToGHCiOpt _ = Nothing
2966
2967 optToStr :: GHCiOption -> String
2968 optToStr Multiline = "m"
2969 optToStr ShowTiming = "s"
2970 optToStr ShowType = "t"
2971 optToStr RevertCAFs = "r"
2972 optToStr CollectInfo = "c"
2973
2974
2975 -- ---------------------------------------------------------------------------
2976 -- :show
2977
2978 showCmd :: String -> GHCi ()
2979 showCmd "" = showOptions False
2980 showCmd "-a" = showOptions True
2981 showCmd str = do
2982 st <- getGHCiState
2983 dflags <- getDynFlags
2984
2985 let lookupCmd :: String -> Maybe (GHCi ())
2986 lookupCmd name = lookup name $ map (\(_,b,c) -> (b,c)) cmds
2987
2988 -- (show in help?, command name, action)
2989 action :: String -> GHCi () -> (Bool, String, GHCi ())
2990 action name m = (True, name, m)
2991
2992 hidden :: String -> GHCi () -> (Bool, String, GHCi ())
2993 hidden name m = (False, name, m)
2994
2995 cmds =
2996 [ action "args" $ liftIO $ putStrLn (show (GhciMonad.args st))
2997 , action "prog" $ liftIO $ putStrLn (show (progname st))
2998 , action "editor" $ liftIO $ putStrLn (show (editor st))
2999 , action "stop" $ liftIO $ putStrLn (show (stop st))
3000 , action "imports" $ showImports
3001 , action "modules" $ showModules
3002 , action "bindings" $ showBindings
3003 , action "linker" $ getDynFlags >>= liftIO . showLinkerState
3004 , action "breaks" $ showBkptTable
3005 , action "context" $ showContext
3006 , action "packages" $ showPackages
3007 , action "paths" $ showPaths
3008 , action "language" $ showLanguages
3009 , hidden "languages" $ showLanguages -- backwards compat
3010 , hidden "lang" $ showLanguages -- useful abbreviation
3011 , action "targets" $ showTargets
3012 ]
3013
3014 case words str of
3015 [w] | Just action <- lookupCmd w -> action
3016
3017 _ -> let helpCmds = [ text name | (True, name, _) <- cmds ]
3018 in throwGhcException $ CmdLineError $ showSDoc dflags
3019 $ hang (text "syntax:") 4
3020 $ hang (text ":show") 6
3021 $ brackets (fsep $ punctuate (text " |") helpCmds)
3022
3023 showiCmd :: String -> GHCi ()
3024 showiCmd str = do
3025 case words str of
3026 ["languages"] -> showiLanguages -- backwards compat
3027 ["language"] -> showiLanguages
3028 ["lang"] -> showiLanguages -- useful abbreviation
3029 _ -> throwGhcException (CmdLineError ("syntax: :showi language"))
3030
3031 showImports :: GHCi ()
3032 showImports = do
3033 st <- getGHCiState
3034 dflags <- getDynFlags
3035 let rem_ctx = reverse (remembered_ctx st)
3036 trans_ctx = transient_ctx st
3037
3038 show_one (IIModule star_m)
3039 = ":module +*" ++ moduleNameString star_m
3040 show_one (IIDecl imp) = showPpr dflags imp
3041
3042 prel_iidecls <- getImplicitPreludeImports (rem_ctx ++ trans_ctx)
3043
3044 let show_prel p = show_one p ++ " -- implicit"
3045 show_extra p = show_one (IIDecl p) ++ " -- fixed"
3046
3047 trans_comment s = s ++ " -- added automatically" :: String
3048 --
3049 liftIO $ mapM_ putStrLn (map show_one rem_ctx ++
3050 map (trans_comment . show_one) trans_ctx ++
3051 map show_prel prel_iidecls ++
3052 map show_extra (extra_imports st))
3053
3054 showModules :: GHCi ()
3055 showModules = do
3056 loaded_mods <- getLoadedModules
3057 -- we want *loaded* modules only, see #1734
3058 let show_one ms = do m <- GHC.showModule ms; liftIO (putStrLn m)
3059 mapM_ show_one loaded_mods
3060
3061 getLoadedModules :: GHC.GhcMonad m => m [GHC.ModSummary]
3062 getLoadedModules = do
3063 graph <- GHC.getModuleGraph
3064 filterM (GHC.isLoaded . GHC.ms_mod_name) (GHC.mgModSummaries graph)
3065
3066 showBindings :: GHCi ()
3067 showBindings = do
3068 bindings <- GHC.getBindings
3069 (insts, finsts) <- GHC.getInsts
3070 docs <- mapM makeDoc (reverse bindings)
3071 -- reverse so the new ones come last
3072 let idocs = map GHC.pprInstanceHdr insts
3073 fidocs = map GHC.pprFamInst finsts
3074 mapM_ printForUserPartWay (docs ++ idocs ++ fidocs)
3075 where
3076 makeDoc (AnId i) = pprTypeAndContents i
3077 makeDoc tt = do
3078 mb_stuff <- GHC.getInfo False (getName tt)
3079 return $ maybe (text "") pprTT mb_stuff
3080
3081 pprTT :: (TyThing, Fixity, [GHC.ClsInst], [GHC.FamInst], SDoc) -> SDoc
3082 pprTT (thing, fixity, _cls_insts, _fam_insts, _docs)
3083 = pprTyThing showToHeader thing
3084 $$ show_fixity
3085 where
3086 show_fixity
3087 | fixity == GHC.defaultFixity = empty
3088 | otherwise = ppr fixity <+> ppr (GHC.getName thing)
3089
3090
3091 printTyThing :: TyThing -> GHCi ()
3092 printTyThing tyth = printForUser (pprTyThing showToHeader tyth)
3093
3094 showBkptTable :: GHCi ()
3095 showBkptTable = do
3096 st <- getGHCiState
3097 printForUser $ prettyLocations (breaks st)
3098
3099 showContext :: GHCi ()
3100 showContext = do
3101 resumes <- GHC.getResumeContext
3102 printForUser $ vcat (map pp_resume (reverse resumes))
3103 where
3104 pp_resume res =
3105 ptext (sLit "--> ") <> text (GHC.resumeStmt res)
3106 $$ nest 2 (pprStopped res)
3107
3108 pprStopped :: GHC.Resume -> SDoc
3109 pprStopped res =
3110 ptext (sLit "Stopped in")
3111 <+> ((case mb_mod_name of
3112 Nothing -> empty
3113 Just mod_name -> text (moduleNameString mod_name) <> char '.')
3114 <> text (GHC.resumeDecl res))
3115 <> char ',' <+> ppr (GHC.resumeSpan res)
3116 where
3117 mb_mod_name = moduleName <$> GHC.breakInfo_module <$> GHC.resumeBreakInfo res
3118
3119 showPackages :: GHCi ()
3120 showPackages = do
3121 dflags <- getDynFlags
3122 let pkg_flags = packageFlags dflags
3123 liftIO $ putStrLn $ showSDoc dflags $
3124 text ("active package flags:"++if null pkg_flags then " none" else "") $$
3125 nest 2 (vcat (map pprFlag pkg_flags))
3126
3127 showPaths :: GHCi ()
3128 showPaths = do
3129 dflags <- getDynFlags
3130 liftIO $ do
3131 cwd <- getCurrentDirectory
3132 putStrLn $ showSDoc dflags $
3133 text "current working directory: " $$
3134 nest 2 (text cwd)
3135 let ipaths = importPaths dflags
3136 putStrLn $ showSDoc dflags $
3137 text ("module import search paths:"++if null ipaths then " none" else "") $$
3138 nest 2 (vcat (map text ipaths))
3139
3140 showLanguages :: GHCi ()
3141 showLanguages = getDynFlags >>= liftIO . showLanguages' False
3142
3143 showiLanguages :: GHCi ()
3144 showiLanguages = GHC.getInteractiveDynFlags >>= liftIO . showLanguages' False
3145
3146 showLanguages' :: Bool -> DynFlags -> IO ()
3147 showLanguages' show_all dflags =
3148 putStrLn $ showSDoc dflags $ vcat
3149 [ text "base language is: " <>
3150 case language dflags of
3151 Nothing -> text "Haskell2010"
3152 Just Haskell98 -> text "Haskell98"
3153 Just Haskell2010 -> text "Haskell2010"
3154 , (if show_all then text "all active language options:"
3155 else text "with the following modifiers:") $$
3156 nest 2 (vcat (map (setting xopt) DynFlags.xFlags))
3157 ]
3158 where
3159 setting test flag
3160 | quiet = empty
3161 | is_on = text "-X" <> text name
3162 | otherwise = text "-XNo" <> text name
3163 where name = flagSpecName flag
3164 f = flagSpecFlag flag
3165 is_on = test f dflags
3166 quiet = not show_all && test f default_dflags == is_on
3167
3168 llvmConfig = (llvmTargets dflags, llvmPasses dflags)
3169
3170 default_dflags =
3171 defaultDynFlags (settings dflags) llvmConfig `lang_set`
3172 case language dflags of
3173 Nothing -> Just Haskell2010
3174 other -> other
3175
3176 showTargets :: GHCi ()
3177 showTargets = mapM_ showTarget =<< GHC.getTargets
3178 where
3179 showTarget :: Target -> GHCi ()
3180 showTarget (Target (TargetFile f _) _ _) = liftIO (putStrLn f)
3181 showTarget (Target (TargetModule m) _ _) =
3182 liftIO (putStrLn $ moduleNameString m)
3183
3184 -- -----------------------------------------------------------------------------
3185 -- Completion
3186
3187 completeCmd :: String -> GHCi ()
3188 completeCmd argLine0 = case parseLine argLine0 of
3189 Just ("repl", resultRange, left) -> do
3190 (unusedLine,compls) <- ghciCompleteWord (reverse left,"")
3191 let compls' = takeRange resultRange compls
3192 liftIO . putStrLn $ unwords [ show (length compls'), show (length compls), show (reverse unusedLine) ]
3193 forM_ (takeRange resultRange compls) $ \(Completion r _ _) -> do
3194 liftIO $ print r
3195 _ -> throwGhcException (CmdLineError "Syntax: :complete repl [<range>] <quoted-string-to-complete>")
3196 where
3197 parseLine argLine
3198 | null argLine = Nothing
3199 | null rest1 = Nothing
3200 | otherwise = (,,) dom <$> resRange <*> s
3201 where
3202 (dom, rest1) = breakSpace argLine
3203 (rng, rest2) = breakSpace rest1
3204 resRange | head rest1 == '"' = parseRange ""
3205 | otherwise = parseRange rng
3206 s | head rest1 == '"' = readMaybe rest1 :: Maybe String
3207 | otherwise = readMaybe rest2
3208 breakSpace = fmap (dropWhile isSpace) . break isSpace
3209
3210 takeRange (lb,ub) = maybe id (drop . pred) lb . maybe id take ub
3211
3212 -- syntax: [n-][m] with semantics "drop (n-1) . take m"
3213 parseRange :: String -> Maybe (Maybe Int,Maybe Int)
3214 parseRange s = case span isDigit s of
3215 (_, "") ->
3216 -- upper limit only
3217 Just (Nothing, bndRead s)
3218 (s1, '-' : s2)
3219 | all isDigit s2 ->
3220 Just (bndRead s1, bndRead s2)
3221 _ ->
3222 Nothing
3223 where
3224 bndRead x = if null x then Nothing else Just (read x)
3225
3226
3227
3228 completeGhciCommand, completeMacro, completeIdentifier, completeModule,
3229 completeSetModule, completeSeti, completeShowiOptions,
3230 completeHomeModule, completeSetOptions, completeShowOptions,
3231 completeHomeModuleOrFile, completeExpression
3232 :: CompletionFunc GHCi
3233
3234 -- | Provide completions for last word in a given string.
3235 --
3236 -- Takes a tuple of two strings. First string is a reversed line to be
3237 -- completed. Second string is likely unused, 'completeCmd' always passes an
3238 -- empty string as second item in tuple.
3239 ghciCompleteWord :: CompletionFunc GHCi
3240 ghciCompleteWord line@(left,_) = case firstWord of
3241 -- If given string starts with `:` colon, and there is only one following
3242 -- word then provide REPL command completions. If there is more than one
3243 -- word complete either filename or builtin ghci commands or macros.
3244 ':':cmd | null rest -> completeGhciCommand line
3245 | otherwise -> do
3246 completion <- lookupCompletion cmd
3247 completion line
3248 -- If given string starts with `import` keyword provide module name
3249 -- completions
3250 "import" -> completeModule line
3251 -- otherwise provide identifier completions
3252 _ -> completeExpression line
3253 where
3254 (firstWord,rest) = break isSpace $ dropWhile isSpace $ reverse left
3255 lookupCompletion ('!':_) = return completeFilename
3256 lookupCompletion c = do
3257 maybe_cmd <- lookupCommand' c
3258 case maybe_cmd of
3259 Just cmd -> return (cmdCompletionFunc cmd)
3260 Nothing -> return completeFilename
3261
3262 completeGhciCommand = wrapCompleter " " $ \w -> do
3263 macros <- ghci_macros <$> getGHCiState
3264 cmds <- ghci_commands `fmap` getGHCiState
3265 let macro_names = map (':':) . map cmdName $ macros
3266 let command_names = map (':':) . map cmdName $ filter (not . cmdHidden) cmds
3267 let{ candidates = case w of
3268 ':' : ':' : _ -> map (':':) command_names
3269 _ -> nub $ macro_names ++ command_names }
3270 return $ filter (w `isPrefixOf`) candidates
3271
3272 completeMacro = wrapIdentCompleter $ \w -> do
3273 cmds <- ghci_macros <$> getGHCiState
3274 return (filter (w `isPrefixOf`) (map cmdName cmds))
3275
3276 completeIdentifier line@(left, _) =
3277 -- Note: `left` is a reversed input
3278 case left of
3279 (x:_) | isSymbolChar x -> wrapCompleter (specials ++ spaces) complete line
3280 _ -> wrapIdentCompleter complete line
3281 where
3282 complete w = do
3283 rdrs <- GHC.getRdrNamesInScope
3284 dflags <- GHC.getSessionDynFlags
3285 return (filter (w `isPrefixOf`) (map (showPpr dflags) rdrs))
3286
3287 completeModule = wrapIdentCompleter $ \w -> do
3288 dflags <- GHC.getSessionDynFlags
3289 let pkg_mods = allVisibleModules dflags
3290 loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
3291 return $ filter (w `isPrefixOf`)
3292 $ map (showPpr dflags) $ loaded_mods ++ pkg_mods
3293
3294 completeSetModule = wrapIdentCompleterWithModifier "+-" $ \m w -> do
3295 dflags <- GHC.getSessionDynFlags
3296 modules <- case m of
3297 Just '-' -> do
3298 imports <- GHC.getContext
3299 return $ map iiModuleName imports
3300 _ -> do
3301 let pkg_mods = allVisibleModules dflags
3302 loaded_mods <- liftM (map GHC.ms_mod_name) getLoadedModules
3303 return $ loaded_mods ++ pkg_mods
3304 return $ filter (w `isPrefixOf`) $ map (showPpr dflags) modules
3305
3306 completeHomeModule = wrapIdentCompleter listHomeModules
3307
3308 listHomeModules :: String -> GHCi [String]
3309 listHomeModules w = do
3310 g <- GHC.getModuleGraph
3311 let home_mods = map GHC.ms_mod_name (GHC.mgModSummaries g)
3312 dflags <- getDynFlags
3313 return $ sort $ filter (w `isPrefixOf`)
3314 $ map (showPpr dflags) home_mods
3315
3316 completeSetOptions = wrapCompleter flagWordBreakChars $ \w -> do
3317 return (filter (w `isPrefixOf`) opts)
3318 where opts = "args":"prog":"prompt":"prompt-cont":"prompt-function":
3319 "prompt-cont-function":"editor":"stop":flagList
3320 flagList = map head $ group $ sort allNonDeprecatedFlags
3321
3322 completeSeti = wrapCompleter flagWordBreakChars $ \w -> do
3323 return (filter (w `isPrefixOf`) flagList)
3324 where flagList = map head $ group $ sort allNonDeprecatedFlags
3325
3326 completeShowOptions = wrapCompleter flagWordBreakChars $ \w -> do
3327 return (filter (w `isPrefixOf`) opts)
3328 where opts = ["args", "prog", "editor", "stop",
3329 "modules", "bindings", "linker", "breaks",
3330 "context", "packages", "paths", "language", "imports"]
3331
3332 completeShowiOptions = wrapCompleter flagWordBreakChars $ \w -> do
3333 return (filter (w `isPrefixOf`) ["language"])
3334
3335 completeHomeModuleOrFile = completeWord Nothing filenameWordBreakChars
3336 $ unionComplete (fmap (map simpleCompletion) . listHomeModules)
3337 listFiles
3338
3339 unionComplete :: Monad m => (a -> m [b]) -> (a -> m [b]) -> a -> m [b]
3340 unionComplete f1 f2 line = do
3341 cs1 <- f1 line
3342 cs2 <- f2 line
3343 return (cs1 ++ cs2)
3344
3345 wrapCompleter :: String -> (String -> GHCi [String]) -> CompletionFunc GHCi
3346 wrapCompleter breakChars fun = completeWord Nothing breakChars
3347 $ fmap (map simpleCompletion . nubSort) . fun
3348
3349 wrapIdentCompleter :: (String -> GHCi [String]) -> CompletionFunc GHCi
3350 wrapIdentCompleter = wrapCompleter word_break_chars
3351
3352 wrapIdentCompleterWithModifier :: String -> (Maybe Char -> String -> GHCi [String]) -> CompletionFunc GHCi
3353 wrapIdentCompleterWithModifier modifChars fun = completeWordWithPrev Nothing word_break_chars
3354 $ \rest -> fmap (map simpleCompletion . nubSort) . fun (getModifier rest)
3355 where
3356 getModifier = find (`elem` modifChars)
3357
3358 -- | Return a list of visible module names for autocompletion.
3359 -- (NB: exposed != visible)
3360 allVisibleModules :: DynFlags -> [ModuleName]
3361 allVisibleModules dflags = listVisibleModuleNames dflags
3362
3363 completeExpression = completeQuotedWord (Just '\\') "\"" listFiles
3364 completeIdentifier
3365
3366
3367 -- -----------------------------------------------------------------------------
3368 -- commands for debugger
3369
3370 sprintCmd, printCmd, forceCmd :: String -> GHCi ()
3371 sprintCmd = pprintCommand False False
3372 printCmd = pprintCommand True False
3373 forceCmd = pprintCommand False True
3374
3375 pprintCommand :: Bool -> Bool -> String -> GHCi ()
3376 pprintCommand bind force str = do
3377 pprintClosureCommand bind force str
3378
3379 stepCmd :: String -> GHCi ()
3380 stepCmd arg = withSandboxOnly ":step" $ step arg
3381 where
3382 step [] = doContinue (const True) GHC.SingleStep
3383 step expression = runStmt expression GHC.SingleStep >> return ()
3384
3385 stepLocalCmd :: String -> GHCi ()
3386 stepLocalCmd arg = withSandboxOnly ":steplocal" $ step arg
3387 where
3388 step expr
3389 | not (null expr) = stepCmd expr
3390 | otherwise = do
3391 mb_span <- getCurrentBreakSpan
3392 case mb_span of
3393 Nothing -> stepCmd []
3394 Just loc -> do
3395 md <- fromJust <$> getCurrentBreakModule
3396 current_toplevel_decl <- enclosingTickSpan md loc
3397 doContinue (`isSubspanOf` RealSrcSpan current_toplevel_decl) GHC.SingleStep
3398
3399 stepModuleCmd :: String -> GHCi ()
3400 stepModuleCmd arg = withSandboxOnly ":stepmodule" $ step arg
3401 where
3402 step expr
3403 | not (null expr) = stepCmd expr
3404 | otherwise = do
3405 mb_span <- getCurrentBreakSpan
3406 case mb_span of
3407 Nothing -> stepCmd []
3408 Just pan -> do
3409 let f some_span = srcSpanFileName_maybe pan == srcSpanFileName_maybe some_span
3410 doContinue f GHC.SingleStep
3411
3412 -- | Returns the span of the largest tick containing the srcspan given
3413 enclosingTickSpan :: Module -> SrcSpan -> GHCi RealSrcSpan
3414 enclosingTickSpan _ (UnhelpfulSpan _) = panic "enclosingTickSpan UnhelpfulSpan"
3415 enclosingTickSpan md (RealSrcSpan src) = do
3416 ticks <- getTickArray md
3417 let line = srcSpanStartLine src
3418 ASSERT(inRange (bounds ticks) line) do
3419 let enclosing_spans = [ pan | (_,pan) <- ticks ! line
3420 , realSrcSpanEnd pan >= realSrcSpanEnd src]
3421 return . head . sortBy leftmostLargestRealSrcSpan $ enclosing_spans
3422 where
3423
3424 leftmostLargestRealSrcSpan :: RealSrcSpan -> RealSrcSpan -> Ordering
3425 leftmostLargestRealSrcSpan a b =
3426 (realSrcSpanStart a `compare` realSrcSpanStart b)
3427 `thenCmp`
3428 (realSrcSpanEnd b `compare` realSrcSpanEnd a)
3429
3430 traceCmd :: String -> GHCi ()
3431 traceCmd arg
3432 = withSandboxOnly ":trace" $ tr arg
3433 where
3434 tr [] = doContinue (const True) GHC.RunAndLogSteps
3435 tr expression = runStmt expression GHC.RunAndLogSteps >> return ()
3436
3437 continueCmd :: String -> GHCi ()
3438 continueCmd = noArgs $ withSandboxOnly ":continue" $ doContinue (const True) GHC.RunToCompletion
3439
3440 -- doContinue :: SingleStep -> GHCi ()
3441 doContinue :: (SrcSpan -> Bool) -> SingleStep -> GHCi ()
3442 doContinue pre step = do
3443 runResult <- resume pre step
3444 _ <- afterRunStmt pre runResult
3445 return ()
3446
3447 abandonCmd :: String -> GHCi ()
3448 abandonCmd = noArgs $ withSandboxOnly ":abandon" $ do
3449 b <- GHC.abandon -- the prompt will change to indicate the new context
3450 when (not b) $ liftIO $ putStrLn "There is no computation running."
3451
3452 deleteCmd :: String -> GHCi ()
3453 deleteCmd argLine = withSandboxOnly ":delete" $ do
3454 deleteSwitch $ words argLine
3455 where
3456 deleteSwitch :: [String] -> GHCi ()
3457 deleteSwitch [] =
3458 liftIO $ putStrLn "The delete command requires at least one argument."
3459 -- delete all break points
3460 deleteSwitch ("*":_rest) = discardActiveBreakPoints
3461 deleteSwitch idents = do
3462 mapM_ deleteOneBreak idents
3463 where
3464 deleteOneBreak :: String -> GHCi ()
3465 deleteOneBreak str
3466 | all isDigit str = deleteBreak (read str)
3467 | otherwise = return ()
3468
3469 historyCmd :: String -> GHCi ()
3470 historyCmd arg
3471 | null arg = history 20
3472 | all isDigit arg = history (read arg)
3473 | otherwise = liftIO $ putStrLn "Syntax: :history [num]"
3474 where
3475 history num = do
3476 resumes <- GHC.getResumeContext
3477 case resumes of
3478 [] -> liftIO $ putStrLn "Not stopped at a breakpoint"
3479 (r:_) -> do
3480 let hist = GHC.resumeHistory r
3481 (took,rest) = splitAt num hist
3482 case hist of
3483 [] -> liftIO $ putStrLn $
3484 "Empty history. Perhaps you forgot to use :trace?"
3485 _ -> do
3486 pans <- mapM GHC.getHistorySpan took
3487 let nums = map (printf "-%-3d:") [(1::Int)..]
3488 names = map GHC.historyEnclosingDecls took
3489 printForUser (vcat(zipWith3
3490 (\x y z -> x <+> y <+> z)
3491 (map text nums)
3492 (map (bold . hcat . punctuate colon . map text) names)
3493 (map (parens . ppr) pans)))
3494 liftIO $ putStrLn $ if null rest then "<end of history>" else "..."
3495
3496 bold :: SDoc -> SDoc
3497 bold c | do_bold = text start_bold <> c <> text end_bold
3498 | otherwise = c
3499
3500 backCmd :: String -> GHCi ()
3501 backCmd arg
3502 | null arg = back 1
3503 | all isDigit arg = back (read arg)
3504 | otherwise = liftIO $ putStrLn "Syntax: :back [num]"
3505 where
3506 back num = withSandboxOnly ":back" $ do
3507 (names, _, pan, _) <- GHC.back num
3508 printForUser $ ptext (sLit "Logged breakpoint at") <+> ppr pan
3509 printTypeOfNames names
3510 -- run the command set with ":set stop <cmd>"
3511 st <- getGHCiState
3512 enqueueCommands [stop st]
3513
3514 forwardCmd :: String -> GHCi ()
3515 forwardCmd arg
3516 | null arg = forward 1
3517 | all isDigit arg = forward (read arg)
3518 | otherwise = liftIO $ putStrLn "Syntax: :back [num]"
3519 where
3520 forward num = withSandboxOnly ":forward" $ do
3521 (names, ix, pan, _) <- GHC.forward num
3522 printForUser $ (if (ix == 0)
3523 then ptext (sLit "Stopped at")
3524 else ptext (sLit "Logged breakpoint at")) <+> ppr pan
3525 printTypeOfNames names
3526 -- run the command set with ":set stop <cmd>"
3527 st <- getGHCiState
3528 enqueueCommands [stop st]
3529
3530 -- handle the "break" command
3531 breakCmd :: String -> GHCi ()
3532 breakCmd argLine = withSandboxOnly ":break" $ breakSwitch $ words argLine
3533
3534 breakSwitch :: [String] -> GHCi ()
3535 breakSwitch [] = do
3536 liftIO $ putStrLn "The break command requires at least one argument."
3537 breakSwitch (arg1:rest)
3538 | looksLikeModuleName arg1 && not (null rest) = do
3539 md <- wantInterpretedModule arg1
3540 breakByModule md rest
3541 | all isDigit arg1 = do
3542 imports <- GHC.getContext
3543 case iiModules imports of
3544 (mn : _) -> do
3545 md <- lookupModuleName mn
3546 breakByModuleLine md (read arg1) rest
3547 [] -> do
3548 liftIO $ putStrLn "No modules are loaded with debugging support."
3549 | otherwise = do -- try parsing it as an identifier
3550 wantNameFromInterpretedModule noCanDo arg1 $ \name -> do
3551 maybe_info <- GHC.getModuleInfo (GHC.nameModule name)
3552 case maybe_info of
3553 Nothing -> noCanDo name (ptext (sLit "cannot get module info"))
3554 Just minf ->
3555 ASSERT( isExternalName name )
3556 findBreakAndSet (GHC.nameModule name) $
3557 findBreakForBind name (GHC.modInfoModBreaks minf)
3558 where
3559 noCanDo n why = printForUser $
3560 text "cannot set breakpoint on " <> ppr n <> text ": " <> why
3561
3562 breakByModule :: Module -> [String] -> GHCi ()
3563 breakByModule md (arg1:rest)
3564 | all isDigit arg1 = do -- looks like a line number
3565 breakByModuleLine md (read arg1) rest
3566 breakByModule _ _
3567 = breakSyntax
3568
3569 breakByModuleLine :: Module -> Int -> [String] -> GHCi ()
3570 breakByModuleLine md line args
3571 | [] <- args = findBreakAndSet md $ maybeToList . findBreakByLine line
3572 | [col] <- args, all isDigit col =
3573 findBreakAndSet md $ maybeToList . findBreakByCoord Nothing (line, read col)
3574 | otherwise = breakSyntax
3575
3576 breakSyntax :: a
3577 breakSyntax = throwGhcException (CmdLineError "Syntax: :break [<mod>] <line> [<column>]")
3578
3579 findBreakAndSet :: Module -> (TickArray -> [(Int, RealSrcSpan)]) -> GHCi ()
3580 findBreakAndSet md lookupTickTree = do
3581 tickArray <- getTickArray md
3582 (breakArray, _) <- getModBreak md
3583 case lookupTickTree tickArray of
3584 [] -> liftIO $ putStrLn $ "No breakpoints found at that location."
3585 some -> mapM_ (breakAt breakArray) some
3586 where
3587 breakAt breakArray (tick, pan) = do
3588 setBreakFlag True breakArray tick
3589 (alreadySet, nm) <-
3590 recordBreak $ BreakLocation
3591 { breakModule = md
3592 , breakLoc = RealSrcSpan pan
3593 , breakTick = tick
3594 , onBreakCmd = ""
3595 }
3596 printForUser $
3597 text "Breakpoint " <> ppr nm <>
3598 if alreadySet
3599 then text " was already set at " <> ppr pan
3600 else text " activated at " <> ppr pan
3601
3602 -- When a line number is specified, the current policy for choosing
3603 -- the best breakpoint is this:
3604 -- - the leftmost complete subexpression on the specified line, or
3605 -- - the leftmost subexpression starting on the specified line, or
3606 -- - the rightmost subexpression enclosing the specified line
3607 --
3608 findBreakByLine :: Int -> TickArray -> Maybe (BreakIndex,RealSrcSpan)
3609 findBreakByLine line arr
3610 | not (inRange (bounds arr) line) = Nothing
3611 | otherwise =
3612 listToMaybe (sortBy (leftmostLargestRealSrcSpan `on` snd) comp) `mplus`
3613 listToMaybe (sortBy (compare `on` snd) incomp) `mplus`
3614 listToMaybe (sortBy (flip compare `on` snd) ticks)
3615 where
3616 ticks = arr ! line
3617
3618 starts_here = [ (ix,pan) | (ix, pan) <- ticks,
3619 GHC.srcSpanStartLine pan == line ]
3620
3621 (comp, incomp) = partition ends_here starts_here
3622 where ends_here (_,pan) = GHC.srcSpanEndLine pan == line
3623
3624 -- The aim is to find the breakpoints for all the RHSs of the
3625 -- equations corresponding to a binding. So we find all breakpoints
3626 -- for
3627 -- (a) this binder only (not a nested declaration)
3628 -- (b) that do not have an enclosing breakpoint
3629 findBreakForBind :: Name -> GHC.ModBreaks -> TickArray
3630 -> [(BreakIndex,RealSrcSpan)]
3631 findBreakForBind name modbreaks _ = filter (not . enclosed) ticks
3632 where
3633 ticks = [ (index, span)
3634 | (index, [n]) <- assocs (GHC.modBreaks_decls modbreaks),
3635 n == occNameString (nameOccName name),
3636 RealSrcSpan span <- [GHC.modBreaks_locs modbreaks ! index] ]
3637 enclosed (_,sp0) = any subspan ticks
3638 where subspan (_,sp) = sp /= sp0 &&
3639 realSrcSpanStart sp <= realSrcSpanStart sp0 &&
3640 realSrcSpanEnd sp0 <= realSrcSpanEnd sp
3641
3642 findBreakByCoord :: Maybe FastString -> (Int,Int) -> TickArray
3643 -> Maybe (BreakIndex,RealSrcSpan)
3644 findBreakByCoord mb_file (line, col) arr
3645 | not (inRange (bounds arr) line) = Nothing
3646 | otherwise =
3647 listToMaybe (sortBy (flip compare `on` snd) contains ++
3648 sortBy (compare `on` snd) after_here)
3649 where
3650 ticks = arr ! line
3651
3652 -- the ticks that span this coordinate
3653 contains = [ tick | tick@(_,pan) <- ticks, RealSrcSpan pan `spans` (line,col),
3654 is_correct_file pan ]
3655
3656 is_correct_file pan
3657 | Just f <- mb_file = GHC.srcSpanFile pan == f
3658 | otherwise = True
3659
3660 after_here = [ tick | tick@(_,pan) <- ticks,
3661 GHC.srcSpanStartLine pan == line,
3662 GHC.srcSpanStartCol pan >= col ]
3663
3664 -- For now, use ANSI bold on terminals that we know support it.
3665 -- Otherwise, we add a line of carets under the active expression instead.
3666 -- In particular, on Windows and when running the testsuite (which sets
3667 -- TERM to vt100 for other reasons) we get carets.
3668 -- We really ought to use a proper termcap/terminfo library.
3669 do_bold :: Bool
3670 do_bold = (`isPrefixOf` unsafePerformIO mTerm) `any` ["xterm", "linux"]
3671 where mTerm = System.Environment.getEnv "TERM"
3672 `catchIO` \_ -> return "TERM not set"
3673
3674 start_bold :: String
3675 start_bold = "\ESC[1m"
3676 end_bold :: String
3677 end_bold = "\ESC[0m"
3678
3679 -----------------------------------------------------------------------------
3680 -- :where
3681
3682 whereCmd :: String -> GHCi ()
3683 whereCmd = noArgs $ do
3684 mstrs <- getCallStackAtCurrentBreakpoint
3685 case mstrs of
3686 Nothing -> return ()
3687 Just strs -> liftIO $ putStrLn (renderStack strs)
3688
3689 -----------------------------------------------------------------------------
3690 -- :list
3691
3692 listCmd :: String -> InputT GHCi ()
3693 listCmd c = listCmd' c
3694
3695 listCmd' :: String -> InputT GHCi ()
3696 listCmd' "" = do
3697 mb_span <- lift getCurrentBreakSpan
3698 case mb_span of
3699 Nothing ->
3700 printForUser $ text "Not stopped at a breakpoint; nothing to list"
3701 Just (RealSrcSpan pan) ->
3702 listAround pan True
3703 Just pan@(UnhelpfulSpan _) ->
3704 do resumes <- GHC.getResumeContext
3705 case resumes of
3706 [] -> panic "No resumes"
3707 (r:_) ->
3708 do let traceIt = case GHC.resumeHistory r of
3709 [] -> text "rerunning with :trace,"
3710 _ -> empty
3711 doWhat = traceIt <+> text ":back then :list"
3712 printForUser (text "Unable to list source for" <+>
3713 ppr pan
3714 $$ text "Try" <+> doWhat)
3715 listCmd' str = list2 (words str)
3716
3717 list2 :: [String] -> InputT GHCi ()
3718 list2 [arg] | all isDigit arg = do
3719 imports <- GHC.getContext
3720 case iiModules imports of
3721 [] -> liftIO $ putStrLn "No module to list"
3722 (mn : _) -> do
3723 md <- lift $ lookupModuleName mn
3724 listModuleLine md (read arg)
3725 list2 [arg1,arg2] | looksLikeModuleName arg1, all isDigit arg2 = do
3726 md <- wantInterpretedModule arg1
3727 listModuleLine md (read arg2)
3728 list2 [arg] = do
3729 wantNameFromInterpretedModule noCanDo arg $ \name -> do
3730 let loc = GHC.srcSpanStart (GHC.nameSrcSpan name)
3731 case loc of
3732 RealSrcLoc l ->
3733 do tickArray <- ASSERT( isExternalName name )
3734 lift $ getTickArray (GHC.nameModule name)
3735 let mb_span = findBreakByCoord (Just (GHC.srcLocFile l))
3736 (GHC.srcLocLine l, GHC.srcLocCol l)
3737 tickArray
3738 case mb_span of
3739 Nothing -> listAround (realSrcLocSpan l) False
3740 Just (_, pan) -> listAround pan False
3741 UnhelpfulLoc _ ->
3742 noCanDo name $ text "can't find its location: " <>
3743 ppr loc
3744 where
3745 noCanDo n why = printForUser $
3746 text "cannot list source code for " <> ppr n <> text ": " <> why
3747 list2 _other =
3748 liftIO $ putStrLn "syntax: :list [<line> | <module> <line> | <identifier>]"
3749
3750 listModuleLine :: Module -> Int -> InputT GHCi ()
3751 listModuleLine modl line = do
3752 graph <- GHC.getModuleGraph
3753 let this = GHC.mgLookupModule graph modl
3754 case this of
3755 Nothing -> panic "listModuleLine"
3756 Just summ -> do
3757 let filename = expectJust "listModuleLine" (ml_hs_file (GHC.ms_location summ))
3758 loc = mkRealSrcLoc (mkFastString (filename)) line 0
3759 listAround (realSrcLocSpan loc) False
3760
3761 -- | list a section of a source file around a particular SrcSpan.
3762 -- If the highlight flag is True, also highlight the span using
3763 -- start_bold\/end_bold.
3764
3765 -- GHC files are UTF-8, so we can implement this by:
3766 -- 1) read the file in as a BS and syntax highlight it as before
3767 -- 2) convert the BS to String using utf-string, and write it out.
3768 -- It would be better if we could convert directly between UTF-8 and the
3769 -- console encoding, of course.
3770 listAround :: MonadIO m => RealSrcSpan -> Bool -> InputT m ()
3771 listAround pan do_highlight = do
3772 contents <- liftIO $ BS.readFile (unpackFS file)
3773 -- Drop carriage returns to avoid duplicates, see #9367.
3774 let ls = BS.split '\n' $ BS.filter (/= '\r') contents
3775 ls' = take (line2 - line1 + 1 + pad_before + pad_after) $
3776 drop (line1 - 1 - pad_before) $ ls
3777 fst_line = max 1 (line1 - pad_before)
3778 line_nos = [ fst_line .. ]
3779
3780 highlighted | do_highlight = zipWith highlight line_nos ls'
3781 | otherwise = [\p -> BS.concat[p,l] | l <- ls']
3782
3783 bs_line_nos = [ BS.pack (show l ++ " ") | l <- line_nos ]
3784 prefixed = zipWith ($) highlighted bs_line_nos
3785 output = BS.intercalate (BS.pack "\n") prefixed
3786
3787 let utf8Decoded = utf8DecodeByteString output
3788 liftIO $ putStrLn utf8Decoded
3789 where
3790 file = GHC.srcSpanFile pan
3791 line1 = GHC.srcSpanStartLine pan
3792 col1 = GHC.srcSpanStartCol pan - 1
3793 line2 = GHC.srcSpanEndLine pan
3794 col2 = GHC.srcSpanEndCol pan - 1
3795
3796 pad_before | line1 == 1 = 0
3797 | otherwise = 1
3798 pad_after = 1
3799
3800 highlight | do_bold = highlight_bold
3801 | otherwise = highlight_carets
3802
3803 highlight_bold no line prefix
3804 | no == line1 && no == line2
3805 = let (a,r) = BS.splitAt col1 line
3806 (b,c) = BS.splitAt (col2-col1) r
3807 in
3808 BS.concat [prefix, a,BS.pack start_bold,b,BS.pack end_bold,c]
3809 | no == line1
3810 = let (a,b) = BS.splitAt col1 line in
3811 BS.concat [prefix, a, BS.pack start_bold, b]
3812 | no == line2
3813 = let (a,b) = BS.splitAt col2 line in
3814 BS.concat [prefix, a, BS.pack end_bold, b]
3815 | otherwise = BS.concat [prefix, line]
3816
3817 highlight_carets no line prefix
3818 | no == line1 && no == line2
3819 = BS.concat [prefix, line, nl, indent, BS.replicate col1 ' ',
3820 BS.replicate (col2-col1) '^']
3821 | no == line1
3822 = BS.concat [indent, BS.replicate (col1 - 2) ' ', BS.pack "vv", nl,
3823 prefix, line]
3824 | no == line2
3825 = BS.concat [prefix, line, nl, indent, BS.replicate col2 ' ',
3826 BS.pack "^^"]
3827 | otherwise = BS.concat [prefix, line]
3828 where
3829 indent = BS.pack (" " ++ replicate (length (show no)) ' ')
3830 nl = BS.singleton '\n'
3831
3832
3833 -- --------------------------------------------------------------------------
3834 -- Tick arrays
3835
3836 getTickArray :: Module -> GHCi TickArray
3837 getTickArray modl = do
3838 st <- getGHCiState
3839 let arrmap = tickarrays st
3840 case lookupModuleEnv arrmap modl of
3841 Just arr -> return arr
3842 Nothing -> do
3843 (_breakArray, ticks) <- getModBreak modl
3844 let arr = mkTickArray (assocs ticks)
3845 setGHCiState st{tickarrays = extendModuleEnv arrmap modl arr}
3846 return arr
3847
3848 discardTickArrays :: GHCi ()
3849 discardTickArrays = modifyGHCiState (\st -> st {tickarrays = emptyModuleEnv})
3850
3851 mkTickArray :: [(BreakIndex,SrcSpan)] -> TickArray
3852 mkTickArray ticks
3853 = accumArray (flip (:)) [] (1, max_line)
3854 [ (line, (nm,pan)) | (nm,RealSrcSpan pan) <- ticks, line <- srcSpanLines pan ]
3855 where
3856 max_line = foldr max 0 [ GHC.srcSpanEndLine sp | (_, RealSrcSpan sp) <- ticks ]
3857 srcSpanLines pan = [ GHC.srcSpanStartLine pan .. GHC.srcSpanEndLine pan ]
3858
3859 -- don't reset the counter back to zero?
3860 discardActiveBreakPoints :: GHCi ()
3861 discardActiveBreakPoints = do
3862 st <- getGHCiState
3863 mapM_ (turnOffBreak.snd) (breaks st)
3864 setGHCiState $ st { breaks = [] }
3865
3866 deleteBreak :: Int -> GHCi ()
3867 deleteBreak identity = do
3868 st <- getGHCiState
3869 let oldLocations = breaks st
3870 (this,rest) = partition (\loc -> fst loc == identity) oldLocations
3871 if null this
3872 then printForUser (text "Breakpoint" <+> ppr identity <+>
3873 text "does not exist")
3874 else do
3875 mapM_ (turnOffBreak.snd) this
3876 setGHCiState $ st { breaks = rest }
3877
3878 turnOffBreak :: BreakLocation -> GHCi ()
3879 turnOffBreak loc = do
3880 (arr, _) <- getModBreak (breakModule loc)
3881 hsc_env <- GHC.getSession
3882 liftIO $ enableBreakpoint hsc_env arr (breakTick loc) False
3883
3884 getModBreak :: Module -> GHCi (ForeignRef BreakArray, Array Int SrcSpan)
3885 getModBreak m = do
3886 mod_info <- fromJust <$> GHC.getModuleInfo m
3887 let modBreaks = GHC.modInfoModBreaks mod_info
3888 let arr = GHC.modBreaks_flags modBreaks
3889 let ticks = GHC.modBreaks_locs modBreaks
3890 return (arr, ticks)
3891
3892 setBreakFlag :: Bool -> ForeignRef BreakArray -> Int -> GHCi ()
3893 setBreakFlag toggle arr i = do
3894 hsc_env <- GHC.getSession
3895 liftIO $ enableBreakpoint hsc_env arr i toggle
3896
3897 -- ---------------------------------------------------------------------------
3898 -- User code exception handling
3899
3900 -- This is the exception handler for exceptions generated by the
3901 -- user's code and exceptions coming from children sessions;
3902 -- it normally just prints out the exception. The
3903 -- handler must be recursive, in case showing the exception causes
3904 -- more exceptions to be raised.
3905 --
3906 -- Bugfix: if the user closed stdout or stderr, the flushing will fail,
3907 -- raising another exception. We therefore don't put the recursive
3908 -- handler arond the flushing operation, so if stderr is closed
3909 -- GHCi will just die gracefully rather than going into an infinite loop.
3910 handler :: SomeException -> GHCi Bool
3911
3912 handler exception = do
3913 flushInterpBuffers
3914 withSignalHandlers $
3915 ghciHandle handler (showException exception >> return False)
3916
3917 showException :: SomeException -> GHCi ()
3918 showException se =
3919 liftIO $ case fromException se of
3920 -- omit the location for CmdLineError:
3921 Just (CmdLineError s) -> putException s
3922 -- ditto:
3923 Just other_ghc_ex -> putException (show other_ghc_ex)
3924 Nothing ->
3925 case fromException se of
3926 Just UserInterrupt -> putException "Interrupted."
3927 _ -> putException ("*** Exception: " ++ show se)
3928 where
3929 putException = hPutStrLn stderr
3930
3931
3932 -----------------------------------------------------------------------------
3933 -- recursive exception handlers
3934
3935 -- Don't forget to unblock async exceptions in the handler, or if we're
3936 -- in an exception loop (eg. let a = error a in a) the ^C exception
3937 -- may never be delivered. Thanks to Marcin for pointing out the bug.
3938
3939 ghciHandle :: (HasDynFlags m, ExceptionMonad m) => (SomeException -> m a) -> m a -> m a
3940 ghciHandle h m = gmask $ \restore -> do
3941 -- Force dflags to avoid leaking the associated HscEnv
3942 !dflags <- getDynFlags
3943 gcatch (restore (GHC.prettyPrintGhcErrors dflags m)) $ \e -> restore (h e)
3944
3945 ghciTry :: GHCi a -> GHCi (Either SomeException a)
3946 ghciTry (GHCi m) = GHCi $ \s -> gtry (m s)
3947
3948 tryBool :: GHCi a -> GHCi Bool
3949 tryBool m = do
3950 r <- ghciTry m
3951 case r of
3952 Left _ -> return False
3953 Right _ -> return True
3954
3955 -- ----------------------------------------------------------------------------
3956 -- Utils
3957
3958 lookupModule :: GHC.GhcMonad m => String -> m Module
3959 lookupModule mName = lookupModuleName (GHC.mkModuleName mName)
3960
3961 lookupModuleName :: GHC.GhcMonad m => ModuleName -> m Module
3962 lookupModuleName mName = GHC.lookupModule mName Nothing
3963
3964 isHomeModule :: Module -> Bool
3965 isHomeModule m = GHC.moduleUnitId m == mainUnitId
3966
3967 -- TODO: won't work if home dir is encoded.
3968 -- (changeDirectory may not work either in that case.)
3969 expandPath :: MonadIO m => String -> InputT m String
3970 expandPath = liftIO . expandPathIO
3971
3972 expandPathIO :: String -> IO String
3973 expandPathIO p =
3974 case dropWhile isSpace p of
3975 ('~':d) -> do
3976 tilde <- getHomeDirectory -- will fail if HOME not defined
3977 return (tilde ++ '/':d)
3978 other ->
3979 return other
3980
3981 wantInterpretedModule :: GHC.GhcMonad m => String -> m Module
3982 wantInterpretedModule str = wantInterpretedModuleName (GHC.mkModuleName str)
3983
3984 wantInterpretedModuleName :: GHC.GhcMonad m => ModuleName -> m Module
3985 wantInterpretedModuleName modname = do
3986 modl <- lookupModuleName modname
3987 let str = moduleNameString modname
3988 dflags <- getDynFlags
3989 when (GHC.moduleUnitId modl /= thisPackage dflags) $
3990 throwGhcException (CmdLineError ("module '" ++ str ++ "' is from another package;\nthis command requires an interpreted module"))
3991 is_interpreted <- GHC.moduleIsInterpreted modl
3992 when (not is_interpreted) $
3993 throwGhcException (CmdLineError ("module '" ++ str ++ "' is not interpreted; try \':add *" ++ str ++ "' first"))
3994 return modl
3995
3996 wantNameFromInterpretedModule :: GHC.GhcMonad m
3997 => (Name -> SDoc -> m ())
3998 -> String
3999 -> (Name -> m ())
4000 -> m ()
4001 wantNameFromInterpretedModule noCanDo str and_then =
4002 handleSourceError GHC.printException $ do
4003 names <- GHC.parseName str
4004 case names of
4005 [] -> return ()
4006 (n:_) -> do
4007 let modl = ASSERT( isExternalName n ) GHC.nameModule n
4008 if not (GHC.isExternalName n)
4009 then noCanDo n $ ppr n <>
4010 text " is not defined in an interpreted module"
4011 else do
4012 is_interpreted <- GHC.moduleIsInterpreted modl
4013 if not is_interpreted
4014 then noCanDo n $ text "module " <> ppr modl <>
4015 text " is not interpreted"
4016 else and_then n