TcRnTypes.hs 120 KB
Newer Older
Austin Seipp's avatar
Austin Seipp committed
1
2
3
{-
(c) The University of Glasgow 2006-2012
(c) The GRASP Project, Glasgow University, 1992-2002
4

5
6
7
8
9
10
11
12
13
14
15
16

Various types used during typechecking, please see TcRnMonad as well for
operations on these types. You probably want to import it, instead of this
module.

All the monads exported here are built on top of the same IOEnv monad. The
monad functions like a Reader monad in the way it passes the environment
around. This is done to allow the environment to be manipulated in a stack
like fashion when entering expressions... ect.

For state that is global and should be returned at the end (e.g not part
of the stack mechanism), you should use an TcRef (= IORef) to store them.
Austin Seipp's avatar
Austin Seipp committed
17
-}
18

19
20
{-# LANGUAGE CPP, ExistentialQuantification, GeneralizedNewtypeDeriving,
             ViewPatterns #-}
21

22
module TcRnTypes(
23
24
        TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
        TcRef,
25

26
27
28
29
        -- The environment types
        Env(..),
        TcGblEnv(..), TcLclEnv(..),
        IfGblEnv(..), IfLclEnv(..),
30
        tcVisibleOrphanMods,
31

32
33
34
        -- Frontend types (shouldn't really be here)
        FrontendResult(..),

35
        -- Renamer types
Adam Gundry's avatar
Adam Gundry committed
36
        ErrCtxt, RecFieldEnv,
37
38
        ImportAvails(..), emptyImportAvails, plusImportAvails,
        WhereFrom(..), mkModDeps,
39

40
        -- Typechecker types
41
42
        TcTypeEnv, TcIdBinderStack, TcIdBinder(..),
        TcTyThing(..), PromotionErr(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
43
        SelfBootInfo(..),
44
        pprTcTyThingCategory, pprPECategory,
45

46
47
48
49
        -- Desugaring types
        DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
        DsMetaEnv, DsMetaVal(..),

50
        -- Template Haskell
51
52
        ThStage(..), SpliceType(..), PendingStuff(..),
        topStage, topAnnStage, topSpliceStage,
53
        ThLevel, impLevel, outerLevel, thLevel,
54

55
        -- Arrows
56
        ArrowCtxt(..),
ross's avatar
ross committed
57

58
59
60
61
62
        -- TcSigInfo
        TcSigInfo(..), TcIdSigInfo(..), TcPatSynInfo(..), TcIdSigBndr(..),
        findScopedTyVars, isPartialSig, noCompleteSig, tcSigInfoName,
        completeIdSigPolyId, completeSigPolyId_maybe, completeIdSigPolyId_maybe,

63
        -- Canonical constraints
64
65
        Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
        singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
66
        isEmptyCts, isCTyEqCan, isCFunEqCan,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
67
        isCDictCan_Maybe, isCFunEqCan_maybe,
68
        isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
69
        isGivenCt, isHoleCt, isOutOfScopeCt, isExprHoleCt, isTypeHoleCt,
70
        isUserTypeErrorCt, isCallStackCt, getUserTypeErrorMsg,
71
        ctEvidence, ctLoc, setCtLoc, ctPred, ctFlavour, ctEqRel, ctOrigin,
72
        mkTcEqPredLikeEv,
73
        mkNonCanonical, mkNonCanonicalCt,
74
        ctEvPred, ctEvLoc, ctEvOrigin, ctEvEqRel,
75
        ctEvTerm, ctEvCoercion, ctEvId,
76
77
78
        tyCoVarsOfCt, tyCoVarsOfCts,
        tyCoVarsOfCtList, tyCoVarsOfCtsList,
        toDerivedCt,
79

80
        WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
81
        toDerivedWC,
82
83
        andWC, unionsWC, mkSimpleWC, mkImplicWC,
        addInsols, addSimples, addImplics,
84
        tyCoVarsOfWC, dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
85
        isDroppableDerivedLoc, insolubleImplic,
86
        arisesFromGivens,
87

88
        Implication(..), ImplicStatus(..), isInsolubleStatus,
89
90
        SubGoalDepth, initialSubGoalDepth,
        bumpSubGoalDepth, subGoalDepthExceeded,
91
        CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
92
        ctLocTypeOrKind_maybe,
93
        ctLocDepth, bumpCtLocDepth,
thomasw's avatar
thomasw committed
94
        setCtLocOrigin, setCtLocEnv, setCtLocSpan,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
95
96
        CtOrigin(..), exprCtOrigin, matchesCtOrigin, grhssCtOrigin,
        ErrorThing(..), mkErrorThing, errorThingNumArgs_maybe,
97
98
        TypeOrKind(..), isTypeLevel, isKindLevel,
        pprCtOrigin, pprCtLoc,
99
        pushErrCtxt, pushErrCtxtSameOrigin,
100

101
        SkolemInfo(..), pprSigSkolInfo, pprSkolInfo,
102

103
104
        CtEvidence(..), TcEvDest(..),
        mkGivenLoc, mkKindLoc, toKindLoc,
105
        isWanted, isGiven, isDerived,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
106
        ctEvRole,
107

Adam Gundry's avatar
Adam Gundry committed
108
109
110
        -- Constraint solver plugins
        TcPlugin(..), TcPluginResult(..), TcPluginSolver,
        TcPluginM, runTcPluginM, unsafeTcPluginTcM,
111
        getEvBindsTcPluginM_maybe,
Adam Gundry's avatar
Adam Gundry committed
112

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
113
        CtFlavour(..), ctEvFlavour,
114
        CtFlavourRole, ctEvFlavourRole, ctFlavourRole,
115
116
        eqCanRewrite, eqCanRewriteFR,  eqCanDischarge,
        funEqCanDischarge, funEqCanDischargeFR,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
117

118
        -- Pretty printing
Austin Seipp's avatar
Austin Seipp committed
119
        pprEvVarTheta,
120
        pprEvVars, pprEvVarWithType,
121

122
        -- Misc other types
123
        TcId, TcIdSet, HoleSort(..)
124

125
126
127
128
  ) where

#include "HsVersions.h"

129
import HsSyn
Facundo Domínguez's avatar
Facundo Domínguez committed
130
import CoreSyn
131
import HscTypes
132
import TcEvidence
133
import Type
134
import Class    ( Class )
135
import TyCon    ( TyCon )
136
import Coercion ( Coercion, mkHoleCo )
Gergő Érdi's avatar
Gergő Érdi committed
137
import ConLike  ( ConLike(..) )
138
import DataCon  ( DataCon, dataConUserType, dataConOrigArgTys )
139
import PatSyn   ( PatSyn, patSynType )
140
import Id       ( idName )
141
142
import PrelNames ( callStackTyConKey, ipClassKey )
import Unique ( hasKey )
Adam Gundry's avatar
Adam Gundry committed
143
import FieldLabel ( FieldLabel )
144
import TcType
145
import Annotations
146
147
import InstEnv
import FamInstEnv
148
import PmExpr
149
import IOEnv
150
151
import RdrName
import Name
152
import NameEnv
153
import NameSet
154
import Avail
155
import Var
156
import FV
157
import VarEnv
158
import Module
159
160
161
import SrcLoc
import VarSet
import ErrUtils
162
import UniqFM
163
164
import UniqSupply
import BasicTypes
165
import Bag
Ian Lynagh's avatar
Ian Lynagh committed
166
import DynFlags
167
import Outputable
168
import ListSetOps
169
import FastString
170
import GHC.Fingerprint
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
171
import qualified GHC.LanguageExtensions as LangExt
172

173
import Control.Monad (ap, liftM, msum)
quchen's avatar
quchen committed
174
175
176
#if __GLASGOW_HASKELL__ > 710
import qualified Control.Monad.Fail as MonadFail
#endif
177
178

#ifdef GHCI
179
180
181
import Data.Map      ( Map )
import Data.Dynamic  ( Dynamic )
import Data.Typeable ( TypeRep )
182
import GHCi.Message
183
import GHCi.RemoteTypes
184

185
186
import qualified Language.Haskell.TH as TH
#endif
187

Austin Seipp's avatar
Austin Seipp committed
188
189
190
{-
************************************************************************
*                                                                      *
191
               Standard monad definition for TcRn
192
    All the combinators for the monad can be found in TcRnMonad
Austin Seipp's avatar
Austin Seipp committed
193
194
*                                                                      *
************************************************************************
195

196
The monad itself has to be defined here, because it is mentioned by ErrCtxt
Austin Seipp's avatar
Austin Seipp committed
197
-}
198

Gergő Érdi's avatar
Gergő Érdi committed
199
type TcRnIf a b = IOEnv (Env a b)
200
201
202
203
204
205
206
207
208
209
210
211
type TcRn       = TcRnIf TcGblEnv TcLclEnv    -- Type inference
type IfM lcl    = TcRnIf IfGblEnv lcl         -- Iface stuff
type IfG        = IfM ()                      --    Top level
type IfL        = IfM IfLclEnv                --    Nested
type DsM        = TcRnIf DsGblEnv DsLclEnv    -- Desugaring

-- TcRn is the type-checking and renaming monad: the main monad that
-- most type-checking takes place in.  The global environment is
-- 'TcGblEnv', which tracks all of the top-level type-checking
-- information we've accumulated while checking a module, while the
-- local environment is 'TcLclEnv', which tracks local information as
-- we move inside expressions.
Edward Z. Yang's avatar
Edward Z. Yang committed
212
213
214
215
216
217

-- | Historical "renaming monad" (now it's just 'TcRn').
type RnM  = TcRn

-- | Historical "type-checking monad" (now it's just 'TcRn').
type TcM  = TcRn
218

219
220
221
222
-- We 'stack' these envs through the Reader like monad infastructure
-- as we move into an expression (although the change is focused in
-- the lcl type).
data Env gbl lcl
223
  = Env {
224
225
        env_top  :: HscEnv,  -- Top-level stuff that never changes
                             -- Includes all info about imported things
226

227
        env_us   :: {-# UNPACK #-} !(IORef UniqSupply),
Rik Steenkamp's avatar
Rik Steenkamp committed
228
                             -- Unique supply for local variables
229

230
231
        env_gbl  :: gbl,     -- Info about things defined at the top level
                             -- of the module being compiled
232

233
        env_lcl  :: lcl      -- Nested stuff; changes as we go into
234
    }
235

Ian Lynagh's avatar
Ian Lynagh committed
236
237
instance ContainsDynFlags (Env gbl lcl) where
    extractDynFlags env = hsc_dflags (env_top env)
238
239
    replaceDynFlags env dflags
        = env {env_top = replaceDynFlags (env_top env) dflags}
Ian Lynagh's avatar
Ian Lynagh committed
240

241
242
243
instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
    extractModule env = extractModule (env_gbl env)

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

{-
************************************************************************
*                                                                      *
                The interface environments
              Used when dealing with IfaceDecls
*                                                                      *
************************************************************************
-}

data IfGblEnv
  = IfGblEnv {
        -- The type environment for the module being compiled,
        -- in case the interface refers back to it via a reference that
        -- was originally a hi-boot file.
        -- We need the module name so we can test when it's appropriate
        -- to look in this env.
        if_rec_types :: Maybe (Module, IfG TypeEnv)
                -- Allows a read effect, so it can be in a mutable
                -- variable; c.f. handling the external package type env
                -- Nothing => interactive stuff, no loops possible
    }

data IfLclEnv
  = IfLclEnv {
        -- The module for the current IfaceDecl
        -- So if we see   f = \x -> x
        -- it means M.f = \x -> x, where M is the if_mod
        if_mod :: Module,

        -- The field is used only for error reporting
        -- if (say) there's a Lint error in it
        if_loc :: SDoc,
                -- Where the interface came from:
                --      .hi file, or GHCi state, or ext core
                -- plus which bit is currently being examined

        if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
        if_id_env  :: UniqFM Id         -- Nested id binding
    }

{-
************************************************************************
*                                                                      *
                Desugarer monad
*                                                                      *
************************************************************************

Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
a @UniqueSupply@ and some annotations, which
presumably include source-file location information:
-}

-- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
-- variables found in 'Data.Array.Parallel'.
--
data PArrBuiltin
        = PArrBuiltin
        { lengthPVar         :: Var     -- ^ lengthP
        , replicatePVar      :: Var     -- ^ replicateP
        , singletonPVar      :: Var     -- ^ singletonP
        , mapPVar            :: Var     -- ^ mapP
        , filterPVar         :: Var     -- ^ filterP
        , zipPVar            :: Var     -- ^ zipP
        , crossMapPVar       :: Var     -- ^ crossMapP
        , indexPVar          :: Var     -- ^ (!:)
        , emptyPVar          :: Var     -- ^ emptyP
        , appPVar            :: Var     -- ^ (+:+)
        , enumFromToPVar     :: Var     -- ^ enumFromToP
        , enumFromThenToPVar :: Var     -- ^ enumFromThenToP
        }

data DsGblEnv
        = DsGblEnv
        { ds_mod          :: Module             -- For SCC profiling
        , ds_fam_inst_env :: FamInstEnv         -- Like tcg_fam_inst_env
        , ds_unqual  :: PrintUnqualified
        , ds_msgs    :: IORef Messages          -- Warning messages
        , ds_if_env  :: (IfGblEnv, IfLclEnv)    -- Used for looking up global,
                                                -- possibly-imported things
        , ds_dph_env :: GlobalRdrEnv            -- exported entities of 'Data.Array.Parallel.Prim'
                                                -- iff '-fvectorise' flag was given as well as
                                                -- exported entities of 'Data.Array.Parallel' iff
                                                -- '-XParallelArrays' was given; otherwise, empty
        , ds_parr_bi :: PArrBuiltin             -- desugarar names for '-XParallelArrays'
        , ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
          -- ^ Bindings resulted from floating static forms
        }

instance ContainsModule DsGblEnv where
    extractModule = ds_mod

data DsLclEnv = DsLclEnv {
        dsl_meta    :: DsMetaEnv,        -- Template Haskell bindings
338
339
340
        dsl_loc     :: RealSrcSpan,      -- To put in pattern-matching error msgs
        dsl_dicts   :: Bag EvVar,        -- Constraints from GADT pattern-matching
        dsl_tm_cs   :: Bag SimpleEq
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
     }

-- Inside [| |] brackets, the desugarer looks
-- up variables in the DsMetaEnv
type DsMetaEnv = NameEnv DsMetaVal

data DsMetaVal
   = DsBound Id         -- Bound by a pattern inside the [| |].
                        -- Will be dynamically alpha renamed.
                        -- The Id has type THSyntax.Var

   | DsSplice (HsExpr Id) -- These bindings are introduced by
                          -- the PendingSplices on a HsBracketOut


{-
************************************************************************
*                                                                      *
                Global typechecker environment
*                                                                      *
************************************************************************
-}

364
365
366
367
368
369
370
371
-- | 'FrontendResult' describes the result of running the
-- frontend of a Haskell module.  Usually, you'll get
-- a 'FrontendTypecheck', since running the frontend involves
-- typechecking a program, but for an hs-boot merge you'll
-- just get a ModIface, since no actual typechecking occurred.
--
-- This data type really should be in HscTypes, but it needs
-- to have a TcGblEnv which is only defined here.
372
373
374
data FrontendResult
        = FrontendTypecheck TcGblEnv

Edward Z. Yang's avatar
Edward Z. Yang committed
375
-- | 'TcGblEnv' describes the top-level of the module at the
376
377
-- point at which the typechecker is finished work.
-- It is this structure that is handed on to the desugarer
378
-- For state that needs to be updated during the typechecking
Edward Z. Yang's avatar
Edward Z. Yang committed
379
-- phase and returned at end, use a 'TcRef' (= 'IORef').
380
381
data TcGblEnv
  = TcGblEnv {
382
383
        tcg_mod     :: Module,         -- ^ Module being compiled
        tcg_src     :: HscSource,
384
          -- ^ What kind of module (regular Haskell, hs-boot, hsig)
385
386
387
388
389
        tcg_sig_of  :: Maybe Module,
          -- ^ Are we being compiled as a signature of an implementation?
        tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
          -- ^ Environment used only during -sig-of for resolving top level
          -- bindings.  See Note [Signature parameters in TcGblEnv and DynFlags]
390

391
392
        tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
        tcg_default :: Maybe [Type],
393
          -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
394

395
396
        tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
        tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
397
                                        -- See Note [The interactive package] in HscTypes
398

399
        tcg_type_env :: TypeEnv,
400
          -- ^ Global type env for the module we are compiling now.  All
401
402
403
404
405
          -- TyCons and Classes (for this module) end up in here right away,
          -- along with their derived constructors, selectors.
          --
          -- (Ids defined in this module start in the local envt, though they
          --  move to the global envt during zonking)
406
407
408
          --
          -- NB: for what "things in this module" means, see
          -- Note [The interactive package] in HscTypes
409
410
411
412
413
414
415
416
417

        tcg_type_env_var :: TcRef TypeEnv,
                -- Used only to initialise the interface-file
                -- typechecker in initIfaceTcRn, so that it can see stuff
                -- bound in this module when dealing with hi-boot recursions
                -- Updated at intervals (e.g. after dealing with types and classes)

        tcg_inst_env     :: InstEnv,
          -- ^ Instance envt for all /home-package/ modules;
418
          -- Includes the dfuns in tcg_insts
419
        tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
420
        tcg_ann_env      :: AnnEnv,     -- ^ And for annotations
421
422
423
424
425
426
427

                -- Now a bunch of things about this module that are simply
                -- accumulated, but never consulted until the end.
                -- Nevertheless, it's convenient to accumulate them along
                -- with the rest of the info from this module.
        tcg_exports :: [AvailInfo],     -- ^ What is exported
        tcg_imports :: ImportAvails,
428
          -- ^ Information about what was imported from where, including
429
          -- things bound in this module. Also store Safe Haskell info
430
          -- here about transative trusted packaage requirements.
431

432
433
        tcg_dus       :: DefUses,   -- ^ What is defined in this module and what is used.
        tcg_used_gres :: TcRef [GlobalRdrElt],  -- ^ Records occurrences of imported entities
434
          -- See Note [Tracking unused binding and imports]
435

436
        tcg_keep :: TcRef NameSet,
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
          -- ^ Locally-defined top-level names to keep alive.
          --
          -- "Keep alive" means give them an Exported flag, so that the
          -- simplifier does not discard them as dead code, and so that they
          -- are exposed in the interface file (but not to export to the
          -- user).
          --
          -- Some things, like dict-fun Ids and default-method Ids are "born"
          -- with the Exported flag on, for exactly the above reason, but some
          -- we only discover as we go.  Specifically:
          --
          --   * The to/from functions for generic data types
          --
          --   * Top-level variables appearing free in the RHS of an orphan
          --     rule
          --
          --   * Top-level variables appearing free in a TH bracket

455
        tcg_th_used :: TcRef Bool,
456
457
          -- ^ @True@ <=> Template Haskell syntax used.
          --
458
          -- We need this so that we can generate a dependency on the
Gabor Greif's avatar
typos    
Gabor Greif committed
459
          -- Template Haskell package, because the desugarer is going
460
461
          -- to emit loads of references to TH symbols.  The reference
          -- is implicit rather than explicit, so we have to zap a
462
463
          -- mutable variable.

464
465
466
467
468
        tcg_th_splice_used :: TcRef Bool,
          -- ^ @True@ <=> A Template Haskell splice was used.
          --
          -- Splices disable recompilation avoidance (see #481)

469
        tcg_dfun_n  :: TcRef OccSet,
470
          -- ^ Allows us to choose unique DFun names.
471

472
        -- The next fields accumulate the payload of the module
Gabor Greif's avatar
Gabor Greif committed
473
        -- The binds, rules and foreign-decl fields are collected
474
        -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
475

476
        tcg_rn_exports :: Maybe [Located (IE Name)],
477
                -- Nothing <=> no explicit export list
478
479
                -- Is always Nothing if we don't want to retain renamed
                -- exports
480

481
        tcg_rn_imports :: [LImportDecl Name],
482
483
                -- Keep the renamed imports regardless.  They are not
                -- voluminous and are needed if you want to report unused imports
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
484

485
        tcg_rn_decls :: Maybe (HsGroup Name),
486
487
          -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
          -- decls.
488

489
        tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
GregWeber's avatar
GregWeber committed
490

491
492
493
494
495
496
#ifdef GHCI
        tcg_th_topdecls :: TcRef [LHsDecl RdrName],
        -- ^ Top-level declarations from addTopDecls

        tcg_th_topnames :: TcRef NameSet,
        -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
497
498
499

        tcg_th_modfinalizers :: TcRef [TH.Q ()],
        -- ^ Template Haskell module finalizers
500
501

        tcg_th_state :: TcRef (Map TypeRep Dynamic),
502
        tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))),
503
        -- ^ Template Haskell state
504
505
#endif /* GHCI */

506
        tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
507

508
509
510
        -- Things defined in this module, or (in GHCi)
        -- in the declarations for a single GHCi command.
        -- For the latter, see Note [The interactive package] in HscTypes
511
512
513
        tcg_tr_module :: Maybe Id,           -- Id for $trModule :: GHC.Types.Module
                                             -- for which every module has a top-level defn
                                             -- except in GHCi in which case we have Nothing
514
515
516
517
518
519
520
521
522
523
524
525
        tcg_binds     :: LHsBinds Id,        -- Value bindings in this module
        tcg_sigs      :: NameSet,            -- ...Top-level names that *lack* a signature
        tcg_imp_specs :: [LTcSpecPrag],      -- ...SPECIALISE prags for imported Ids
        tcg_warns     :: Warnings,           -- ...Warnings and deprecations
        tcg_anns      :: [Annotation],       -- ...Annotations
        tcg_tcs       :: [TyCon],            -- ...TyCons and Classes
        tcg_insts     :: [ClsInst],          -- ...Instances
        tcg_fam_insts :: [FamInst],          -- ...Family instances
        tcg_rules     :: [LRuleDecl Id],     -- ...Rules
        tcg_fords     :: [LForeignDecl Id],  -- ...Foreign import & exports
        tcg_vects     :: [LVectDecl Id],     -- ...Vectorisation declarations
        tcg_patsyns   :: [PatSyn],           -- ...Pattern synonyms
526

527
        tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
528
529
530
        tcg_hpc       :: AnyHpcUsage,        -- ^ @True@ if any part of the
                                             --  prog uses hpc instrumentation.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
531
532
533
        tcg_self_boot :: SelfBootInfo,       -- ^ Whether this module has a
                                             -- corresponding hi-boot file

534
        tcg_main      :: Maybe Name,         -- ^ The Name of the main
535
536
                                             -- function, if this module is
                                             -- the main module.
Adam Gundry's avatar
Adam Gundry committed
537

538
539
540
541
542
        tcg_safeInfer :: TcRef (Bool, WarningMessages),
        -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
        -- See Note [Safe Haskell Overlapping Instances Implementation],
        -- although this is used for more than just that failure case.

Facundo Domínguez's avatar
Facundo Domínguez committed
543
        tcg_tc_plugins :: [TcPluginSolver],
544
        -- ^ A list of user-defined plugins for the constraint solver.
Facundo Domínguez's avatar
Facundo Domínguez committed
545
546
547

        tcg_static_wc :: TcRef WantedConstraints
          -- ^ Wanted constraints of static forms.
548
    }
549

550
551
552
553
tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
tcVisibleOrphanMods tcg_env
    = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))

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
-- Note [Signature parameters in TcGblEnv and DynFlags]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- When compiling signature files, we need to know which implementation
-- we've actually linked against the signature.  There are three seemingly
-- redundant places where this information is stored: in DynFlags, there
-- is sigOf, and in TcGblEnv, there is tcg_sig_of and tcg_impl_rdr_env.
-- Here's the difference between each of them:
--
-- * DynFlags.sigOf is global per invocation of GHC.  If we are compiling
--   with --make, there may be multiple signature files being compiled; in
--   which case this parameter is a map from local module name to implementing
--   Module.
--
-- * HscEnv.tcg_sig_of is global per the compilation of a single file, so
--   it is simply the result of looking up tcg_mod in the DynFlags.sigOf
--   parameter.  It's setup in TcRnMonad.initTc.  This prevents us
--   from having to repeatedly do a lookup in DynFlags.sigOf.
--
-- * HscEnv.tcg_impl_rdr_env is a RdrEnv that lets us look up names
--   according to the sig-of module.  It's setup in TcRnDriver.tcRnSignature.
--   Here is an example showing why we need this map:
--
--  module A where
--      a = True
--
--  module ASig where
--      import B
--      a :: Bool
--
--  module B where
--      b = False
--
-- When we compile ASig --sig-of main:A, the default
-- global RdrEnv (tcg_rdr_env) has an entry for b, but not for a
-- (we never imported A).  So we have to look in a different environment
-- to actually get the original name.
--
-- By the way, why do we need to do the lookup; can't we just use A:a
-- as the name directly?  Well, if A is reexporting the entity from another
-- module, then the original name needs to be the real original name:
--
--  module C where
--      a = True
--
--  module A(a) where
--      import C

601
602
603
instance ContainsModule TcGblEnv where
    extractModule env = tcg_mod env

Adam Gundry's avatar
Adam Gundry committed
604
605
606
type RecFieldEnv = NameEnv [FieldLabel]
        -- Maps a constructor name *in this module*
        -- to the fields for that constructor.
607
608
609
610
611
        -- This is used when dealing with ".." notation in record
        -- construction and pattern matching.
        -- The FieldEnv deals *only* with constructors defined in *this*
        -- module.  For imported modules, we get the same info from the
        -- TypeEnv
612

Simon Peyton Jones's avatar
Simon Peyton Jones committed
613
614
615
616
617
618
619
620
621
data SelfBootInfo
  = NoSelfBoot    -- No corresponding hi-boot file
  | SelfBoot
       { sb_mds :: ModDetails   -- There was a hi-boot file,
       , sb_tcs :: NameSet      -- defining these TyCons,
       , sb_ids :: NameSet }    -- and these Ids
  -- We need this info to compute a safe approximation to
  -- recursive loops, to avoid infinite inlinings

622
623
624
625
{- Note [Tracking unused binding and imports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We gather two sorts of usage information

626
627
628
629
630
631
632
633
 * tcg_dus (defs/uses)
      Records *defined* Names (local, top-level)
          and *used*    Names (local or imported)

      Used (a) to report "defined but not used"
               (see RnNames.reportUnusedNames)
           (b) to generate version-tracking usage info in interface
               files (see MkIface.mkUsedNames)
634
   This usage info is mainly gathered by the renamer's
635
636
   gathering of free-variables

637
 * tcg_used_gres
638
      Used only to report unused import declarations
639
640
641
642
643
644
645

      Records each *occurrence* an *imported* (not locally-defined) entity.
      The occurrence is recorded by keeping a GlobalRdrElt for it.
      These is not the GRE that is in the GlobalRdrEnv; rather it
      is recorded *after* the filtering done by pickGREs.  So it reflect
      /how that occurrence is in scope/.   See Note [GRE filtering] in
      RdrName.
Adam Gundry's avatar
Adam Gundry committed
646

647

Austin Seipp's avatar
Austin Seipp committed
648
649
************************************************************************
*                                                                      *
650
                The local typechecker environment
Austin Seipp's avatar
Austin Seipp committed
651
652
*                                                                      *
************************************************************************
653

Edward Z. Yang's avatar
Edward Z. Yang committed
654
655
Note [The Global-Env/Local-Env story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
656
During type checking, we keep in the tcg_type_env
657
658
        * All types and classes
        * All Ids derived from types and classes (constructors, selectors)
659
660
661

At the end of type checking, we zonk the local bindings,
and as we do so we add to the tcg_type_env
662
        * Locally defined top-level Ids
663
664

Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
665
666
667
        a) fed back (via the knot) to typechecking the
           unfoldings of interface signatures
        b) used in the ModDetails of this module
Austin Seipp's avatar
Austin Seipp committed
668
-}
669

670
671
data TcLclEnv           -- Changes as we move inside an expression
                        -- Discarded after typecheck/rename; not passed on to desugarer
672
  = TcLclEnv {
673
        tcl_loc        :: RealSrcSpan,     -- Source span
674
        tcl_ctxt       :: [ErrCtxt],       -- Error context, innermost on top
675
        tcl_tclvl      :: TcLevel,         -- Birthplace for new unification variables
676

677
        tcl_th_ctxt    :: ThStage,         -- Template Haskell context
678
679
680
        tcl_th_bndrs   :: ThBindEnv,       -- Binding level of in-scope Names
                                           -- defined in this module (not imported)

681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
        tcl_arrow_ctxt :: ArrowCtxt,       -- Arrow-notation context

        tcl_rdr :: LocalRdrEnv,         -- Local name envt
                -- Maintained during renaming, of course, but also during
                -- type checking, solely so that when renaming a Template-Haskell
                -- splice we have the right environment for the renamer.
                --
                --   Does *not* include global name envt; may shadow it
                --   Includes both ordinary variables and type variables;
                --   they are kept distinct because tyvar have a different
                --   occurrence contructor (Name.TvOcc)
                -- We still need the unsullied global name env so that
                --   we can look up record field names

        tcl_env  :: TcTypeEnv,    -- The local type environment:
                                  -- Ids and TyVars defined in this module
697

698
        tcl_bndrs :: TcIdBinderStack,   -- Used for reporting relevant bindings
699
700
701

        tcl_tidy :: TidyEnv,      -- Used for tidying types; contains all
                                  -- in-scope type variables (but not term variables)
702
703
704
705
706

        tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
                        -- Namely, the in-scope TyVars bound in tcl_env,
                        -- plus the tyvars mentioned in the types of Ids bound
                        -- in tcl_lenv.
707
                        -- Why mutable? see notes with tcGetGlobalTyCoVars
708

709
710
        tcl_lie  :: TcRef WantedConstraints,    -- Place to accumulate type constraints
        tcl_errs :: TcRef Messages              -- Place to accumulate errors
711
712
    }

713
type TcTypeEnv = NameEnv TcTyThing
714

715
716
717
718
719
720
721
722
723
type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
   -- Domain = all Ids bound in this module (ie not imported)
   -- The TopLevelFlag tells if the binding is syntactically top level.
   -- We need to know this, because the cross-stage persistence story allows
   -- cross-stage at arbitrary types if the Id is bound at top level.
   --
   -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
   -- bound at top level!  See Note [Template Haskell levels] in TcSplice

724
725
{- Note [Given Insts]
   ~~~~~~~~~~~~~~~~~~
726
Because of GADTs, we have to pass inwards the Insts provided by type signatures
727
and existential contexts. Consider
728
729
730
        data T a where { T1 :: b -> b -> T [b] }
        f :: Eq a => T a -> Bool
        f (T1 x y) = [x]==[y]
731
732

The constructor T1 binds an existential variable 'b', and we need Eq [b].
733
Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
734
735
736
pass it inwards.

-}
737

738
739
740
741
742
743
744
745
-- | Type alias for 'IORef'; the convention is we'll use this for mutable
-- bits of data in 'TcGblEnv' which are updated during typechecking and
-- returned at the end.
type TcRef a     = IORef a
-- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
type TcId        = Id
type TcIdSet     = IdSet

746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
---------------------------
-- The TcIdBinderStack
---------------------------

type TcIdBinderStack = [TcIdBinder]
   -- This is a stack of locally-bound ids, innermost on top
   -- Used ony in error reporting (relevantBindings in TcError)

data TcIdBinder
  = TcIdBndr
       TcId
       TopLevelFlag    -- Tells whether the bindind is syntactically top-level
                       -- (The monomorphic Ids for a recursive group count
                       --  as not-top-level for this purpose.)

instance Outputable TcIdBinder where
   ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl)

764
---------------------------
765
-- Template Haskell stages and levels
766
767
---------------------------

768
769
data SpliceType = Typed | Untyped

770
data ThStage    -- See Note [Template Haskell state diagram] in TcSplice
771
772
773
774
  = Splice SpliceType -- Inside a top-level splice
                      -- This code will be run *at compile time*;
                      --   the result replaces the splice
                      -- Binding level = 0
775
776
777

  | Comp        -- Ordinary Haskell code
                -- Binding level = 1
778

779
  | Brack                       -- Inside brackets
780
781
782
783
784
785
786
787
788
      ThStage                   --   Enclosing stage
      PendingStuff

data PendingStuff
  = RnPendingUntyped              -- Renaming the inside of an *untyped* bracket
      (TcRef [PendingRnSplice])   -- Pending splices in here

  | RnPendingTyped                -- Renaming the inside of a *typed* bracket

789
  | TcPending                     -- Typechecking the inside of a typed bracket
790
791
      (TcRef [PendingTcSplice])   --   Accumulate pending splices here
      (TcRef WantedConstraints)   --     and type constraints here
792
793
794

topStage, topAnnStage, topSpliceStage :: ThStage
topStage       = Comp
795
796
topAnnStage    = Splice Untyped
topSpliceStage = Splice Untyped
797
798

instance Outputable ThStage where
799
800
801
   ppr (Splice _)  = text "Splice"
   ppr Comp        = text "Comp"
   ppr (Brack s _) = text "Brack" <> parens (ppr s)
802

803
type ThLevel = Int
804
805
806
807
808
    -- NB: see Note [Template Haskell levels] in TcSplice
    -- Incremented when going inside a bracket,
    -- decremented when going inside a splice
    -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
    --     original "Template meta-programming for Haskell" paper
809

810
impLevel, outerLevel :: ThLevel
811
812
impLevel = 0    -- Imported things; they can be used inside a top level splice
outerLevel = 1  -- Things defined outside brackets
813

814
thLevel :: ThStage -> ThLevel
815
816
817
thLevel (Splice _)  = 0
thLevel Comp        = 1
thLevel (Brack s _) = thLevel s + 1
818

ross's avatar
ross committed
819
820
821
822
---------------------------
-- Arrow-notation context
---------------------------

823
824
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ross's avatar
ross committed
825
826
827
828
In arrow notation, a variable bound by a proc (or enclosed let/kappa)
is not in scope to the left of an arrow tail (-<) or the head of (|..|).
For example

829
        proc x -> (e1 -< e2)
ross's avatar
ross committed
830
831
832
833

Here, x is not in scope in e1, but it is in scope in e2.  This can get
a bit complicated:

834
835
        let x = 3 in
        proc y -> (proc z -> e1) -< e2
ross's avatar
ross committed
836

837
Here, x and z are in scope in e1, but y is not.
838
839

We implement this by
ross's avatar
ross committed
840
841
842
recording the environment when passing a proc (using newArrowScope),
and returning to that (using escapeArrowScope) on the left of -< and the
head of (|..|).
843

844
845
846
847
848
849
850
851
852
853
All this can be dealt with by the *renamer*. But the type checker needs
to be involved too.  Example (arrowfail001)
  class Foo a where foo :: a -> ()
  data Bar = forall a. Foo a => Bar a
  get :: Bar -> ()
  get = proc x -> case x of Bar a -> foo -< a
Here the call of 'foo' gives rise to a (Foo a) constraint that should not
be captured by the pattern match on 'Bar'.  Rather it should join the
constraints from further out.  So we must capture the constraint bag
from further out in the ArrowCtxt that we push inwards.
ross's avatar
ross committed
854
855
-}

