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 TysWiredIn ( callStackTyCon, ipClass )
134
import Type
135
import Class    ( Class )
136
import TyCon    ( TyCon )
137
import Coercion ( Coercion, mkHoleCo )
Gergő Érdi's avatar
Gergő Érdi committed
138
import ConLike  ( ConLike(..) )
139
import DataCon  ( DataCon, dataConUserType, dataConOrigArgTys )
140
import PatSyn   ( PatSyn, patSynType )
141
import Id       ( idName )
Adam Gundry's avatar
Adam Gundry committed
142
import FieldLabel ( FieldLabel )
143
import TcType
144
import Annotations
145 146
import InstEnv
import FamInstEnv
147
import PmExpr
148
import IOEnv
149 150
import RdrName
import Name
151
import NameEnv
152
import NameSet
153
import Avail
154
import Var
155
import FV
156
import VarEnv
157
import Module
158 159 160
import SrcLoc
import VarSet
import ErrUtils
161
import UniqFM
162 163
import UniqSupply
import BasicTypes
164
import Bag
Ian Lynagh's avatar
Ian Lynagh committed
165
import DynFlags
166
import Outputable
167
import ListSetOps
168
import FastString
169
import GHC.Fingerprint
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
170
import qualified GHC.LanguageExtensions as LangExt
171

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

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

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

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

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

Gergő Érdi's avatar
Gergő Érdi committed
198
type TcRnIf a b = IOEnv (Env a b)
199 200 201 202 203 204 205 206 207 208 209 210
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
211 212 213 214 215 216

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

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

218 219 220 221
-- 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
222
  = Env {
223 224
        env_top  :: HscEnv,  -- Top-level stuff that never changes
                             -- Includes all info about imported things
225

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

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

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

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

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

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336

{-
************************************************************************
*                                                                      *
                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
337 338 339
        dsl_loc     :: RealSrcSpan,      -- To put in pattern-matching error msgs
        dsl_dicts   :: Bag EvVar,        -- Constraints from GADT pattern-matching
        dsl_tm_cs   :: Bag SimpleEq
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
     }

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

363 364 365 366 367 368 369 370
-- | '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.
371 372 373
data FrontendResult
        = FrontendTypecheck TcGblEnv

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

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

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

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

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

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

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

435
        tcg_keep :: TcRef NameSet,
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
          -- ^ 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

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

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

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

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

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

480
        tcg_rn_imports :: [LImportDecl Name],
481 482
                -- 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
483

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

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

490 491 492 493 494 495
#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
496 497 498

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

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

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

507 508 509
        -- 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
510 511 512
        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
513 514 515 516 517 518 519 520 521 522 523 524
        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
525

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

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

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

537 538 539 540 541
        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
542
        tcg_tc_plugins :: [TcPluginSolver],
543
        -- ^ A list of user-defined plugins for the constraint solver.
Facundo Domínguez's avatar
Facundo Domínguez committed
544 545 546

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

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

553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
-- 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

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

Adam Gundry's avatar
Adam Gundry committed
603 604 605
type RecFieldEnv = NameEnv [FieldLabel]
        -- Maps a constructor name *in this module*
        -- to the fields for that constructor.
606 607 608 609 610
        -- 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
611

Simon Peyton Jones's avatar
Simon Peyton Jones committed
612 613 614 615 616 617 618 619 620
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

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

625 626 627 628 629 630 631 632
 * 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)
633
   This usage info is mainly gathered by the renamer's
634 635
   gathering of free-variables

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

      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
645

646

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

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

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

Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
664 665 666
        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
667
-}
668

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

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

680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
        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
696

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

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

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

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

712
type TcTypeEnv = NameEnv TcTyThing
713

714 715 716 717 718 719 720 721 722
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

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

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

-}
736

737 738 739 740 741 742 743 744
-- | 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

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
---------------------------
-- 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)

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

767 768
data SpliceType = Typed | Untyped

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

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

778
  | Brack                       -- Inside brackets
779 780 781 782 783 784 785 786 787
      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

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

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

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

802
type ThLevel = Int
803 804 805 806 807
    -- 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
808

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

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

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

822 823
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ross's avatar
ross committed
824 825 826 827
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

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

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

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

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

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

843 844 845 846 847 848 849 850 851 852
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
853 854
-}

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

859

860 861 862 863
---------------------------
-- TcTyThing
---------------------------

Edward Z. Yang's avatar
Edward Z. Yang committed
864 865 866
-- | 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'.
867
data TcTyThing
868
  = AGlobal TyThing             -- Used only in the return type of a lookup
869

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

874 875 876 877
  | 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
878

879
  | ATcTyCon TyCon   -- Used temporarily, during kind checking, for the
880
                     -- tycons and clases in this recursive group
881 882
                     -- 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
883 884
                     -- Note [Type checking recursive type and class declarations]

885
  | APromotionErr PromotionErr
886

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

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

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

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

instance Outputable PromotionErr where
914 915
  ppr ClassPE        = text "ClassPE"
  ppr TyConPE        = text "TyConPE"
916
  ppr PatSynPE       = text "PatSynPE"
917 918 919 920 921
  ppr FamDataConPE   = text