Debian Codegraph @

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

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