TcRnTypes.hs 124 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(..),
43 44
        IdBindingInfo(..),
        IsGroupClosed(..),
Simon Peyton Jones's avatar
Simon Peyton Jones committed
45
        SelfBootInfo(..),
46
        pprTcTyThingCategory, pprPECategory,
47

48 49 50 51
        -- Desugaring types
        DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
        DsMetaEnv, DsMetaVal(..),

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

57
        -- Arrows
58
        ArrowCtxt(..),
ross's avatar
ross committed
59

60
        -- TcSigInfo
61 62 63
        TcSigInfo(..), TcIdSigInfo(..),
        TcIdSigInst(..), TcPatSynInfo(..),
        isPartialSig,
64

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

83
        WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
84
        toDerivedWC,
85 86
        andWC, unionsWC, mkSimpleWC, mkImplicWC,
        addInsols, addSimples, addImplics,
87
        tyCoVarsOfWC, dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
88
        tyCoVarsOfWCList,
89
        isDroppableDerivedLoc, insolubleImplic,
90
        arisesFromGivens,
91

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

105
        SkolemInfo(..), pprSigSkolInfo, pprSkolInfo,
106

107 108
        CtEvidence(..), TcEvDest(..),
        mkGivenLoc, mkKindLoc, toKindLoc,
109
        isWanted, isGiven, isDerived,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
110
        ctEvRole,
111

Adam Gundry's avatar
Adam Gundry committed
112 113 114
        -- Constraint solver plugins
        TcPlugin(..), TcPluginResult(..), TcPluginSolver,
        TcPluginM, runTcPluginM, unsafeTcPluginTcM,
115
        getEvBindsTcPluginM_maybe,
Adam Gundry's avatar
Adam Gundry committed
116

eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
117
        CtFlavour(..), ctEvFlavour,
118
        CtFlavourRole, ctEvFlavourRole, ctFlavourRole,
119 120
        eqCanRewrite, eqCanRewriteFR,  eqCanDischarge,
        funEqCanDischarge, funEqCanDischargeFR,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
121

122
        -- Pretty printing
Austin Seipp's avatar
Austin Seipp committed
123
        pprEvVarTheta,
124
        pprEvVars, pprEvVarWithType,
125

126
        -- Misc other types
127 128
        TcId, TcIdSet,
        Hole(..), holeOcc
129

130 131 132 133
  ) where

#include "HsVersions.h"

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

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

#ifdef GHCI
182 183 184
import Data.Map      ( Map )
import Data.Dynamic  ( Dynamic )
import Data.Typeable ( TypeRep )
185
import GHCi.Message
186
import GHCi.RemoteTypes
187

188 189
import qualified Language.Haskell.TH as TH
#endif
190

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

199
The monad itself has to be defined here, because it is mentioned by ErrCtxt
Austin Seipp's avatar
Austin Seipp committed
200
-}
201

cactus's avatar
cactus committed
202
type TcRnIf a b = IOEnv (Env a b)
203 204 205 206 207 208 209 210 211 212 213 214
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
215 216 217 218 219 220

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

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

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

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

233 234
        env_gbl  :: gbl,     -- Info about things defined at the top level
                             -- of the module being compiled
235

236
        env_lcl  :: lcl      -- Nested stuff; changes as we go into
237
    }
238

Ian Lynagh's avatar
Ian Lynagh committed
239 240 241
instance ContainsDynFlags (Env gbl lcl) where
    extractDynFlags env = hsc_dflags (env_top env)

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

245 246 247 248 249 250 251 252 253 254 255 256

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

data IfGblEnv
  = IfGblEnv {
257 258 259
        -- Some information about where this environment came from;
        -- useful for debugging.
        if_doc :: SDoc,
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
        -- 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

niteria's avatar
niteria committed
285 286
        if_tv_env  :: FastStringEnv TyVar,     -- Nested tyvar bindings
        if_id_env  :: FastStringEnv Id         -- Nested id binding
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
    }