856
data ArrowCtxt   -- Note [Escaping the arrow scope]
ross's avatar
ross committed
857
  = NoArrowCtxt
858
859
  | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)

860

861
862
863
864
---------------------------
-- TcTyThing
---------------------------

Edward Z. Yang's avatar
Edward Z. Yang committed
865
866
867
-- | A typecheckable thing available in a local context.  Could be
-- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
-- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
868
data TcTyThing
869
  = AGlobal TyThing             -- Used only in the return type of a lookup
870

871
872
  | ATcId   {           -- Ids defined in this module; may not be fully zonked
        tct_id     :: TcId,
873
        tct_closed :: TopLevelFlag }   -- See Note [Bindings with closed types]
874

875
876
877
878
  | ATyVar  Name TcTyVar        -- The type variable to which the lexically scoped type
                                -- variable is bound. We only need the Name
                                -- for error-message purposes; it is the corresponding
                                -- Name in the domain of the envt
879

880
  | ATcTyCon TyCon   -- Used temporarily, during kind checking, for the
881
                     -- tycons and clases in this recursive group
882
883
                     -- The TyCon is always a TcTyCon.  Its kind
                     -- can be a mono-kind or a poly-kind; in TcTyClsDcls see
dreixel's avatar
dreixel committed
884
885
                     -- Note [Type checking recursive type and class declarations]

886
  | APromotionErr PromotionErr
887

888
data PromotionErr
889
890
891
892
893
  = TyConPE          -- TyCon used in a kind before we are ready
                     --     data T :: T -> * where ...
  | ClassPE          -- Ditto Class

  | FamDataConPE     -- Data constructor for a data family
894
                     -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
895
896
  | PatSynPE         -- Pattern synonyms
                     -- See Note [Don't promote pattern synonyms] in TcEnv
dreixel's avatar
dreixel committed
897

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
898
  | RecDataConPE     -- Data constructor in a recursive loop
899
                     -- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
900
  | NoDataKinds      -- -XDataKinds not enabled
901
902
  | NoTypeInTypeTC   -- -XTypeInType not enabled (for a tycon)
  | NoTypeInTypeDC   -- -XTypeInType not enabled (for a datacon)
903

904
instance Outputable TcTyThing where     -- Debugging only
905
   ppr (AGlobal g)      = pprTyThing g
906
907
   ppr elt@(ATcId {})   = text "Identifier" <>
                          brackets (ppr (tct_id elt) <> dcolon
908
                                 <> ppr (varType (tct_id elt)) <> comma
909
                                 <+> ppr (tct_closed elt))
Simon Peyton Jones's avatar
Simon Peyton Jones committed
910
   ppr (ATyVar n tv)    = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
911
   ppr (ATcTyCon tc)    = text "ATcTyCon" <+> ppr tc
912
913
914
   ppr (APromotionErr err) = text "APromotionErr" <+> ppr err

instance Outputable PromotionErr where
915
916
  ppr ClassPE        = text "ClassPE"
  ppr TyConPE        = text "TyConPE"
917
  ppr PatSynPE       = text "PatSynPE"
918
919
920
921
922
  ppr FamDataConPE   = text "FamDataConPE"
  ppr RecDataConPE   = text "RecDataConPE"
  ppr NoDataKinds    = text "NoDataKinds"
  ppr NoTypeInTypeTC = text "NoTypeInTypeTC"
  ppr NoTypeInTypeDC = text "NoTypeInTypeDC"
923
924

pprTcTyThingCategory :: TcTyThing -> SDoc
925
926
927
pprTcTyThingCategory (AGlobal thing)    = pprTyThingCategory thing
pprTcTyThingCategory (ATyVar {})        = ptext (sLit "Type variable")
pprTcTyThingCategory (ATcId {})         = ptext (sLit "Local identifier")
928
pprTcTyThingCategory (ATcTyCon {})     = ptext (sLit "Local tycon")
929
930
931
pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe

pprPECategory :: PromotionErr -> SDoc
932
933
pprPECategory ClassPE        = ptext (sLit "Class")
pprPECategory TyConPE        = ptext (sLit "Type constructor")
934
pprPECategory PatSynPE       = ptext (sLit "Pattern synonym")
935
936
937
938
939
pprPECategory FamDataConPE   = ptext (sLit "Data constructor")
pprPECategory RecDataConPE   = ptext (sLit "Data constructor")
pprPECategory NoDataKinds    = ptext (sLit "Data constructor")
pprPECategory NoTypeInTypeTC = ptext (sLit "Type constructor")
pprPECategory NoTypeInTypeDC = ptext (sLit "Data constructor")
940

941
{- Note [Bindings with closed types]
942
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
943
944
945
946
947
Consider

  f x = let g ys = map not ys
        in ...

948
Can we generalise 'g' under the OutsideIn algorithm?  Yes,
dreixel's avatar
dreixel committed
949
because all g's free variables are top-level; that is they themselves
950
951
952
953
954
have no free type variables, and it is the type variables in the
environment that makes things tricky for OutsideIn generalisation.

Definition:
   A variable is "closed", and has tct_closed set to TopLevel,
955
956
iff
   a) all its free variables are imported, or are let-bound with closed types
957
958
   b) generalisation is not restricted by the monomorphism restriction

959
960
Invariant: a closed variable has no free type variables in its type.

961
962
Under OutsideIn we are free to generalise a closed let-binding.
This is an extension compared to the JFP paper on OutsideIn, which
963
used "top-level" as a proxy for "closed".  (It's not a good proxy
964
965
966
967
anyway -- the MR can make a top-level binding with a free type
variable.)

Note that:
968
  * A top-level binding may not be closed, if it suffers from the MR
969
970
971

  * A nested binding may be closed (eg 'g' in the example we started with)
    Indeed, that's the point; whether a function is defined at top level
972
    or nested is orthogonal to the question of whether or not it is closed
973
974
975
976
977

  * A binding may be non-closed because it mentions a lexically scoped
    *type variable*  Eg
        f :: forall a. blah
        f x = let g y = ...(y::a)...
978

Austin Seipp's avatar
Austin Seipp committed
979
-}
980

981
type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
982
983
984
        -- Monadic so that we have a chance
        -- to deal with bound type variables just before error
        -- message construction
985

986
987
        -- Bool:  True <=> this is a landmark context; do not
        --                 discard it when trimming for display
988

Austin Seipp's avatar
Austin Seipp committed
989
990
991
{-
************************************************************************
*                                                                      *
992
        Operations over ImportAvails
Austin Seipp's avatar
Austin Seipp committed
993
994
995
*                                                                      *
************************************************************************
-}
996

997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
-- | 'ImportAvails' summarises what was imported from where, irrespective of
-- whether the imported things are actually used or not.  It is used:
--
--  * when processing the export list,
--
--  * when constructing usage info for the interface file,
--
--  * to identify the list of directly imported modules for initialisation
--    purposes and for optimised overlap checking of family instances,
--
--  * when figuring out what things are really unused
--
1009
data ImportAvails
1010
   = ImportAvails {
1011
        imp_mods :: ImportedMods,
1012
          --      = ModuleEnv [ImportedModsVal],
1013
          -- ^ Domain is all directly-imported modules
1014
          --
1015
1016
          -- See the documentaion on ImportedModsVal in HscTypes for the
          -- meaning of the fields.
1017
          --
1018
1019
1020
1021
          -- We need a full ModuleEnv rather than a ModuleNameEnv here,
          -- because we might be importing modules of the same name from
          -- different packages. (currently not the case, but might be in the
          -- future).
1022

1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
        imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
          -- ^ Home-package modules needed by the module being compiled
          --
          -- It doesn't matter whether any of these dependencies
          -- are actually /used/ when compiling the module; they
          -- are listed if they are below it at all.  For
          -- example, suppose M imports A which imports X.  Then
          -- compiling M might not need to consult X.hi, but X
          -- is still listed in M's dependencies.

1033
        imp_dep_pkgs :: [UnitId],
1034
1035
1036
          -- ^ Packages needed by the module being compiled, whether directly,
          -- or via other modules in this package, or via modules imported
          -- from other packages.
1037

1038
        imp_trust_pkgs :: [UnitId],
1039
1040
1041
1042
          -- ^ This is strictly a subset of imp_dep_pkgs and records the
          -- packages the current module needs to trust for Safe Haskell
          -- compilation to succeed. A package is required to be trusted if
          -- we are dependent on a trustworthy module in that package.
1043
          -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1044
1045
1046
          -- where True for the bool indicates the package is required to be
          -- trusted is the more logical  design, doing so complicates a lot
          -- of code not concerned with Safe Haskell.
1047
          -- See Note [RnNames . Tracking Trust Transitively]
1048

1049
1050
1051
1052