mirrored from https://gitlab.haskell.org/ghc/ghc.git
-
Notifications
You must be signed in to change notification settings - Fork 703
/
UI.hs
4609 lines (4036 loc) · 184 KB
/
UI.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE CPP #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiWayIf #-}
{-# LANGUAGE NondecreasingIndentation #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS -fno-warn-name-shadowing #-}
-- This module does a lot of it
-----------------------------------------------------------------------------
--
-- GHC Interactive User Interface
--
-- (c) The GHC Team 2005-2006
--
-----------------------------------------------------------------------------
module GHCi.UI (
interactiveUI,
GhciSettings(..),
defaultGhciSettings,
ghciCommands,
ghciWelcomeMsg
) where
-- GHCi
import qualified GHCi.UI.Monad as GhciMonad ( args, runStmt, runDecls' )
import GHCi.UI.Monad hiding ( args, runStmt )
import GHCi.UI.Tags
import GHCi.UI.Info
import GHC.Runtime.Debugger
-- The GHC interface
import GHC.Runtime.Interpreter
import GHCi.RemoteTypes
import GHCi.BreakArray( breakOn, breakOff )
import GHC.ByteCode.Types
import GHC.Core.DataCon
import GHC.Core.ConLike
import GHC.Core.PatSyn
import GHC.Driver.Errors
import GHC.Driver.Phases
import GHC.Driver.Session as DynFlags
import GHC.Driver.Ppr hiding (printForUser)
import GHC.Utils.Error hiding (traceCmd)
import GHC.Driver.Monad ( modifySession )
import GHC.Driver.Config.Parser (initParserOpts)
import qualified GHC
import GHC ( LoadHowMuch(..), Target(..), TargetId(..),
Resume, SingleStep, Ghc,
GetDocsFailure(..), putLogMsgM, pushLogHookM,
getModuleGraph, handleSourceError, ms_mod )
import GHC.Driver.Main (hscParseDeclsWithLocation, hscParseStmtWithLocation)
import GHC.Hs.ImpExp
import GHC.Hs
import GHC.Driver.Env
import GHC.Runtime.Context
import GHC.Types.TyThing
import GHC.Types.TyThing.Ppr
import GHC.Core.TyCo.Ppr
import GHC.Types.SafeHaskell ( getSafeMode )
import GHC.Types.Name
import GHC.Types.SourceText
import GHC.Types.Var ( varType )
import GHC.Iface.Syntax ( showToHeader )
import GHC.Builtin.Names
import GHC.Builtin.Types( stringTyCon_RDR )
import GHC.Types.Name.Reader as RdrName ( getGRE_NameQualifier_maybes, getRdrName )
import GHC.Types.SrcLoc as SrcLoc
import qualified GHC.Parser.Lexer as Lexer
import GHC.Parser.Header ( toArgs )
import GHC.Unit
import GHC.Unit.State
import GHC.Unit.Finder as Finder
import GHC.Unit.Module.Graph (filterToposortToModules)
import GHC.Unit.Module.ModSummary
import GHC.Data.StringBuffer
import GHC.Utils.Outputable
import GHC.Utils.Logger
-- Other random utilities
import GHC.Types.Basic hiding ( isTopLevel )
import GHC.Settings.Config
import GHC.Data.Graph.Directed
import GHC.Utils.Encoding
import GHC.Data.FastString
import qualified GHC.Linker.Loader as Loader
import GHC.Data.Maybe ( orElse, expectJust )
import GHC.Types.Name.Set
import GHC.Utils.Panic hiding ( showException, try )
import GHC.Utils.Panic.Plain
import GHC.Utils.Misc
import qualified GHC.LanguageExtensions as LangExt
import GHC.Data.Bag (unitBag)
import qualified GHC.Data.Strict as Strict
-- Haskell Libraries
import System.Console.Haskeline as Haskeline
import Control.Applicative hiding (empty)
import Control.DeepSeq (deepseq)
import Control.Monad as Monad
import Control.Monad.Catch as MC
import Control.Monad.IO.Class
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Data.Array
import qualified Data.ByteString.Char8 as BS
import Data.Char
import Data.Function
import Data.IORef ( IORef, modifyIORef, newIORef, readIORef, writeIORef )
import Data.List ( elemIndices, find, group, intercalate, intersperse,
isPrefixOf, isSuffixOf, nub, partition, sort, sortBy, (\\) )
import qualified Data.Set as S
import Data.Maybe
import qualified Data.Map as M
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Time.LocalTime ( getZonedTime )
import Data.Time.Format ( formatTime, defaultTimeLocale )
import Data.Version ( showVersion )
import Prelude hiding ((<>))
import GHC.Utils.Exception as Exception hiding (catch, mask, handle)
import Foreign hiding (void)
import GHC.Stack hiding (SrcLoc(..))
import System.Directory
import System.Environment
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.Info
import System.IO
import System.IO.Error
import System.IO.Unsafe ( unsafePerformIO )
import System.Process
import Text.Printf
import Text.Read ( readMaybe )
import Text.Read.Lex (isSymbolChar)
import Unsafe.Coerce
#if !defined(mingw32_HOST_OS)
import System.Posix hiding ( getEnv )
#else
import qualified System.Win32
#endif
import GHC.IO.Exception ( IOErrorType(InvalidArgument) )
import GHC.IO.Handle ( hFlushAll )
import GHC.TopHandler ( topHandler )
import GHCi.Leak
-----------------------------------------------------------------------------
data GhciSettings = GhciSettings {
availableCommands :: [Command],
shortHelpText :: String,
fullHelpText :: String,
defPrompt :: PromptFunction,
defPromptCont :: PromptFunction
}
defaultGhciSettings :: GhciSettings
defaultGhciSettings =
GhciSettings {
availableCommands = ghciCommands,
shortHelpText = defShortHelpText,
defPrompt = default_prompt,
defPromptCont = default_prompt_cont,
fullHelpText = defFullHelpText
}
ghciWelcomeMsg :: String
ghciWelcomeMsg = "GHCi, version " ++ cProjectVersion ++
": https://www.haskell.org/ghc/ :? for help"
ghciCommands :: [Command]
ghciCommands = map mkCmd [
-- Hugs users are accustomed to :e, so make sure it doesn't overlap
("?", keepGoing help, noCompletion),
("add", keepGoingPaths addModule, completeFilename),
("abandon", keepGoing abandonCmd, noCompletion),
("break", keepGoing breakCmd, completeBreakpoint),
("back", keepGoing backCmd, noCompletion),
("browse", keepGoing' (browseCmd False), completeModule),
("browse!", keepGoing' (browseCmd True), completeModule),
("cd", keepGoing' changeDirectory, completeFilename),
("check", keepGoing' checkModule, completeHomeModule),
("continue", keepGoing continueCmd, noCompletion),
("cmd", keepGoing cmdCmd, completeExpression),
("ctags", keepGoing createCTagsWithLineNumbersCmd, completeFilename),
("ctags!", keepGoing createCTagsWithRegExesCmd, completeFilename),
("def", keepGoing (defineMacro False), completeExpression),
("def!", keepGoing (defineMacro True), completeExpression),
("delete", keepGoing deleteCmd, noCompletion),
("disable", keepGoing disableCmd, noCompletion),
("doc", keepGoing' docCmd, completeIdentifier),
("edit", keepGoing' editFile, completeFilename),
("enable", keepGoing enableCmd, noCompletion),
("etags", keepGoing createETagsFileCmd, completeFilename),
("force", keepGoing forceCmd, completeExpression),
("forward", keepGoing forwardCmd, noCompletion),
("help", keepGoing help, noCompletion),
("history", keepGoing historyCmd, noCompletion),
("info", keepGoing' (info False), completeIdentifier),
("info!", keepGoing' (info True), completeIdentifier),
("issafe", keepGoing' isSafeCmd, completeModule),
("ignore", keepGoing ignoreCmd, noCompletion),
("kind", keepGoing' (kindOfType False), completeIdentifier),
("kind!", keepGoing' (kindOfType True), completeIdentifier),
("load", keepGoingPaths loadModule_, completeHomeModuleOrFile),
("load!", keepGoingPaths loadModuleDefer, completeHomeModuleOrFile),
("list", keepGoing' listCmd, noCompletion),
("module", keepGoing moduleCmd, completeSetModule),
("main", keepGoing runMain, completeFilename),
("print", keepGoing printCmd, completeExpression),
("quit", quit, noCompletion),
("reload", keepGoing' reloadModule, noCompletion),
("reload!", keepGoing' reloadModuleDefer, noCompletion),
("run", keepGoing runRun, completeFilename),
("script", keepGoing' scriptCmd, completeFilename),
("set", keepGoing setCmd, completeSetOptions),
("seti", keepGoing setiCmd, completeSeti),
("show", keepGoing showCmd, completeShowOptions),
("showi", keepGoing showiCmd, completeShowiOptions),
("sprint", keepGoing sprintCmd, completeExpression),
("step", keepGoing stepCmd, completeIdentifier),
("steplocal", keepGoing stepLocalCmd, completeIdentifier),
("stepmodule",keepGoing stepModuleCmd, completeIdentifier),
("type", keepGoing' typeOfExpr, completeExpression),
("trace", keepGoing traceCmd, completeExpression),
("unadd", keepGoingPaths unAddModule, completeFilename),
("undef", keepGoing undefineMacro, completeMacro),
("unset", keepGoing unsetOptions, completeSetOptions),
("where", keepGoing whereCmd, noCompletion),
("instances", keepGoing' instancesCmd, completeExpression)
] ++ map mkCmdHidden [ -- hidden commands
("all-types", keepGoing' allTypesCmd),
("complete", keepGoing completeCmd),
("loc-at", keepGoing' locAtCmd),
("type-at", keepGoing' typeAtCmd),
("uses", keepGoing' usesCmd)
]
where
mkCmd (n,a,c) = Command { cmdName = n
, cmdAction = a
, cmdHidden = False
, cmdCompletionFunc = c
}
mkCmdHidden (n,a) = Command { cmdName = n
, cmdAction = a
, cmdHidden = True
, cmdCompletionFunc = noCompletion
}
-- We initialize readline (in the interactiveUI function) to use
-- word_break_chars as the default set of completion word break characters.
-- This can be overridden for a particular command (for example, filename
-- expansion shouldn't consider '/' to be a word break) by setting the third
-- entry in the Command tuple above.
--
-- NOTE: in order for us to override the default correctly, any custom entry
-- must be a SUBSET of word_break_chars.
word_break_chars :: String
word_break_chars = spaces ++ specials ++ symbols
symbols, specials, spaces :: String
symbols = "!#$%&*+/<=>?@\\^|-~"
specials = "(),;[]`{}"
spaces = " \t\n"
flagWordBreakChars :: String
flagWordBreakChars = " \t\n"
keepGoing :: (String -> GHCi ()) -> (String -> InputT GHCi Bool)
keepGoing a str = keepGoing' (lift . a) str
keepGoing' :: Monad m => (String -> m ()) -> String -> m Bool
keepGoing' a str = a str >> return False
keepGoingPaths :: ([FilePath] -> InputT GHCi ()) -> (String -> InputT GHCi Bool)
keepGoingPaths a str
= do case toArgsNoLoc str of
Left err -> liftIO $ hPutStrLn stderr err
Right args -> a args
return False
defShortHelpText :: String
defShortHelpText = "use :? for help.\n"
defFullHelpText :: String
defFullHelpText =
" Commands available from the prompt:\n" ++
"\n" ++
" <statement> evaluate/run <statement>\n" ++
" : repeat last command\n" ++
" :{\\n ..lines.. \\n:}\\n multiline command\n" ++
" :add [*]<module> ... add module(s) to the current target set\n" ++
" :browse[!] [[*]<mod>] display the names defined by module <mod>\n" ++
" (!: more details; *: all top-level names)\n" ++
" :cd <dir> change directory to <dir>\n" ++
" :cmd <expr> run the commands returned by <expr>::IO String\n" ++
" :complete <dom> [<rng>] <s> list completions for partial input string\n" ++
" :ctags[!] [<file>] create tags file <file> for Vi (default: \"tags\")\n" ++
" (!: use regex instead of line number)\n" ++
" :def[!] <cmd> <expr> define command :<cmd> (later defined command has\n" ++
" precedence, ::<cmd> is always a builtin command)\n" ++
" (!: redefine an existing command name)\n" ++
" :doc <name> display docs for the given name (experimental)\n" ++
" :edit <file> edit file\n" ++
" :edit edit last module\n" ++
" :etags [<file>] create tags file <file> for Emacs (default: \"TAGS\")\n" ++
" :help, :? display this list of commands\n" ++
" :info[!] [<name> ...] display information about the given names\n" ++
" (!: do not filter instances)\n" ++
" :instances <type> display the class instances available for <type>\n" ++
" :issafe [<mod>] display safe haskell information of module <mod>\n" ++
" :kind[!] <type> show the kind of <type>\n" ++
" (!: also print the normalised type)\n" ++
" :load[!] [*]<module> ... load module(s) and their dependents\n" ++
" (!: defer type errors)\n" ++
" :main [<arguments> ...] run the main function with the given arguments\n" ++
" :module [+/-] [*]<mod> ... set the context for expression evaluation\n" ++
" :quit exit GHCi\n" ++
" :reload[!] reload the current module set\n" ++
" (!: defer type errors)\n" ++
" :run function [<arguments> ...] run the function with the given arguments\n" ++
" :script <file> run the script <file>\n" ++
" :type <expr> show the type of <expr>\n" ++
" :type +d <expr> show the type of <expr>, defaulting type variables\n" ++
" :type +v <expr> show the type of <expr>, with its specified tyvars\n" ++
" :unadd <module> ... remove module(s) from the current target set\n" ++
" :undef <cmd> undefine user-defined command :<cmd>\n" ++
" ::<cmd> run the builtin command\n" ++
" :!<command> run the shell command <command>\n" ++
"\n" ++
" -- Commands for debugging:\n" ++
"\n" ++
" :abandon at a breakpoint, abandon current computation\n" ++
" :back [<n>] go back in the history N steps (after :trace)\n" ++
" :break [<mod>] <l> [<col>] set a breakpoint at the specified location\n" ++
" :break <name> set a breakpoint on the specified function\n" ++
" :continue [<count>] resume after a breakpoint [and set break ignore count]\n" ++
" :delete <number> ... delete the specified breakpoints\n" ++
" :delete * delete all breakpoints\n" ++
" :disable <number> ... disable the specified breakpoints\n" ++
" :disable * disable all breakpoints\n" ++
" :enable <number> ... enable the specified breakpoints\n" ++
" :enable * enable all breakpoints\n" ++
" :force <expr> print <expr>, forcing unevaluated parts\n" ++
" :forward [<n>] go forward in the history N step s(after :back)\n" ++
" :history [<n>] after :trace, show the execution history\n" ++
" :ignore <breaknum> <count> for break <breaknum> set break ignore <count>\n" ++
" :list show the source code around current breakpoint\n" ++
" :list <identifier> show the source code for <identifier>\n" ++
" :list [<module>] <line> show the source code around line number <line>\n" ++
" :print [<name> ...] show a value without forcing its computation\n" ++
" :sprint [<name> ...] simplified version of :print\n" ++
" :step single-step after stopping at a breakpoint\n"++
" :step <expr> single-step into <expr>\n"++
" :steplocal single-step within the current top-level binding\n"++
" :stepmodule single-step restricted to the current module\n"++
" :trace trace after stopping at a breakpoint\n"++
" :trace <expr> evaluate <expr> with tracing on (see :history)\n"++
"\n" ++
" -- Commands for changing settings:\n" ++
"\n" ++
" :set <option> ... set options\n" ++
" :seti <option> ... set options for interactive evaluation only\n" ++
" :set local-config { source | ignore }\n" ++
" set whether to source .ghci in current dir\n" ++
" (loading untrusted config is a security issue)\n" ++
" :set args <arg> ... set the arguments returned by System.getArgs\n" ++
" :set prog <progname> set the value returned by System.getProgName\n" ++
" :set prompt <prompt> set the prompt used in GHCi\n" ++
" :set prompt-cont <prompt> set the continuation prompt used in GHCi\n" ++
" :set prompt-function <expr> set the function to handle the prompt\n" ++
" :set prompt-cont-function <expr>\n" ++
" set the function to handle the continuation prompt\n" ++
" :set editor <cmd> set the command used for :edit\n" ++
" :set stop [<n>] <cmd> set the command to run when a breakpoint is hit\n" ++
" :unset <option> ... unset options\n" ++
"\n" ++
" Options for ':set' and ':unset':\n" ++
"\n" ++
" +m allow multiline commands\n" ++
" +r revert top-level expressions after each evaluation\n" ++
" +s print timing/memory stats after each evaluation\n" ++
" +t print type after evaluation\n" ++
" +c collect type/location info after loading modules\n" ++
" -<flags> most GHC command line flags can also be set here\n" ++
" (eg. -v2, -XFlexibleInstances, etc.)\n" ++
" for GHCi-specific flags, see User's Guide,\n"++
" Flag reference, Interactive-mode options\n" ++
"\n" ++
" -- Commands for displaying information:\n" ++
"\n" ++
" :show bindings show the current bindings made at the prompt\n" ++
" :show breaks show the active breakpoints\n" ++
" :show context show the breakpoint context\n" ++
" :show imports show the current imports\n" ++
" :show linker show current linker state\n" ++
" :show modules show the currently loaded modules\n" ++
" :show packages show the currently active package flags\n" ++
" :show paths show the currently active search paths\n" ++
" :show language show the currently active language flags\n" ++
" :show targets show the current set of targets\n" ++
" :show <setting> show value of <setting>, which is one of\n" ++
" [args, prog, editor, stop]\n" ++
" :showi language show language flags for interactive evaluation\n" ++
"\n" ++
" The User's Guide has more information. An online copy can be found here:\n" ++
"\n" ++
" https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/ghci.html\n" ++
"\n"
findEditor :: IO String
findEditor = do
getEnv "VISUAL" <|> getEnv "EDITOR" <|> defaultEditor
where
defaultEditor = do
#if defined(mingw32_HOST_OS)
win <- System.Win32.getWindowsDirectory
return (win </> "notepad.exe")
#else
return ""
#endif
default_progname, default_stop :: String
default_progname = "<interactive>"
default_stop = ""
default_prompt, default_prompt_cont :: PromptFunction
default_prompt = generatePromptFunctionFromString "ghci> "
default_prompt_cont = generatePromptFunctionFromString "| "
default_args :: [String]
default_args = []
interactiveUI :: GhciSettings -> [(FilePath, Maybe Phase)] -> Maybe [String]
-> Ghc ()
interactiveUI config srcs maybe_exprs = do
-- HACK! If we happen to get into an infinite loop (eg the user
-- types 'let x=x in x' at the prompt), then the thread will block
-- on a blackhole, and become unreachable during GC. The GC will
-- detect that it is unreachable and send it the NonTermination
-- exception. However, since the thread is unreachable, everything
-- it refers to might be finalized, including the standard Handles.
-- This sounds like a bug, but we don't have a good solution right
-- now.
_ <- liftIO $ newStablePtr stdin
_ <- liftIO $ newStablePtr stdout
_ <- liftIO $ newStablePtr stderr
-- Initialise buffering for the *interpreted* I/O system
(nobuffering, flush) <- runInternal initInterpBuffering
-- The initial set of DynFlags used for interactive evaluation is the same
-- as the global DynFlags, plus -XExtendedDefaultRules and
-- -XNoMonomorphismRestriction.
-- See note [Changing language extensions for interactive evaluation] #10857
dflags <- getDynFlags
let dflags' = (xopt_set_unlessExplSpec
LangExt.ExtendedDefaultRules xopt_set)
. (xopt_set_unlessExplSpec
LangExt.MonomorphismRestriction xopt_unset)
$ dflags
GHC.setInteractiveDynFlags dflags'
_ <- GHC.setProgramDynFlags
-- Set Opt_KeepGoing so that :reload loads as much as
-- possible
(gopt_set dflags Opt_KeepGoing)
-- Update the LogAction. Ensure we don't override the user's log action lest
-- we break -ddump-json (#14078)
lastErrLocationsRef <- liftIO $ newIORef []
pushLogHookM (ghciLogAction lastErrLocationsRef)
when (isNothing maybe_exprs) $ do
-- Only for GHCi (not runghc and ghc -e):
-- Turn buffering off for the compiled program's stdout/stderr
turnOffBuffering_ nobuffering
-- Turn buffering off for GHCi's stdout
liftIO $ hFlush stdout
liftIO $ hSetBuffering stdout NoBuffering
-- We don't want the cmd line to buffer any input that might be
-- intended for the program, so unbuffer stdin.
liftIO $ hSetBuffering stdin NoBuffering
liftIO $ hSetBuffering stderr NoBuffering
#if defined(mingw32_HOST_OS)
-- On Unix, stdin will use the locale encoding. The IO library
-- doesn't do this on Windows (yet), so for now we use UTF-8,
-- for consistency with GHC 6.10 and to make the tests work.
liftIO $ hSetEncoding stdin utf8
#endif
default_editor <- liftIO $ findEditor
eval_wrapper <- mkEvalWrapper default_progname default_args
let prelude_import = simpleImportDecl preludeModuleName
startGHCi (runGHCi srcs maybe_exprs)
GHCiState{ progname = default_progname,
args = default_args,
evalWrapper = eval_wrapper,
prompt = defPrompt config,
prompt_cont = defPromptCont config,
stop = default_stop,
editor = default_editor,
options = [],
localConfig = SourceLocalConfig,
-- We initialize line number as 0, not 1, because we use
-- current line number while reporting errors which is
-- incremented after reading a line.
line_number = 0,
break_ctr = 0,
breaks = IntMap.empty,
tickarrays = emptyModuleEnv,
ghci_commands = availableCommands config,
ghci_macros = [],
last_command = Nothing,
cmd_wrapper = (cmdSuccess =<<),
cmdqueue = [],
remembered_ctx = [],
transient_ctx = [],
extra_imports = [],
prelude_imports = [prelude_import],
ghc_e = isJust maybe_exprs,
short_help = shortHelpText config,
long_help = fullHelpText config,
lastErrorLocations = lastErrLocationsRef,
mod_infos = M.empty,
flushStdHandles = flush,
noBuffering = nobuffering
}
return ()
{-
Note [Changing language extensions for interactive evaluation]
--------------------------------------------------------------
GHCi maintains two sets of options:
- The "loading options" apply when loading modules
- The "interactive options" apply when evaluating expressions and commands
typed at the GHCi prompt.
The loading options are mostly created in ghc/Main.hs:main' from the command
line flags. In the function ghc/GHCi/UI.hs:interactiveUI the loading options
are copied to the interactive options.
These interactive options (but not the loading options!) are supplemented
unconditionally by setting ExtendedDefaultRules ON and
MonomorphismRestriction OFF. The unconditional setting of these options
eventually overwrite settings already specified at the command line.
Therefore instead of unconditionally setting ExtendedDefaultRules and
NoMonomorphismRestriction for the interactive options, we use the function
'xopt_set_unlessExplSpec' to first check whether the extension has already
specified at the command line.
The ghci config file has not yet been processed.
-}
resetLastErrorLocations :: GhciMonad m => m ()
resetLastErrorLocations = do
st <- getGHCiState
liftIO $ writeIORef (lastErrorLocations st) []
ghciLogAction :: IORef [(FastString, Int)] -> LogAction -> LogAction
ghciLogAction lastErrLocations old_log_action
dflags msg_class srcSpan msg = do
old_log_action dflags msg_class srcSpan msg
case msg_class of
MCDiagnostic SevError _reason -> case srcSpan of
RealSrcSpan rsp _ -> modifyIORef lastErrLocations
(++ [(srcLocFile (realSrcSpanStart rsp), srcLocLine (realSrcSpanStart rsp))])
_ -> return ()
_ -> return ()
withGhcAppData :: (FilePath -> IO a) -> IO a -> IO a
withGhcAppData right left = do
either_dir <- tryIO (getXdgDirectory XdgData "ghc")
case either_dir of
Right dir ->
do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
right dir
_ -> left
withGhcConfig :: (FilePath -> IO a) -> IO a -> IO a
withGhcConfig right left = do
old_path <- getAppUserDataDirectory "ghc"
use_old_path <- doesPathExist old_path
let path = (if use_old_path
then getAppUserDataDirectory "ghc"
else getXdgDirectory XdgConfig "ghc")
either_dir <- tryIO (path)
case either_dir of
Right dir ->
do createDirectoryIfMissing False dir `catchIO` \_ -> return ()
right dir
_ -> left
runGHCi :: [(FilePath, Maybe Phase)] -> Maybe [String] -> GHCi ()
runGHCi paths maybe_exprs = do
dflags <- getDynFlags
let
ignore_dot_ghci = gopt Opt_IgnoreDotGhci dflags
app_user_dir = liftIO $ withGhcConfig
(\dir -> return (Just (dir </> "ghci.conf")))
(return Nothing)
home_dir = do
either_dir <- liftIO $ tryIO (getEnv "HOME")
case either_dir of
Right home -> return (Just (home </> ".ghci"))
_ -> return Nothing
canonicalizePath' :: FilePath -> IO (Maybe FilePath)
canonicalizePath' fp = liftM Just (canonicalizePath fp)
`catchIO` \_ -> return Nothing
sourceConfigFile :: FilePath -> GHCi ()
sourceConfigFile file = do
exists <- liftIO $ doesFileExist file
when exists $ do
either_hdl <- liftIO $ tryIO (openFile file ReadMode)
case either_hdl of
Left _e -> return ()
-- NOTE: this assumes that runInputT won't affect the terminal;
-- can we assume this will always be the case?
-- This would be a good place for runFileInputT.
Right hdl ->
do runInputTWithPrefs defaultPrefs defaultSettings $
runCommands $ fileLoop hdl
liftIO (hClose hdl `catchIO` \_ -> return ())
-- Don't print a message if this is really ghc -e (#11478).
-- Also, let the user silence the message with -v0
-- (the default verbosity in GHCi is 1).
when (isNothing maybe_exprs && verbosity dflags > 0) $
liftIO $ putStrLn ("Loaded GHCi configuration from " ++ file)
--
setGHCContextFromGHCiState
processedCfgs <- if ignore_dot_ghci
then pure []
else do
userCfgs <- do
paths <- catMaybes <$> sequence [ app_user_dir, home_dir ]
checkedPaths <- liftIO $ filterM checkFileAndDirPerms paths
liftIO . fmap (nub . catMaybes) $ mapM canonicalizePath' checkedPaths
localCfg <- do
let path = ".ghci"
ok <- liftIO $ checkFileAndDirPerms path
if ok then liftIO $ canonicalizePath' path else pure Nothing
mapM_ sourceConfigFile userCfgs
-- Process the global and user .ghci
-- (but not $CWD/.ghci or CLI args, yet)
behaviour <- localConfig <$> getGHCiState
processedLocalCfg <- case localCfg of
Just path | path `notElem` userCfgs ->
-- don't read .ghci twice if CWD is $HOME
case behaviour of
SourceLocalConfig -> localCfg <$ sourceConfigFile path
IgnoreLocalConfig -> pure Nothing
_ -> pure Nothing
pure $ maybe id (:) processedLocalCfg userCfgs
let arg_cfgs = reverse $ ghciScripts dflags
-- -ghci-script are collected in reverse order
-- We don't require that a script explicitly added by -ghci-script
-- is owned by the current user. (#6017)
mapM_ sourceConfigFile $ nub arg_cfgs \\ processedCfgs
-- Dedup, and remove any configs we already processed.
-- Importantly, if $PWD/.ghci was ignored due to configuration,
-- explicitly specifying it does cause it to be processed.
-- Perform a :load for files given on the GHCi command line
-- When in -e mode, if the load fails then we want to stop
-- immediately rather than going on to evaluate the expression.
when (not (null paths)) $ do
ok <- ghciHandle (\e -> do showException e; return Failed) $
-- TODO: this is a hack.
runInputTWithPrefs defaultPrefs defaultSettings $
loadModule paths
when (isJust maybe_exprs && failed ok) $
liftIO (exitWith (ExitFailure 1))
installInteractivePrint (interactivePrint dflags) (isJust maybe_exprs)
-- if verbosity is greater than 0, or we are connected to a
-- terminal, display the prompt in the interactive loop.
is_tty <- liftIO (hIsTerminalDevice stdin)
let show_prompt = verbosity dflags > 0 || is_tty
-- reset line number
modifyGHCiState $ \st -> st{line_number=0}
case maybe_exprs of
Nothing ->
do
-- enter the interactive loop
runGHCiInput $ runCommands $ nextInputLine show_prompt is_tty
Just exprs -> do
-- just evaluate the expression we were given
enqueueCommands exprs
let hdle e = do st <- getGHCiState
-- flush the interpreter's stdout/stderr on exit (#3890)
flushInterpBuffers
-- Jump through some hoops to get the
-- current progname in the exception text:
-- <progname>: <exception>
liftIO $ withProgName (progname st)
$ topHandler e
-- this used to be topHandlerFastExit, see #2228
runInputTWithPrefs defaultPrefs defaultSettings $ do
-- make `ghc -e` exit nonzero on invalid input, see #7962
_ <- runCommands' hdle
(Just $ hdle (toException $ ExitFailure 1) >> return ())
(return Nothing)
return ()
-- and finally, exit
liftIO $ when (verbosity dflags > 0) $ putStrLn "Leaving GHCi."
runGHCiInput :: InputT GHCi a -> GHCi a
runGHCiInput f = do
dflags <- getDynFlags
let ghciHistory = gopt Opt_GhciHistory dflags
let localGhciHistory = gopt Opt_LocalGhciHistory dflags
currentDirectory <- liftIO $ getCurrentDirectory
histFile <- case (ghciHistory, localGhciHistory) of
(True, True) -> return (Just (currentDirectory </> ".ghci_history"))
(True, _) -> liftIO $ withGhcAppData
(\dir -> return (Just (dir </> "ghci_history"))) (return Nothing)
_ -> return Nothing
runInputT
(setComplete ghciCompleteWord $ defaultSettings {historyFile = histFile})
f
-- | How to get the next input line from the user
nextInputLine :: Bool -> Bool -> InputT GHCi (Maybe String)
nextInputLine show_prompt is_tty
| is_tty = do
prmpt <- if show_prompt then lift mkPrompt else return ""
r <- getInputLine prmpt
incrementLineNo
return r
| otherwise = do
when show_prompt $ lift mkPrompt >>= liftIO . putStr
fileLoop stdin
-- NOTE: We only read .ghci files if they are owned by the current user,
-- and aren't world writable (files owned by root are ok, see #9324).
-- Otherwise, we could be accidentally running code planted by
-- a malicious third party.
-- Furthermore, We only read ./.ghci if . is owned by the current user
-- and isn't writable by anyone else. I think this is sufficient: we
-- don't need to check .. and ../.. etc. because "." always refers to
-- the same directory while a process is running.
checkFileAndDirPerms :: FilePath -> IO Bool
checkFileAndDirPerms file = do
file_ok <- checkPerms file
-- Do not check dir perms when .ghci doesn't exist, otherwise GHCi will
-- print some confusing and useless warnings in some cases (e.g. in
-- travis). Note that we can't add a test for this, as all ghci tests should
-- run with -ignore-dot-ghci, which means we never get here.
if file_ok then checkPerms (getDirectory file) else return False
where
getDirectory f = case takeDirectory f of
"" -> "."
d -> d
checkPerms :: FilePath -> IO Bool
#if defined(mingw32_HOST_OS)
checkPerms _ = return True
#else
checkPerms file =
handleIO (\_ -> return False) $ do
st <- getFileStatus file
me <- getRealUserID
let mode = System.Posix.fileMode st
ok = (fileOwner st == me || fileOwner st == 0) &&
groupWriteMode /= mode `intersectFileModes` groupWriteMode &&
otherWriteMode /= mode `intersectFileModes` otherWriteMode
unless ok $
-- #8248: Improving warning to include a possible fix.
putStrLn $ "*** WARNING: " ++ file ++
" is writable by someone else, IGNORING!" ++
"\nSuggested fix: execute 'chmod go-w " ++ file ++ "'"
return ok
#endif
incrementLineNo :: GhciMonad m => m ()
incrementLineNo = modifyGHCiState incLineNo
where
incLineNo st = st { line_number = line_number st + 1 }
fileLoop :: GhciMonad m => Handle -> m (Maybe String)
fileLoop hdl = do
l <- liftIO $ tryIO $ hGetLine hdl
case l of
Left e | isEOFError e -> return Nothing
| -- as we share stdin with the program, the program
-- might have already closed it, so we might get a
-- handle-closed exception. We therefore catch that
-- too.
isIllegalOperation e -> return Nothing
| InvalidArgument <- etype -> return Nothing
| otherwise -> liftIO $ ioError e
where etype = ioeGetErrorType e
-- treat InvalidArgument in the same way as EOF:
-- this can happen if the user closed stdin, or
-- perhaps did getContents which closes stdin at
-- EOF.
Right l' -> do
incrementLineNo
return (Just l')
formatCurrentTime :: String -> IO String
formatCurrentTime format =
getZonedTime >>= return . (formatTime defaultTimeLocale format)
getUserName :: IO String
getUserName = do
#if defined(mingw32_HOST_OS)
getEnv "USERNAME"
`catchIO` \e -> do
putStrLn $ show e
return ""
#else
getLoginName
#endif
getInfoForPrompt :: GhciMonad m => m (SDoc, [String], Int)
getInfoForPrompt = do
st <- getGHCiState
imports <- GHC.getContext
resumes <- GHC.getResumeContext
context_bit <-
case resumes of
[] -> return empty
r:_ -> do
let ix = GHC.resumeHistoryIx r
if ix == 0
then return (brackets (ppr (GHC.resumeSpan r)) <> space)
else do
let hist = GHC.resumeHistory r !! (ix-1)
pan <- GHC.getHistorySpan hist
return (brackets (ppr (negate ix) <> char ':'
<+> ppr pan) <> space)
let
dots | _:rs <- resumes, not (null rs) = text "... "
| otherwise = empty
rev_imports = reverse imports -- rightmost are the most recent
myIdeclName d | Just m <- ideclAs d = unLoc m
| otherwise = unLoc (ideclName d)
modules_names =
['*':(moduleNameString m) | IIModule m <- rev_imports] ++
[moduleNameString (myIdeclName d) | IIDecl d <- rev_imports]
line = 1 + line_number st
return (dots <> context_bit, modules_names, line)
parseCallEscape :: String -> (String, String)
parseCallEscape s
| not (all isSpace beforeOpen) = ("", "")
| null sinceOpen = ("", "")
| null sinceClosed = ("", "")
| null cmd = ("", "")
| otherwise = (cmd, tail sinceClosed)
where
(beforeOpen, sinceOpen) = span (/='(') s
(cmd, sinceClosed) = span (/=')') (tail sinceOpen)
checkPromptStringForErrors :: String -> Maybe String
checkPromptStringForErrors ('%':'c':'a':'l':'l':xs) =
case parseCallEscape xs of
("", "") -> Just ("Incorrect %call syntax. " ++
"Should be %call(a command and arguments).")
(_, afterClosed) -> checkPromptStringForErrors afterClosed
checkPromptStringForErrors ('%':'%':xs) = checkPromptStringForErrors xs
checkPromptStringForErrors (_:xs) = checkPromptStringForErrors xs
checkPromptStringForErrors "" = Nothing
generatePromptFunctionFromString :: String -> PromptFunction
generatePromptFunctionFromString promptS modules_names line =
processString promptS
where
processString :: String -> GHCi SDoc
processString ('%':'s':xs) =
liftM2 (<>) (return modules_list) (processString xs)
where
modules_list = hsep . map text . ordNub $ modules_names
processString ('%':'l':xs) =
liftM2 (<>) (return $ ppr line) (processString xs)
processString ('%':'d':xs) =
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%a %b %d"
processString ('%':'t':xs) =
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%H:%M:%S"
processString ('%':'T':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%I:%M:%S"
processString ('%':'@':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%I:%M %P"
processString ('%':'A':xs) = do
liftM2 (<>) (liftM text formatted_time) (processString xs)
where
formatted_time = liftIO $ formatCurrentTime "%H:%M"
processString ('%':'u':xs) =
liftM2 (<>) (liftM text user_name) (processString xs)
where
user_name = liftIO $ getUserName
processString ('%':'w':xs) =
liftM2 (<>) (liftM text current_directory) (processString xs)
where
current_directory = liftIO $ getCurrentDirectory
processString ('%':'o':xs) =
liftM ((text os) <>) (processString xs)
processString ('%':'a':xs) =
liftM ((text arch) <>) (processString xs)
processString ('%':'N':xs) =
liftM ((text compilerName) <>) (processString xs)
processString ('%':'V':xs) =
liftM ((text $ showVersion compilerVersion) <>) (processString xs)
processString ('%':'c':'a':'l':'l':xs) = do
respond <- liftIO $ do
(code, out, err) <-
readProcessWithExitCode
(head list_words) (tail list_words) ""
`catchIO` \e -> return (ExitFailure 1, "", show e)
case code of
ExitSuccess -> return out
_ -> do
hPutStrLn stderr err
return ""
liftM ((text respond) <>) (processString afterClosed)
where
(cmd, afterClosed) = parseCallEscape xs
list_words = words cmd
processString ('%':'%':xs) =
liftM ((char '%') <>) (processString xs)
processString (x:xs) =
liftM (char x <>) (processString xs)
processString "" =
return empty
mkPrompt :: GHCi String
mkPrompt = do
st <- getGHCiState
dflags <- getDynFlags
(context, modules_names, line) <- getInfoForPrompt
prompt_string <- (prompt st) modules_names line
let prompt_doc = context <> prompt_string
return (showSDoc dflags prompt_doc)
queryQueue :: GhciMonad m => m (Maybe String)
queryQueue = do
st <- getGHCiState