{-
************************************************************************
*                                                                      *
                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'
        }

instance ContainsModule DsGblEnv where
    extractModule = ds_mod

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

-- 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
*                                                                      *
************************************************************************
-}

367 368 369 370 371 372 373 374
-- | '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.
375 376 377
data FrontendResult
        = FrontendTypecheck TcGblEnv

Edward Z. Yang's avatar
Edward Z. Yang committed
378
-- | 'TcGblEnv' describes the top-level of the module at the
379 380
-- point at which the typechecker is finished work.
-- It is this structure that is handed on to the desugarer
381
-- For state that needs to be updated during the typechecking
Edward Z. Yang's avatar
Edward Z. Yang committed
382
-- phase and returned at end, use a 'TcRef' (= 'IORef').
383 384
data TcGblEnv
  = TcGblEnv {
385 386
        tcg_mod     :: Module,         -- ^ Module being compiled
        tcg_src     :: HscSource,
387
          -- ^ What kind of module (regular Haskell, hs-boot, hsig)
388 389 390 391 392
        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]
393

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

398 399
        tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
        tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
400
                                        -- See Note [The interactive package] in HscTypes
401

402
        tcg_type_env :: TypeEnv,
403
          -- ^ Global type env for the module we are compiling now.  All
404 405 406 407 408
          -- 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)
409 410 411
          --
          -- NB: for what "things in this module" means, see
          -- Note [The interactive package] in HscTypes
412 413 414 415 416 417 418 419 420

        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;
421
          -- Includes the dfuns in tcg_insts
422
        tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
423
        tcg_ann_env      :: AnnEnv,     -- ^ And for annotations
424 425 426 427 428 429 430

                -- 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,
431
          -- ^ Information about what was imported from where, including
432
          -- things bound in this module. Also store Safe Haskell info
433
          -- here about transative trusted packaage requirements.
434

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

439
        tcg_keep :: TcRef NameSet,
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
          -- ^ 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

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

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

472 473 474 475
        tcg_th_top_level_locs :: TcRef (Set RealSrcSpan),
          -- ^ Locations of the top-level splices; used for providing details on
          -- scope in error messages for out-of-scope variables

476
        tcg_dfun_n  :: TcRef OccSet,
477
          -- ^ Allows us to choose unique DFun names.
478

479
        -- The next fields accumulate the payload of the module
Gabor Greif's avatar
Gabor Greif committed
480
        -- The binds, rules and foreign-decl fields are collected
481
        -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
482

483
        tcg_rn_exports :: Maybe [Located (IE Name)],
484
                -- Nothing <=> no explicit export list
485 486
                -- Is always Nothing if we don't want to retain renamed
                -- exports
487

488
        tcg_rn_imports :: [LImportDecl Name],
489 490
                -- 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
491

492
        tcg_rn_decls :: Maybe (HsGroup Name),
493 494
          -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
          -- decls.
495

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

498 499 500 501 502 503
#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
504 505 506

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

        tcg_th_state :: TcRef (Map TypeRep Dynamic),
509
        tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))),
510
        -- ^ Template Haskell state
511 512
#endif /* GHCI */

513
        tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
514

515 516 517
        -- 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
518 519 520
        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
521 522 523 524 525 526 527 528 529 530 531 532
        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
533

534
        tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
535 536 537
        tcg_hpc       :: AnyHpcUsage,        -- ^ @True@ if any part of the
                                             --  prog uses hpc instrumentation.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
538 539 540
        tcg_self_boot :: SelfBootInfo,       -- ^ Whether this module has a
                                             -- corresponding hi-boot file

541
        tcg_main      :: Maybe Name,         -- ^ The Name of the main
542 543
                                             -- function, if this module is
                                             -- the main module.
Adam Gundry's avatar
Adam Gundry committed
544

545 546 547 548 549
        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
550
        tcg_tc_plugins :: [TcPluginSolver],
551
        -- ^ A list of user-defined plugins for the constraint solver.
Facundo Domínguez's avatar
Facundo Domínguez committed
552 553 554

        tcg_static_wc :: TcRef WantedConstraints
          -- ^ Wanted constraints of static forms.
555
    }
556

557 558 559 560
tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
tcVisibleOrphanMods tcg_env
    = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))

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
-- 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

608 609 610
instance ContainsModule TcGblEnv where
    extractModule env = tcg_mod env

Adam Gundry's avatar
Adam Gundry committed
611 612 613
type RecFieldEnv = NameEnv [FieldLabel]
        -- Maps a constructor name *in this module*
        -- to the fields for that constructor.
614 615 616 617 618
        -- 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
619

Simon Peyton Jones's avatar
Simon Peyton Jones committed
620 621 622 623 624 625 626 627 628
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

629 630 631 632
{- Note [Tracking unused binding and imports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We gather two sorts of usage information

633 634 635 636 637 638 639 640
 * 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)
641
   This usage info is mainly gathered by the renamer's
642 643
   gathering of free-variables

644
 * tcg_used_gres
645
      Used only to report unused import declarations
646 647 648 649 650 651 652

      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
653

654

Austin Seipp's avatar
Austin Seipp committed
655 656
************************************************************************
*                                                                      *
657
                The local typechecker environment
Austin Seipp's avatar
Austin Seipp committed
658 659
*                                                                      *
************************************************************************
660

Edward Z. Yang's avatar
Edward Z. Yang committed
661 662
Note [The Global-Env/Local-Env story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
663
During type checking, we keep in the tcg_type_env
664 665
        * All types and classes
        * All Ids derived from types and classes (constructors, selectors)
666 667 668

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

Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
672 673 674
        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
675
-}
676

677 678
data TcLclEnv           -- Changes as we move inside an expression
                        -- Discarded after typecheck/rename; not passed on to desugarer
679
  = TcLclEnv {
680
        tcl_loc        :: RealSrcSpan,     -- Source span
681
        tcl_ctxt       :: [ErrCtxt],       -- Error context, innermost on top
682
        tcl_tclvl      :: TcLevel,         -- Birthplace for new unification variables
683

684
        tcl_th_ctxt    :: ThStage,         -- Template Haskell context
685 686 687
        tcl_th_bndrs   :: ThBindEnv,       -- Binding level of in-scope Names
                                           -- defined in this module (not imported)

688 689 690 691 692 693 694 695 696 697
        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
Gabor Greif's avatar
Gabor Greif committed
698
                --   occurrence constructor (Name.TvOcc)
699 700 701 702 703
                -- 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
704

705
        tcl_bndrs :: TcIdBinderStack,   -- Used for reporting relevant bindings
706 707 708

        tcl_tidy :: TidyEnv,      -- Used for tidying types; contains all
                                  -- in-scope type variables (but not term variables)
709 710 711 712 713

        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.
714
                        -- Why mutable? see notes with tcGetGlobalTyCoVars
715

716 717
        tcl_lie  :: TcRef WantedConstraints,    -- Place to accumulate type constraints
        tcl_errs :: TcRef Messages              -- Place to accumulate errors
718 719
    }

720
type TcTypeEnv = NameEnv TcTyThing
721

722 723 724 725 726 727 728 729 730
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

731 732
{- Note [Given Insts]
   ~~~~~~~~~~~~~~~~~~
733
Because of GADTs, we have to pass inwards the Insts provided by type signatures
734
and existential contexts. Consider
735 736 737
        data T a where { T1 :: b -> b -> T [b] }
        f :: Eq a => T a -> Bool
        f (T1 x y) = [x]==[y]
738 739

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

-}
744

745 746 747 748 749 750 751 752
-- | 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

753 754 755 756 757 758 759
---------------------------
-- The TcIdBinderStack
---------------------------

type TcIdBinderStack = [TcIdBinder]
   -- This is a stack of locally-bound ids, innermost on top
   -- Used ony in error reporting (relevantBindings in TcError)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
760 761
   -- We can't use the tcl_env type environment, because it doesn't
   --   keep track of the nesting order
762 763 764 765 766 767 768

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.)
769 770 771 772 773
  | TcIdBndr_ExpType  -- Variant that allows the type to be specified as
                      -- an ExpType
       Name
       ExpType
       TopLevelFlag
774 775

instance Outputable TcIdBinder where
776 777
   ppr (TcIdBndr id top_lvl)           = ppr id <> brackets (ppr top_lvl)
   ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl)
778

779
---------------------------
780
-- Template Haskell stages and levels
781 782
---------------------------

783 784
data SpliceType = Typed | Untyped

785
data ThStage    -- See Note [Template Haskell state diagram] in TcSplice
786 787 788 789
  = Splice SpliceType -- Inside a top-level splice
                      -- This code will be run *at compile time*;
                      --   the result replaces the splice
                      -- Binding level = 0
790 791 792

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

794
  | Brack                       -- Inside brackets
795 796 797 798 799 800 801 802 803
      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

804
  | TcPending                     -- Typechecking the inside of a typed bracket
805 806
      (TcRef [PendingTcSplice])   --   Accumulate pending splices here
      (TcRef WantedConstraints)   --     and type constraints here
807 808 809

topStage, topAnnStage, topSpliceStage :: ThStage
topStage       = Comp
810 811
topAnnStage    = Splice Untyped
topSpliceStage = Splice Untyped
812 813

instance Outputable ThStage where
814 815 816
   ppr (Splice _)  = text "Splice"
   ppr Comp        = text "Comp"
   ppr (Brack s _) = text "Brack" <> parens (ppr s)
817

818
type ThLevel = Int
819 820 821 822 823
    -- 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
824

825
impLevel, outerLevel :: ThLevel
826 827
impLevel = 0    -- Imported things; they can be used inside a top level splice
outerLevel = 1  -- Things defined outside brackets
828

829
thLevel :: ThStage -> ThLevel
830 831 832
thLevel (Splice _)  = 0
thLevel Comp        = 1
thLevel (Brack s _) = thLevel s + 1
833

ross's avatar
ross committed
834 835 836 837
---------------------------
-- Arrow-notation context
---------------------------

838 839
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ross's avatar
ross committed
840 841 842 843
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

844
        proc x -> (e1 -< e2)
ross's avatar
ross committed
845 846 847 848

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

849 850
        let x = 3 in
        proc y -> (proc z -> e1) -< e2
ross's avatar
ross committed
851

852
Here, x and z are in scope in e1, but y is not.
853 854

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

859 860 861 862 863 864 865 866 867 868
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
869 870
-}

871
data ArrowCtxt   -- Note [Escaping the arrow scope]
ross's avatar
ross committed
872
  = NoArrowCtxt
873 874
  | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)

875

876 877 878 879
---------------------------
-- TcTyThing
---------------------------

Edward Z. Yang's avatar
Edward Z. Yang committed
880 881 882
-- | 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'.
883
data TcTyThing
884
  = AGlobal TyThing             -- Used only in the return type of a lookup
885

886 887
  | ATcId   {           -- Ids defined in this module; may not be fully zonked
        tct_id     :: TcId,
888
        tct_info :: IdBindingInfo }   -- See Note [Bindings with closed types]
889

890 891 892 893
  | 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
894

895
  | ATcTyCon TyCon   -- Used temporarily, during kind checking, for the
896
                     -- tycons and clases in this recursive group
897 898
                     -- 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
899 900
                     -- Note [Type checking recursive type and class declarations]

901
  | APromotionErr PromotionErr
902

903
data PromotionErr
904 905 906 907 908
  = TyConPE          -- TyCon used in a kind before we are ready
                     --     data T :: T -> * where ...
  | ClassPE          -- Ditto Class

  | FamDataConPE     -- Data constructor for a data family
909
                     -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver