forked from ghc/ghc
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGHC.hs
More file actions
2057 lines (1796 loc) · 75.8 KB
/
Copy pathGHC.hs
File metadata and controls
2057 lines (1796 loc) · 75.8 KB
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 MultiWayIf #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE NondecreasingIndentation, ScopedTypeVariables #-}
{-# LANGUAGE TupleSections, NamedFieldPuns #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE LambdaCase #-}
-- -----------------------------------------------------------------------------
--
-- (c) The University of Glasgow, 2005-2012
--
-- The GHC API
--
-- -----------------------------------------------------------------------------
module GHC (
-- * Initialisation
defaultErrorHandler,
defaultCleanupHandler,
prettyPrintGhcErrors,
withSignalHandlers,
withCleanupSession,
-- * GHC Monad
Ghc, GhcT, GhcMonad(..), HscEnv,
runGhc, runGhcT, initGhcMonad,
printException,
handleSourceError,
-- * Flags and settings
DynFlags(..), GeneralFlag(..), Severity(..), Backend, gopt,
ncgBackend, llvmBackend, viaCBackend, interpreterBackend, noBackend,
GhcMode(..), GhcLink(..),
parseDynamicFlags, parseTargetFiles,
getSessionDynFlags,
setTopSessionDynFlags,
setSessionDynFlags,
setUnitDynFlags,
getProgramDynFlags, setProgramDynFlags,
setProgramHUG, setProgramHUG_,
#if defined(HAVE_INTERPRETER)
getInteractiveDynFlags, setInteractiveDynFlags,
normaliseInteractiveDynFlags, initialiseInteractiveDynFlags,
#endif
interpretPackageEnv,
-- * Logging
Logger, getLogger,
pushLogHook, popLogHook,
pushLogHookM, popLogHookM, modifyLogger,
putMsgM, putLogMsgM,
-- * Targets
Target(..), TargetId(..), Phase,
setTargets,
getTargets,
addTarget,
removeTarget,
guessTarget,
guessTargetId,
-- * Loading\/compiling the program
depanal, depanalE,
load, loadWithCache, LoadHowMuch(..),
#if defined(HAVE_INTERPRETER)
InteractiveImport(..),
#endif
SuccessFlag(..), succeeded, failed,
defaultWarnErrLogger, WarnErrLogger,
workingDirectoryChanged,
parseModule, typecheckModule, desugarModule,
ParsedModule(..), TypecheckedModule(..), DesugaredModule(..),
TypecheckedSource, ParsedSource, RenamedSource, -- ditto
TypecheckedMod, ParsedMod,
moduleInfo, renamedSource, typecheckedSource,
parsedSource, coreModule,
PkgQual(..),
-- ** Compiling to Core
CoreModule(..),
compileToCoreModule, compileToCoreSimplified,
-- * Inspecting the module structure of the program
ModuleGraph, emptyMG, mapMG, mkModuleGraph, mgModSummaries,
mgLookupModule,
ModSummary(..), ms_mod_name, ModLocation(..),
pattern ModLocation,
getModSummary,
getModuleGraph,
isLoaded,
isLoadedModule,
isLoadedHomeModule,
topSortModuleGraph,
-- * Inspecting modules
ModuleInfo,
getModuleInfo,
modInfoTyThings,
modInfoExports,
modInfoExportsWithSelectors,
modInfoInstances,
modInfoIsExportedName,
modInfoLookupName,
modInfoIface,
modInfoSafe,
lookupGlobalName,
findGlobalAnns,
mkNamePprCtxForModule,
ModIface,
ModIface_( mi_mod_info
, mi_module
, mi_sig_of
, mi_hsc_src
, mi_iface_hash
, mi_deps
, mi_public
, mi_exports
, mi_fixities
, mi_warns
, mi_anns
, mi_decls
, mi_defaults
, mi_simplified_core
, mi_top_env
, mi_insts
, mi_fam_insts
, mi_rules
, mi_trust
, mi_trust_pkg
, mi_complete_matches
, mi_docs
, mi_abi_hashes
, mi_ext_fields
, mi_hi_bytes
, mi_self_recomp_info
, mi_fix_fn
, mi_decl_warn_fn
, mi_export_warn_fn
, mi_hash_fn
),
pattern ModIface,
SafeHaskellMode(..),
-- * Printing
NamePprCtx, alwaysQualify,
-- * Interactive evaluation
#if defined(HAVE_INTERPRETER)
-- ** Executing statements
execStmt, execStmt', ExecOptions(..), execOptions, ExecResult(..),
resumeExec,
-- ** Adding new declarations
runDecls, runDeclsWithLocation, runParsedDecls,
-- ** Get/set the current context
parseImportDecl,
setContext, getContext,
#if defined(HAVE_INTERPRETER)
setGHCiMonad, getGHCiMonad,
#endif
-- ** Inspecting the current context
getBindings, getInsts, getNamePprCtx,
findModule, lookupModule,
findQualifiedModule, lookupQualifiedModule,
lookupLoadedHomeModuleByModuleName, lookupAllQualifiedModuleNames,
renamePkgQualM, renameRawPkgQualM,
isModuleTrusted, moduleTrustReqs,
getNamesInScope,
getRdrNamesInScope,
#if defined(HAVE_INTERPRETER)
getGRE,
#endif
moduleIsInterpreted,
getInfo,
showModule,
moduleIsBootOrNotObjectLinkable,
getNameToInstancesIndex,
-- ** Inspecting types and kinds
exprType, TcRnExprMode(..),
typeKind,
-- ** Looking up a Name
parseName,
lookupName,
-- ** Compiling expressions
HValue, parseExpr, compileParsedExpr,
GHC.Runtime.Eval.compileExpr, dynCompileExpr,
ForeignHValue,
compileExprRemote, compileParsedExprRemote,
-- ** Docs
getDocs, GetDocsFailure(..),
-- ** Other
runTcInteractive, -- Desired by some clients (#8878)
isStmt, hasImport, isImport, isDecl,
#endif
-- ** The debugger
#if defined(HAVE_INTERPRETER)
SingleStep(..),
Resume(..),
History(historyBreakpointId, historyEnclosingDecls),
GHC.getHistorySpan, getHistoryModule,
abandon, abandonAll,
getResumeContext,
GHC.obtainTermFromId, GHC.obtainTermFromVal, reconstructType,
modInfoModBreaks,
ModBreaks(..), BreakTickIndex,
BreakpointId(..), InternalBreakpointId(..),
GHC.Runtime.Eval.back,
GHC.Runtime.Eval.forward,
GHC.Runtime.Eval.setupBreakpoint,
#endif
-- * Abstract syntax elements
-- ** Units
Unit,
-- ** Modules
Module, mkModule, pprModule, moduleName, moduleUnit,
-- ** Names
Name,
isExternalName, nameModule, pprParenSymName, nameSrcSpan,
NamedThing(..),
RdrName(Qual,Unqual),
-- ** Identifiers
Id, idType,
isImplicitId, isDeadBinder,
isExportedId, isLocalId, isGlobalId,
isRecordSelector,
isPrimOpId, isFCallId, isClassOpId_maybe,
isDataConWorkId, idDataCon,
isDeadEndId, isDictonaryId,
recordSelectorTyCon,
-- ** Type constructors
TyCon,
tyConTyVars, tyConDataCons, tyConArity,
isClassTyCon, isTypeSynonymTyCon, isTypeFamilyTyCon, isNewTyCon,
isPrimTyCon,
isFamilyTyCon, isOpenFamilyTyCon, isOpenTypeFamilyTyCon,
tyConClass_maybe,
synTyConRhs_maybe, synTyConDefn_maybe, tyConKind,
-- ** Type variables
TyVar,
alphaTyVars,
-- ** Data constructors
DataCon,
dataConType, dataConTyCon, dataConFieldLabels,
dataConIsInfix, isVanillaDataCon, dataConWrapperType,
dataConSrcBangs,
StrictnessMark(..), isMarkedStrict,
-- ** Classes
Class,
classMethods, classSCTheta, classTvsFds, classATs,
pprFundeps,
-- ** Instances
ClsInst,
instanceDFunId,
pprInstance, pprInstanceHdr,
pprFamInst,
FamInst,
-- ** Types and Kinds
Type, splitForAllTyCoVars, funResultTy,
pprParendType, pprTypeApp,
Kind,
PredType,
ThetaType, pprForAll, pprThetaArrowTy,
#if defined(HAVE_INTERPRETER)
parseInstanceHead,
getInstancesForType,
#endif
-- ** Entities
TyThing(..),
-- ** Syntax
module GHC.Hs, -- ToDo: remove extraneous bits
-- ** Fixities
FixityDirection(..),
defaultFixity, maxPrecedence,
negateFixity,
compareFixity,
LexicalFixity(..),
-- ** Source locations
SrcLoc(..), RealSrcLoc,
mkSrcLoc, noSrcLoc,
srcLocFile, srcLocLine, srcLocCol,
SrcSpan(..), RealSrcSpan,
mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
srcSpanStart, srcSpanEnd,
srcSpanFile,
srcSpanStartLine, srcSpanEndLine,
srcSpanStartCol, srcSpanEndCol,
-- ** Located
GenLocated(..), Located, RealLocated,
-- *** Constructing Located
noLoc, mkGeneralLocated,
-- *** Deconstructing Located
getLoc, unLoc,
getRealSrcSpan, unRealSrcSpan,
-- *** Combining and comparing Located values
eqLocated, cmpLocated, combineLocs, addCLoc,
leftmost_smallest, leftmost_largest, rightmost_smallest,
spans, isSubspanOf,
-- * Exceptions
GhcException(..), showGhcException,
GhcApiError(..),
-- * Token stream manipulations
Token,
getTokenStream, getRichTokenStream,
showRichTokenStream, addSourceToTokens,
-- * Pure interface to the parser
parser,
-- * API Annotations
EpaComment(..)
) where
{-
ToDo:
* inline bits of GHC.Driver.Main here to simplify layering: hscTcExpr, hscStmt.
-}
import GHC.Prelude hiding (init)
import GHC.Platform
import GHC.Driver.Phases ( Phase(..), isHaskellSrcFilename
, isSourceFilename, startPhase )
import GHC.Driver.Env
import GHC.Driver.Errors
import GHC.Driver.Errors.Types
import GHC.Driver.CmdLine
import GHC.Driver.Session
import GHC.Driver.Session.Inspect
import GHC.Driver.Backend
import GHC.Driver.Config.Finder (initFinderOpts)
import GHC.Driver.Config.Parser (initParserOpts)
import GHC.Driver.Config.Logger (initLogFlags)
import GHC.Driver.Config.Diagnostic
import GHC.Driver.Main
import GHC.Driver.Make
import GHC.Driver.Hooks
import GHC.Driver.Monad
import GHC.Driver.Ppr
#if defined(HAVE_INTERPRETER)
import GHC.Driver.Config.StgToJS (initStgToJSConfig)
import GHC.ByteCode.Types
import GHC.Runtime.Loader
import GHC.Runtime.Eval
import GHC.Runtime.Interpreter
import GHC.Runtime.Interpreter.Init
import GHC.Driver.Config.Interpreter
import GHC.Runtime.Context
import GHCi.RemoteTypes
#endif
import qualified GHC.Parser as Parser
import GHC.Parser.Lexer
import GHC.Parser.Annotation
import GHC.Parser.Utils
import GHC.Iface.Env ( trace_if )
import GHC.Iface.Load ( loadSysInterface )
import GHC.Hs
import GHC.Builtin.Types.Prim ( alphaTyVars )
import GHC.Data.StringBuffer
import GHC.Data.FastString
import qualified GHC.LanguageExtensions as LangExt
import GHC.Rename.Names (renamePkgQual, renameRawPkgQual)
import GHC.Tc.Utils.Monad ( finalSafeMode, fixSafeInstances, initIfaceTcRn )
import GHC.Tc.Types
import GHC.Tc.Utils.TcType
import GHC.Tc.Module
import GHC.Tc.Utils.Instantiate
import GHC.Tc.Instance.Family
import GHC.Utils.TmpFs
import GHC.Utils.Error
import GHC.Utils.Exception
import GHC.Utils.Monad
import GHC.Utils.Misc
import GHC.Utils.Outputable
import GHC.Utils.Panic
import GHC.Utils.Logger
import GHC.Utils.Fingerprint
import GHC.Core.Predicate
import GHC.Core.Type hiding( typeKind )
import GHC.Core.TyCon
import GHC.Core.TyCo.Ppr ( pprForAll )
import GHC.Core.Class
import GHC.Core.DataCon
import GHC.Core.FamInstEnv ( FamInst, famInstEnvElts, orphNamesOfFamInst )
import GHC.Core.InstEnv
import GHC.Core
import GHC.Data.Maybe
import GHC.Types.Id
import GHC.Types.Name hiding ( varName )
import GHC.Types.Avail
import GHC.Types.SrcLoc
import GHC.Types.TyThing.Ppr ( pprFamInst )
import GHC.Types.Annotations
import GHC.Types.Name.Set
import GHC.Types.Name.Reader
import GHC.Types.SourceError
import GHC.Types.SafeHaskell
import GHC.Types.Error
import GHC.Types.Fixity
import GHC.Types.Target
import GHC.Types.Basic
import GHC.Types.TyThing
import GHC.Types.Name.Env
import GHC.Types.TypeEnv
import GHC.Types.PkgQual
import GHC.Unit
import GHC.Unit.Env as UnitEnv
import GHC.Unit.Finder
import GHC.Unit.Module.ModIface
import GHC.Unit.Module.ModGuts
import GHC.Unit.Module.ModDetails
import GHC.Unit.Module.ModSummary
import GHC.Unit.Module.Graph
import GHC.Unit.Home.ModInfo
import qualified GHC.Unit.Home.Graph as HUG
import Control.Applicative ((<|>))
import Control.Monad
import Control.Monad.Catch as MC
import Data.Foldable
import Data.Function ((&))
import Data.IORef
import Data.List (isPrefixOf)
import Data.Typeable ( Typeable )
import Data.Word ( Word8 )
import qualified Data.Map.Strict as Map
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Sequence as Seq
import System.Directory
import System.Environment ( getEnv, getProgName )
import System.Exit ( exitWith, ExitCode(..) )
import System.FilePath
import System.IO.Error ( isDoesNotExistError )
-- %************************************************************************
-- %* *
-- Initialisation: exception handlers
-- %* *
-- %************************************************************************
-- | Install some default exception handlers and run the inner computation.
-- Unless you want to handle exceptions yourself, you should wrap this around
-- the top level of your program. The default handlers output the error
-- message(s) to stderr and exit cleanly.
defaultErrorHandler :: (ExceptionMonad m)
=> FatalMessager -> FlushOut -> m a -> m a
defaultErrorHandler fm (FlushOut flushOut) inner =
-- top-level exception handler: any unrecognised exception is a compiler bug.
MC.handle (\exception -> liftIO $ do
flushOut
case fromException exception of
-- an IO exception probably isn't our fault, so don't panic
Just (ioe :: IOException) ->
fm (show ioe)
_ -> case fromException exception of
Just UserInterrupt ->
-- Important to let this one propagate out so our
-- calling process knows we were interrupted by ^C
liftIO $ throwIO UserInterrupt
Just StackOverflow ->
fm "stack overflow: use +RTS -K<size> to increase it"
Just HeapOverflow ->
fm "heap overflow: use +RTS -M<size> to increase maximum heap size"
_ -> case fromException exception of
Just (ex :: ExitCode) -> liftIO $ throwIO ex
_ ->
fm (show (Panic (show exception)))
exitWith (ExitFailure 1)
) $
-- error messages propagated as exceptions
handleGhcException
(\ge -> liftIO $ do
flushOut
case ge of
Signal _ -> return ()
ProgramError _ -> fm (show ge)
CmdLineError _ -> fm ("<command line>: " ++ show ge)
_ -> do
progName <- getProgName
fm (progName ++ ": " ++ show ge)
exitWith (ExitFailure 1)
) $
inner
-- | This function is no longer necessary, cleanup is now done by
-- runGhc/runGhcT.
{-# DEPRECATED defaultCleanupHandler "Cleanup is now done by runGhc/runGhcT" #-}
defaultCleanupHandler :: (ExceptionMonad m) => DynFlags -> m a -> m a
defaultCleanupHandler _ m = m
where _warning_suppression = m `MC.onException` undefined
-- %************************************************************************
-- %* *
-- The Ghc Monad
-- %* *
-- %************************************************************************
-- | Run function for the 'Ghc' monad.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
--
-- Any errors not handled inside the 'Ghc' action are propagated as IO
-- exceptions.
runGhc :: Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> Ghc a -- ^ The action to perform.
-> IO a
runGhc mb_top_dir ghc = do
ref <- newIORef (panic "empty session")
let session = Session ref
flip unGhc session $ withSignalHandlers $ do -- catch ^C
initGhcMonad mb_top_dir
withCleanupSession ghc
-- | Run function for 'GhcT' monad transformer.
--
-- It initialises the GHC session and warnings via 'initGhcMonad'. Each call
-- to this function will create a new session which should not be shared among
-- several threads.
runGhcT :: ExceptionMonad m =>
Maybe FilePath -- ^ See argument to 'initGhcMonad'.
-> GhcT m a -- ^ The action to perform.
-> m a
runGhcT mb_top_dir ghct = do
ref <- liftIO $ newIORef (panic "empty session")
let session = Session ref
flip unGhcT session $ withSignalHandlers $ do -- catch ^C
initGhcMonad mb_top_dir
withCleanupSession ghct
withCleanupSession :: GhcMonad m => m a -> m a
withCleanupSession ghc = ghc `MC.finally` cleanup
where
cleanup = do
hsc_env <- getSession
let dflags = hsc_dflags hsc_env
let logger = hsc_logger hsc_env
let tmpfs = hsc_tmpfs hsc_env
liftIO $ do
unless (gopt Opt_KeepTmpFiles dflags) $ do
cleanTempFiles logger tmpfs
cleanTempDirs logger tmpfs
#if defined(HAVE_INTERPRETER)
traverse_ stopInterp (hsc_interp hsc_env)
#endif
-- exceptions will be blocked while we clean the temporary files,
-- so there shouldn't be any difficulty if we receive further
-- signals.
-- | Initialise a GHC session.
--
-- If you implement a custom 'GhcMonad' you must call this function in the
-- monad run function. It will initialise the session variable and clear all
-- warnings.
--
-- The first argument should point to the directory where GHC's library files
-- reside. More precisely, this should be the output of @ghc --print-libdir@
-- of the version of GHC the module using this API is compiled with. For
-- portability, you should use the @ghc-paths@ package, available at
-- <http://hackage.haskell.org/package/ghc-paths>.
initGhcMonad :: GhcMonad m => Maybe FilePath -> m ()
initGhcMonad mb_top_dir = setSession =<< liftIO ( do
#if !defined(javascript_HOST_ARCH)
-- The call to c_keepCAFsForGHCi must not be optimized away. Even in non-debug builds.
-- So we can't use assertM here.
-- See Note [keepCAFsForGHCi] in keepCAFsForGHCi.c for details about why.
!keep_cafs <- c_keepCAFsForGHCi
massert keep_cafs
#endif
initHscEnv mb_top_dir
)
-- %************************************************************************
-- %* *
-- Flags & settings
-- %* *
-- %************************************************************************
-- $DynFlags
--
-- The GHC session maintains two sets of 'DynFlags':
--
-- * The "interactive" @DynFlags@, which are used for everything
-- related to interactive evaluation, including 'runStmt',
-- 'runDecls', 'exprType', 'lookupName' and so on (everything
-- under \"Interactive evaluation\" in this module).
--
-- * The "program" @DynFlags@, which are used when loading
-- whole modules with 'load'
--
-- 'setInteractiveDynFlags', 'getInteractiveDynFlags' work with the
-- interactive @DynFlags@.
--
-- 'setProgramDynFlags', 'getProgramDynFlags' work with the
-- program @DynFlags@.
--
-- 'setSessionDynFlags' sets both @DynFlags@, and 'getSessionDynFlags'
-- retrieves the program @DynFlags@ (for backwards compatibility).
-- This is a compatibility function which sets dynflags for the top session
-- as well as the unit.
setSessionDynFlags :: (HasCallStack, GhcMonad m) => DynFlags -> m ()
setSessionDynFlags dflags0 = do
hsc_env <- getSession
logger <- getLogger
dflags <- checkNewDynFlags logger dflags0
let all_uids = hsc_all_home_unit_ids hsc_env
case S.toList all_uids of
[uid] -> do
setUnitDynFlagsNoCheck uid dflags
modifySession (hscUpdateLoggerFlags . hscSetActiveUnitId (homeUnitId_ dflags))
dflags' <- getDynFlags
setTopSessionDynFlags dflags'
[] -> panic "nohue"
_ -> panic "setSessionDynFlags can only be used with a single home unit"
setUnitDynFlags :: GhcMonad m => UnitId -> DynFlags -> m ()
setUnitDynFlags uid dflags0 = do
logger <- getLogger
dflags1 <- checkNewDynFlags logger dflags0
setUnitDynFlagsNoCheck uid dflags1
setUnitDynFlagsNoCheck :: GhcMonad m => UnitId -> DynFlags -> m ()
setUnitDynFlagsNoCheck uid dflags1 = do
logger <- getLogger
hsc_env <- getSession
let old_hue = ue_findHomeUnitEnv uid (hsc_unit_env hsc_env)
let cached_unit_dbs = homeUnitEnv_unit_dbs old_hue
(dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags1 cached_unit_dbs (hsc_all_home_unit_ids hsc_env)
updated_dflags <- liftIO $ updatePlatformConstants dflags1 mconstants
let upd hue =
hue
{ homeUnitEnv_units = unit_state
, homeUnitEnv_unit_dbs = Just dbs
, homeUnitEnv_dflags = updated_dflags
, homeUnitEnv_home_unit = Just home_unit
}
let unit_env = UnitEnv.ue_updateHomeUnitEnv upd uid (hsc_unit_env hsc_env)
let dflags = updated_dflags
let unit_env0 = unit_env
{ ue_platform = targetPlatform dflags
, ue_namever = ghcNameVersion dflags
}
-- if necessary, change the key for the currently active unit
-- as the dynflags might have been changed
-- This function is called on every --make invocation because at the start of
-- the session there is one fake unit called main which is immediately replaced
-- after the DynFlags are parsed.
let !unit_env1 =
if homeUnitId_ dflags /= uid
then
UnitEnv.renameUnitId
uid
(homeUnitId_ dflags)
unit_env0
else unit_env0
modifySession $ \h -> h{ hsc_unit_env = unit_env1
}
invalidateModSummaryCache
setTopSessionDynFlags :: GhcMonad m => DynFlags -> m ()
setTopSessionDynFlags dflags = do
hsc_env <- getSession
logger <- getLogger
#if defined(HAVE_INTERPRETER)
let platform = targetPlatform dflags
let unit_env = hsc_unit_env hsc_env
let tmpfs = hsc_tmpfs hsc_env
let finder_cache = hsc_FC hsc_env
interp_opts' <- liftIO $ initInterpOpts dflags
let interp_opts = interp_opts'
{ interpCreateProcess = createIservProcessHook (hsc_hooks hsc_env)
}
interp <- liftIO $ initInterpreter tmpfs logger platform finder_cache unit_env interp_opts
#else
-- No interpreter support (HAVE_INTERPRETER not defined)
let interp = Nothing
#endif
modifySession $ \h -> hscSetFlags dflags
#if defined(HAVE_INTERPRETER)
h{ hsc_IC = (hsc_IC h){ ic_dflags = dflags }
, hsc_interp = hsc_interp h <|> interp
}
#else
h{ hsc_interp = hsc_interp h <|> interp }
#endif
invalidateModSummaryCache
-- | Sets the program 'DynFlags'. Note: this invalidates the internal
-- cached module graph, causing more work to be done the next time
-- 'load' is called.
--
-- Returns a boolean indicating if preload units have changed and need to be
-- reloaded.
setProgramDynFlags :: GhcMonad m => DynFlags -> m Bool
setProgramDynFlags dflags = setProgramDynFlags_ True dflags
setProgramDynFlags_ :: GhcMonad m => Bool -> DynFlags -> m Bool
setProgramDynFlags_ invalidate_needed dflags = do
logger <- getLogger
dflags0 <- checkNewDynFlags logger dflags
dflags_prev <- getProgramDynFlags
let changed = packageFlagsChanged dflags_prev dflags0
if changed
then do
-- additionally, set checked dflags so we don't lose fixes
old_unit_env <- ue_setFlags dflags0 . hsc_unit_env <$> getSession
home_unit_graph <- forM (ue_home_unit_graph old_unit_env) $ \homeUnitEnv -> do
let cached_unit_dbs = homeUnitEnv_unit_dbs homeUnitEnv
dflags = homeUnitEnv_dflags homeUnitEnv
old_hpt = homeUnitEnv_hpt homeUnitEnv
home_units = HUG.allUnits (ue_home_unit_graph old_unit_env)
(dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags cached_unit_dbs home_units
updated_dflags <- liftIO $ updatePlatformConstants dflags0 mconstants
pure HomeUnitEnv
{ homeUnitEnv_units = unit_state
, homeUnitEnv_unit_dbs = Just dbs
, homeUnitEnv_dflags = updated_dflags
, homeUnitEnv_hpt = old_hpt
, homeUnitEnv_home_unit = Just home_unit
}
let dflags1 = homeUnitEnv_dflags $ HUG.unitEnv_lookup (ue_currentUnit old_unit_env) home_unit_graph
let unit_env = UnitEnv
{ ue_platform = targetPlatform dflags1
, ue_namever = ghcNameVersion dflags1
, ue_home_unit_graph = home_unit_graph
, ue_current_unit = ue_currentUnit old_unit_env
, ue_module_graph = ue_module_graph old_unit_env
, ue_eps = ue_eps old_unit_env
}
modifySession $ \h -> hscSetFlags dflags1 h{ hsc_unit_env = unit_env }
else modifySession (hscSetFlags dflags0)
when invalidate_needed $ invalidateModSummaryCache
return changed
-- | Sets the program 'HomeUnitGraph'.
--
-- Sets the given 'HomeUnitGraph' as the 'HomeUnitGraph' of the current
-- session. If the package flags change, we reinitialise the 'UnitState'
-- of all 'HomeUnitEnv's in the current session.
--
-- This function unconditionally invalidates the module graph cache.
--
-- Precondition: the given 'HomeUnitGraph' must have the same keys as the 'HomeUnitGraph'
-- of the current session. I.e., assuming the new 'HomeUnitGraph' is called
-- 'new_hug', then:
--
-- @
-- do
-- hug <- hsc_HUG \<$\> getSession
-- pure $ unitEnv_keys new_hug == unitEnv_keys hug
-- @
--
-- If this precondition is violated, the function will crash.
--
-- Conceptually, similar to 'setProgramDynFlags', but performs the same check
-- for all 'HomeUnitEnv's.
setProgramHUG :: GhcMonad m => HomeUnitGraph -> m Bool
setProgramHUG =
setProgramHUG_ True
-- | Same as 'setProgramHUG', but gives you control over whether you want to
-- invalidate the module graph cache.
setProgramHUG_ :: GhcMonad m => Bool -> HomeUnitGraph -> m Bool
setProgramHUG_ invalidate_needed new_hug0 = do
logger <- getLogger
hug0 <- hsc_HUG <$> getSession
(changed, new_hug1) <- checkNewHugDynFlags logger hug0 new_hug0
if changed
then do
unit_env0 <- hsc_unit_env <$> getSession
home_unit_graph <- HUG.unitEnv_traverseWithKey
(updateHomeUnit logger unit_env0 new_hug1)
(ue_home_unit_graph unit_env0)
let dflags1 = homeUnitEnv_dflags $ HUG.unitEnv_lookup (ue_currentUnit unit_env0) home_unit_graph
let unit_env = UnitEnv
{ ue_platform = targetPlatform dflags1
, ue_namever = ghcNameVersion dflags1
, ue_home_unit_graph = home_unit_graph
, ue_current_unit = ue_currentUnit unit_env0
, ue_eps = ue_eps unit_env0
, ue_module_graph = ue_module_graph unit_env0
}
modifySession $ \h ->
-- hscSetFlags takes care of updating the logger as well.
hscSetFlags dflags1 h{ hsc_unit_env = unit_env }
else do
modifySession (\env ->
env
-- Set the new 'HomeUnitGraph'.
& hscUpdateHUG (const new_hug1)
-- hscSetActiveUnitId makes sure that the 'hsc_dflags'
-- are up-to-date.
& hscSetActiveUnitId (hscActiveUnitId env)
-- Make sure the logger is also updated.
& hscUpdateLoggerFlags)
when invalidate_needed $ invalidateModSummaryCache
pure changed
where
checkNewHugDynFlags :: GhcMonad m => Logger -> HomeUnitGraph -> HomeUnitGraph -> m (Bool, HomeUnitGraph)
checkNewHugDynFlags logger old_hug new_hug = do
-- Traverse the new HUG and check its 'DynFlags'.
-- The old 'HUG' is used to check whether package flags have changed.
hugWithCheck <- HUG.unitEnv_traverseWithKey
(\unitId homeUnit -> do
let newFlags = homeUnitEnv_dflags homeUnit
oldFlags = homeUnitEnv_dflags (HUG.unitEnv_lookup unitId old_hug)
checkedFlags <- checkNewDynFlags logger newFlags
pure
( packageFlagsChanged oldFlags checkedFlags
, homeUnit { homeUnitEnv_dflags = checkedFlags }
)
)
new_hug
let
-- Did any of the package flags change?
changed = or $ fmap fst hugWithCheck
hug = fmap snd hugWithCheck
pure (changed, hug)
updateHomeUnit :: GhcMonad m => Logger -> UnitEnv -> HomeUnitGraph -> (UnitId -> HomeUnitEnv -> m HomeUnitEnv)
updateHomeUnit logger unit_env updates = \uid homeUnitEnv -> do
let cached_unit_dbs = homeUnitEnv_unit_dbs homeUnitEnv
dflags = case HUG.unitEnv_lookup_maybe uid updates of
Nothing -> homeUnitEnv_dflags homeUnitEnv
Just env -> homeUnitEnv_dflags env
old_hpt = homeUnitEnv_hpt homeUnitEnv
home_units = HUG.allUnits (ue_home_unit_graph unit_env)
(dbs,unit_state,home_unit,mconstants) <- liftIO $ initUnits logger dflags cached_unit_dbs home_units
updated_dflags <- liftIO $ updatePlatformConstants dflags mconstants
pure HomeUnitEnv
{ homeUnitEnv_units = unit_state
, homeUnitEnv_unit_dbs = Just dbs
, homeUnitEnv_dflags = updated_dflags
, homeUnitEnv_hpt = old_hpt
, homeUnitEnv_home_unit = Just home_unit
}
-- When changing the DynFlags, we want the changes to apply to future
-- loads, but without completely discarding the program. But the
-- DynFlags are cached in each ModSummary in the hsc_mod_graph, so
-- after a change to DynFlags, the changes would apply to new modules
-- but not existing modules; this seems undesirable.
--
-- Furthermore, the GHC API client might expect that changing
-- log_action would affect future compilation messages, but for those
-- modules we have cached ModSummaries for, we'll continue to use the
-- old log_action. This is definitely wrong (#7478).
--
-- Hence, we invalidate the ModSummary cache after changing the
-- DynFlags. We do this by tweaking the hash on each ModSummary, so
-- that the next downsweep will think that all the files have changed
-- and preprocess them again. This won't necessarily cause everything
-- to be recompiled, because by the time we check whether we need to
-- recompile a module, we'll have re-summarised the module and have a
-- correct ModSummary.
--
invalidateModSummaryCache :: GhcMonad m => m ()
invalidateModSummaryCache =
modifySession $ \hsc_env -> setModuleGraph (mapMG inval (hsc_mod_graph hsc_env)) hsc_env
where
inval ms = ms { ms_hs_hash = fingerprint0 }
-- | Returns the program 'DynFlags'.
getProgramDynFlags :: GhcMonad m => m DynFlags
getProgramDynFlags = getSessionDynFlags
-- | Set the 'DynFlags' used to evaluate interactive expressions.
-- Also initialise (load) plugins.
--
-- Note: this cannot be used for changes to packages. Use
-- 'setSessionDynFlags', or 'setProgramDynFlags' and then copy the
-- 'unitState' into the interactive @DynFlags@.
#if defined(HAVE_INTERPRETER)
setInteractiveDynFlags :: GhcMonad m => DynFlags -> m ()
setInteractiveDynFlags dflags = do
logger <- getLogger
icdflags <- normaliseInteractiveDynFlags logger dflags
modifySessionM (initialiseInteractiveDynFlags icdflags)
-- | Get the 'DynFlags' used to evaluate interactive expressions.
getInteractiveDynFlags :: GhcMonad m => m DynFlags
getInteractiveDynFlags = withSession $ \h -> return (ic_dflags (hsc_IC h))
#endif
parseDynamicFlags
:: MonadIO m
=> Logger
-> DynFlags
-> [Located String]
-> m (DynFlags, [Located String], Messages DriverMessage)
parseDynamicFlags logger dflags cmdline = do
(dflags1, leftovers, warns) <- parseDynamicFlagsCmdLine logger dflags cmdline
-- flags that have just been read are used by the logger when loading package
-- env (this is checked by T16318)
let logger1 = setLogFlags logger (initLogFlags dflags1)
dflags2 <- liftIO $ interpretPackageEnv logger1 dflags1
return (dflags2, leftovers, warns)
-- | Parse command line arguments that look like files.
-- First normalises its arguments and then splits them into source files
-- and object files.
-- A source file can be turned into a 'Target' via 'guessTarget'
parseTargetFiles :: DynFlags -> [String] -> (DynFlags, [(String, Maybe Phase)], [String])
parseTargetFiles dflags0 fileish_args =
let
normal_fileish_paths = map normalise_hyp fileish_args
(srcs, raw_objs) = partition_args normal_fileish_paths [] []
objs = map (augmentByWorkingDirectory dflags0) raw_objs
dflags1 = dflags0 { ldInputs = map (FileOption "") objs
++ ldInputs dflags0 }
{-
We split out the object files (.o, .dll) and add them
to ldInputs for use by the linker.
The following things should be considered compilation manager inputs: