TcRnTypes.hs 95.3 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
{-# LANGUAGE CPP, ExistentialQuantification, GeneralizedNewtypeDeriving #-}
20

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

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

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

34
        -- Renamer types
35
        ErrCtxt, RecFieldEnv,
36 37
        ImportAvails(..), emptyImportAvails, plusImportAvails,
        WhereFrom(..), mkModDeps,
38

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

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

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

54
        -- Arrows
55
        ArrowCtxt(..),
56

57
        -- Canonical constraints
58 59
        Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
        singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
60
        isEmptyCts, isCTyEqCan, isCFunEqCan,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
61
        isCDictCan_Maybe, isCFunEqCan_maybe,
62
        isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
63
        isGivenCt, isHoleCt, isOutOfScopeCt, isExprHoleCt, isTypeHoleCt,
64
        isUserTypeErrorCt, getUserTypeErrorMsg,
65
        ctEvidence, ctLoc, setCtLoc, ctPred, ctFlavour, ctEqRel, ctOrigin,
66
        mkNonCanonical, mkNonCanonicalCt,
67
        ctEvPred, ctEvLoc, ctEvOrigin, ctEvEqRel,
68
        ctEvTerm, ctEvCoercion, ctEvId,
69

70
        WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
71
        andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
72
        dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
73
        isDroppableDerivedLoc, insolubleImplic, trulyInsoluble,
74

75
        Implication(..), ImplicStatus(..), isInsolubleStatus,
76 77
        SubGoalDepth, initialSubGoalDepth,
        bumpSubGoalDepth, subGoalDepthExceeded,
78
        CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
79
        ctLocDepth, bumpCtLocDepth,
thomasw's avatar
thomasw committed
80
        setCtLocOrigin, setCtLocEnv, setCtLocSpan,
81
        CtOrigin(..), pprCtOrigin, pprCtLoc,
82
        pushErrCtxt, pushErrCtxtSameOrigin,
83

84
        SkolemInfo(..),
85

86
        CtEvidence(..),
87
        mkGivenLoc,
88
        isWanted, isGiven, isDerived,
89
        ctEvRole,
90

Adam Gundry's avatar
Adam Gundry committed
91 92 93
        -- Constraint solver plugins
        TcPlugin(..), TcPluginResult(..), TcPluginSolver,
        TcPluginM, runTcPluginM, unsafeTcPluginTcM,
94
        getEvBindsTcPluginM_maybe,
Adam Gundry's avatar
Adam Gundry committed
95

96
        CtFlavour(..), ctEvFlavour,
97
        CtFlavourRole, ctEvFlavourRole, ctFlavourRole,
eir@cis.upenn.edu's avatar
eir@cis.upenn.edu committed
98
        eqCanRewrite, eqCanRewriteFR, canDischarge, canDischargeFR,
99

100
        -- Pretty printing
Austin Seipp's avatar
Austin Seipp committed
101
        pprEvVarTheta,
102
        pprEvVars, pprEvVarWithType,
103

104
        -- Misc other types
105
        TcId, TcIdSet, HoleSort(..)
106

107 108 109 110
  ) where

#include "HsVersions.h"

111
import HsSyn
112
import CoreSyn
113
import HscTypes
114
import TcEvidence
115
import Type
116
import CoAxiom  ( Role )
117
import Class    ( Class )
118
import TyCon    ( TyCon )
cactus's avatar
cactus committed
119
import ConLike  ( ConLike(..) )
120
import DataCon  ( DataCon, dataConUserType, dataConOrigArgTys )
121
import PatSyn   ( PatSyn, patSynType )
122
import FieldLabel ( FieldLabel )
123
import TcType
124
import Annotations
125 126
import InstEnv
import FamInstEnv
127
import IOEnv
128 129
import RdrName
import Name
130
import NameEnv
131
import NameSet
132
import Avail
133 134
import Var
import VarEnv
135
import Module
136 137 138
import SrcLoc
import VarSet
import ErrUtils
139
import UniqFM
140 141
import UniqSupply
import BasicTypes
142
import Bag
Ian Lynagh's avatar
Ian Lynagh committed
143
import DynFlags
144
import Outputable
145
import ListSetOps
146
import FastString
147
import GHC.Fingerprint
148

149
import Control.Monad (ap, liftM, msum)
150 151

#ifdef GHCI
152 153 154 155
import Data.Map      ( Map )
import Data.Dynamic  ( Dynamic )
import Data.Typeable ( TypeRep )

156 157
import qualified Language.Haskell.TH as TH
#endif
158

Austin Seipp's avatar
Austin Seipp committed
159 160 161
{-
************************************************************************
*                                                                      *
162
               Standard monad definition for TcRn
163
    All the combinators for the monad can be found in TcRnMonad
Austin Seipp's avatar
Austin Seipp committed
164 165
*                                                                      *
************************************************************************
166

167
The monad itself has to be defined here, because it is mentioned by ErrCtxt
Austin Seipp's avatar
Austin Seipp committed
168
-}
169

cactus's avatar
cactus committed
170
type TcRnIf a b = IOEnv (Env a b)
171 172 173 174 175 176 177 178 179 180 181 182
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
183 184 185 186 187 188

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

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

190 191 192 193
-- 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
194
  = Env {
195 196
        env_top  :: HscEnv,  -- Top-level stuff that never changes
                             -- Includes all info about imported things
197

198 199
        env_us   :: {-# UNPACK #-} !(IORef UniqSupply),
                             -- Unique supply for local varibles
200

201 202
        env_gbl  :: gbl,     -- Info about things defined at the top level
                             -- of the module being compiled
203

204
        env_lcl  :: lcl      -- Nested stuff; changes as we go into
205
    }
206

Ian Lynagh's avatar
Ian Lynagh committed
207 208
instance ContainsDynFlags (Env gbl lcl) where
    extractDynFlags env = hsc_dflags (env_top env)
209 210
    replaceDynFlags env dflags
        = env {env_top = replaceDynFlags (env_top env) dflags}
Ian Lynagh's avatar
Ian Lynagh committed
211

212 213 214
instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
    extractModule env = extractModule (env_gbl env)

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333

{-
************************************************************************
*                                                                      *
                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
                                        -- (and coercions)
        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
        dsl_loc     :: SrcSpan           -- to put in pattern-matching error msgs
     }

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

334 335 336 337 338 339 340 341
-- | '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.
342 343 344
data FrontendResult
        = FrontendTypecheck TcGblEnv

Edward Z. Yang's avatar
Edward Z. Yang committed
345
-- | 'TcGblEnv' describes the top-level of the module at the
346 347
-- point at which the typechecker is finished work.
-- It is this structure that is handed on to the desugarer
348
-- For state that needs to be updated during the typechecking
Edward Z. Yang's avatar
Edward Z. Yang committed
349
-- phase and returned at end, use a 'TcRef' (= 'IORef').
350 351
data TcGblEnv
  = TcGblEnv {
352 353
        tcg_mod     :: Module,         -- ^ Module being compiled
        tcg_src     :: HscSource,
354
          -- ^ What kind of module (regular Haskell, hs-boot, hsig)
355 356 357 358 359
        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]
360

361 362
        tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
        tcg_default :: Maybe [Type],
363
          -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
364

365 366
        tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
        tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
367
                                        -- See Note [The interactive package] in HscTypes
368

369
        tcg_type_env :: TypeEnv,
370
          -- ^ Global type env for the module we are compiling now.  All
371 372 373 374 375
          -- 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)
376 377 378
          --
          -- NB: for what "things in this module" means, see
          -- Note [The interactive package] in HscTypes
379 380 381 382 383 384 385 386 387

        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;
388
          -- Includes the dfuns in tcg_insts
389
        tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
390
        tcg_ann_env      :: AnnEnv,     -- ^ And for annotations
391 392 393 394 395 396 397

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

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

406
        tcg_keep :: TcRef NameSet,
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
          -- ^ 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

425
        tcg_th_used :: TcRef Bool,
426 427
          -- ^ @True@ <=> Template Haskell syntax used.
          --
428
          -- We need this so that we can generate a dependency on the
Gabor Greif's avatar
typos  
Gabor Greif committed
429
          -- Template Haskell package, because the desugarer is going
430 431
          -- to emit loads of references to TH symbols.  The reference
          -- is implicit rather than explicit, so we have to zap a
432 433
          -- mutable variable.

434 435 436 437 438
        tcg_th_splice_used :: TcRef Bool,
          -- ^ @True@ <=> A Template Haskell splice was used.
          --
          -- Splices disable recompilation avoidance (see #481)

439
        tcg_dfun_n  :: TcRef OccSet,
440
          -- ^ Allows us to choose unique DFun names.
441

442
        -- The next fields accumulate the payload of the module
Gabor Greif's avatar
Gabor Greif committed
443
        -- The binds, rules and foreign-decl fields are collected
444
        -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
445

446
        tcg_rn_exports :: Maybe [Located (IE Name)],
447
                -- Nothing <=> no explicit export list
448 449
                -- Is always Nothing if we don't want to retain renamed
                -- exports
450

451
        tcg_rn_imports :: [LImportDecl Name],
452 453
                -- 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
454

455
        tcg_rn_decls :: Maybe (HsGroup Name),
456 457
          -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
          -- decls.
458

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

461 462 463 464 465 466
#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
467 468 469

        tcg_th_modfinalizers :: TcRef [TH.Q ()],
        -- ^ Template Haskell module finalizers
470 471 472

        tcg_th_state :: TcRef (Map TypeRep Dynamic),
        -- ^ Template Haskell state
473 474
#endif /* GHCI */

475
        tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
476

477 478 479
        -- 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
480 481 482
        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
483 484 485 486 487 488 489 490 491 492 493 494
        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
495

496
        tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
497 498 499
        tcg_hpc       :: AnyHpcUsage,        -- ^ @True@ if any part of the
                                             --  prog uses hpc instrumentation.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
500 501 502
        tcg_self_boot :: SelfBootInfo,       -- ^ Whether this module has a
                                             -- corresponding hi-boot file

503
        tcg_main      :: Maybe Name,         -- ^ The Name of the main
504 505
                                             -- function, if this module is
                                             -- the main module.
Adam Gundry's avatar
Adam Gundry committed
506

507 508 509 510 511
        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.

512
        tcg_tc_plugins :: [TcPluginSolver],
513
        -- ^ A list of user-defined plugins for the constraint solver.
514 515 516

        tcg_static_wc :: TcRef WantedConstraints
          -- ^ Wanted constraints of static forms.
517
    }
518

519 520 521 522
tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
tcVisibleOrphanMods tcg_env
    = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
-- 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

570 571 572
instance ContainsModule TcGblEnv where
    extractModule env = tcg_mod env

573 574 575
type RecFieldEnv = NameEnv [FieldLabel]
        -- Maps a constructor name *in this module*
        -- to the fields for that constructor.
576 577 578 579 580
        -- 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
581

Simon Peyton Jones's avatar
Simon Peyton Jones committed
582 583 584 585 586 587 588 589 590
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

591 592 593 594
{- Note [Tracking unused binding and imports]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We gather two sorts of usage information

595 596 597 598 599 600 601 602
 * 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)
603
   This usage info is mainly gathered by the renamer's
604 605
   gathering of free-variables

606
 * tcg_used_gres
607
      Used only to report unused import declarations
608 609 610 611 612 613 614

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

616

Austin Seipp's avatar
Austin Seipp committed
617 618
************************************************************************
*                                                                      *
619
                The local typechecker environment
Austin Seipp's avatar
Austin Seipp committed
620 621
*                                                                      *
************************************************************************
622

Edward Z. Yang's avatar
Edward Z. Yang committed
623 624
Note [The Global-Env/Local-Env story]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
625
During type checking, we keep in the tcg_type_env
626 627
        * All types and classes
        * All Ids derived from types and classes (constructors, selectors)
628 629 630

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

Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
634 635 636
        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
637
-}
638

639 640
data TcLclEnv           -- Changes as we move inside an expression
                        -- Discarded after typecheck/rename; not passed on to desugarer
641
  = TcLclEnv {
642
        tcl_loc        :: RealSrcSpan,     -- Source span
643
        tcl_ctxt       :: [ErrCtxt],       -- Error context, innermost on top
644
        tcl_tclvl      :: TcLevel,         -- Birthplace for new unification variables
645

646
        tcl_th_ctxt    :: ThStage,         -- Template Haskell context
647 648 649
        tcl_th_bndrs   :: ThBindEnv,       -- Binding level of in-scope Names
                                           -- defined in this module (not imported)

650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
        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
666

667
        tcl_bndrs :: TcIdBinderStack,   -- Used for reporting relevant bindings
668 669 670

        tcl_tidy :: TidyEnv,      -- Used for tidying types; contains all
                                  -- in-scope type variables (but not term variables)
671 672 673 674 675

        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.
676 677
                        -- Why mutable? see notes with tcGetGlobalTyVars

678 679
        tcl_lie  :: TcRef WantedConstraints,    -- Place to accumulate type constraints
        tcl_errs :: TcRef Messages              -- Place to accumulate errors
680 681
    }

682
type TcTypeEnv = NameEnv TcTyThing
683

684 685 686 687 688 689 690 691 692
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

693 694
{- Note [Given Insts]
   ~~~~~~~~~~~~~~~~~~
695
Because of GADTs, we have to pass inwards the Insts provided by type signatures
696
and existential contexts. Consider
697 698 699
        data T a where { T1 :: b -> b -> T [b] }
        f :: Eq a => T a -> Bool
        f (T1 x y) = [x]==[y]
700 701

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

-}
706

707 708 709 710 711 712 713 714
-- | 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

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
---------------------------
-- 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)

733
---------------------------
734
-- Template Haskell stages and levels
735 736
---------------------------

737 738
data SpliceType = Typed | Untyped

739
data ThStage    -- See Note [Template Haskell state diagram] in TcSplice
740 741 742 743
  = Splice SpliceType -- Inside a top-level splice
                      -- This code will be run *at compile time*;
                      --   the result replaces the splice
                      -- Binding level = 0
744 745 746

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

748
  | Brack                       -- Inside brackets
749 750 751 752 753 754 755 756 757
      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

758
  | TcPending                     -- Typechecking the inside of a typed bracket
759 760
      (TcRef [PendingTcSplice])   --   Accumulate pending splices here
      (TcRef WantedConstraints)   --     and type constraints here
761 762 763

topStage, topAnnStage, topSpliceStage :: ThStage
topStage       = Comp
764 765
topAnnStage    = Splice Untyped
topSpliceStage = Splice Untyped
766 767

instance Outputable ThStage where
768 769 770
   ppr (Splice _)  = text "Splice"
   ppr Comp        = text "Comp"
   ppr (Brack s _) = text "Brack" <> parens (ppr s)
771

772
type ThLevel = Int
773 774 775 776 777
    -- 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
778

779
impLevel, outerLevel :: ThLevel
780 781
impLevel = 0    -- Imported things; they can be used inside a top level splice
outerLevel = 1  -- Things defined outside brackets
782

783
thLevel :: ThStage -> ThLevel
784 785 786
thLevel (Splice _)  = 0
thLevel Comp        = 1
thLevel (Brack s _) = thLevel s + 1
787

788 789 790 791
---------------------------
-- Arrow-notation context
---------------------------

792 793
{- Note [Escaping the arrow scope]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
794 795 796 797
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

798
        proc x -> (e1 -< e2)
799 800 801 802

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

803 804
        let x = 3 in
        proc y -> (proc z -> e1) -< e2
805

806
Here, x and z are in scope in e1, but y is not.
807 808

We implement this by
809 810 811
recording the environment when passing a proc (using newArrowScope),
and returning to that (using escapeArrowScope) on the left of -< and the
head of (|..|).
812

813 814 815 816 817 818 819 820 821 822
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.
823 824
-}

825
data ArrowCtxt   -- Note [Escaping the arrow scope]
826
  = NoArrowCtxt
827 828
  | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)

829

830 831 832 833
---------------------------
-- TcTyThing
---------------------------

Edward Z. Yang's avatar
Edward Z. Yang committed
834 835 836
-- | 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'.
837
data TcTyThing
838
  = AGlobal TyThing             -- Used only in the return type of a lookup
839

840 841
  | ATcId   {           -- Ids defined in this module; may not be fully zonked
        tct_id     :: TcId,
842
        tct_closed :: TopLevelFlag }   -- See Note [Bindings with closed types]
843

844 845 846 847
  | 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
848

dreixel's avatar
dreixel committed
849
  | AThing  TcKind   -- Used temporarily, during kind checking, for the
850
                     -- tycons and clases in this recursive group
dreixel's avatar
dreixel committed
851 852 853
                     -- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
                     -- Note [Type checking recursive type and class declarations]

854
  | APromotionErr PromotionErr
855

856
data PromotionErr
857 858 859 860 861
  = TyConPE          -- TyCon used in a kind before we are ready
                     --     data T :: T -> * where ...
  | ClassPE          -- Ditto Class

  | FamDataConPE     -- Data constructor for a data family
862
                     -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
dreixel's avatar
dreixel committed
863

Krzysztof Gogolewski's avatar
Krzysztof Gogolewski committed
864
  | RecDataConPE     -- Data constructor in a recursive loop
865
                     -- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
866
  | NoDataKinds      -- -XDataKinds not enabled
867

868
instance Outputable TcTyThing where     -- Debugging only
869
   ppr (AGlobal g)      = pprTyThing g
870 871
   ppr elt@(ATcId {})   = text "Identifier" <>
                          brackets (ppr (tct_id elt) <> dcolon
872
                                 <> ppr (varType (tct_id elt)) <> comma
873
                                 <+> ppr (tct_closed elt))
Simon Peyton Jones's avatar
Simon Peyton Jones committed
874
   ppr (ATyVar n tv)    = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
875
   ppr (AThing k)       = text "AThing" <+> ppr k
876 877 878 879 880 881 882
   ppr (APromotionErr err) = text "APromotionErr" <+> ppr err

instance Outputable PromotionErr where
  ppr ClassPE      = text "ClassPE"
  ppr TyConPE      = text "TyConPE"
  ppr FamDataConPE = text "FamDataConPE"
  ppr RecDataConPE = text "RecDataConPE"
883
  ppr NoDataKinds  = text "NoDataKinds"
884 885

pprTcTyThingCategory :: TcTyThing -> SDoc
886 887 888 889 890 891 892 893 894 895 896
pprTcTyThingCategory (AGlobal thing)    = pprTyThingCategory thing
pprTcTyThingCategory (ATyVar {})        = ptext (sLit "Type variable")
pprTcTyThingCategory (ATcId {})         = ptext (sLit "Local identifier")
pprTcTyThingCategory (AThing {})        = ptext (sLit "Kinded thing")
pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe

pprPECategory :: PromotionErr -> SDoc
pprPECategory ClassPE      = ptext (sLit "Class")
pprPECategory TyConPE      = ptext (sLit "Type constructor")
pprPECategory FamDataConPE = ptext (sLit "Data constructor")
pprPECategory RecDataConPE = ptext (sLit "Data constructor")
897
pprPECategory NoDataKinds  = ptext (sLit "Data constructor")
898

899
{- Note [Bindings with closed types]
900
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
901 902 903 904 905
Consider

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

906
Can we generalise 'g' under the OutsideIn algorithm?  Yes,
dreixel's avatar
dreixel committed
907
because all g's free variables are top-level; that is they themselves
908 909 910 911 912
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,
913 914
iff
   a) all its free variables are imported, or are let-bound with closed types
915 916
   b) generalisation is not restricted by the monomorphism restriction

917 918
Invariant: a closed variable has no free type variables in its type.

919 920
Under OutsideIn we are free to generalise a closed let-binding.
This is an extension compared to the JFP paper on OutsideIn, which
921
used "top-level" as a proxy for "closed".  (It's not a good proxy
922 923 924 925
anyway -- the MR can make a top-level binding with a free type
variable.)

Note that:
926
  * A top-level binding may not be closed, if it suffers from the MR
927 928 929

  * 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
930
    or nested is orthogonal to the question of whether or not it is closed
931 932 933 934 935

  * 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)...
Austin Seipp's avatar
Austin Seipp committed
936
-}
937

938
type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
939 940 941
        -- Monadic so that we have a chance
        -- to deal with bound type variables just before error
        -- message construction
942

943 944
        -- Bool:  True <=> this is a landmark context; do not
        --                 discard it when trimming for display
945

Austin Seipp's avatar
Austin Seipp committed
946 947 948
{-
************************************************************************
*                                                                      *
949
        Operations over ImportAvails
Austin Seipp's avatar
Austin Seipp committed
950 951 952
*                                                                      *
************************************************************************
-}
953

954 955 956 957 958 959 960 961 962 963 964 965
-- | '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
--
966
data ImportAvails
967
   = ImportAvails {
968
        imp_mods :: ImportedMods,
969
          --      = ModuleEnv [ImportedModsVal],
970
          -- ^ Domain is all directly-imported modules
971
          --
972 973
          -- See the documentaion on ImportedModsVal in HscTypes for the
          -- meaning of the fields.
974
          --
975 976 977 978
          -- 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).
979

980 981 982 983 984 985 986 987 988 989
        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.

990
        imp_dep_pkgs :: [UnitId],
991 992 993
          -- ^ Packages needed by the module being compiled, whether directly,
          -- or via other modules in this package, or via modules imported
          -- from other packages.
994

995
        imp_trust_pkgs :: [UnitId],
996 997 998 999
          -- ^ 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.
1000
          -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1001 1002 1003
          -- 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.
1004
          -- See Note [RnNames . Tracking Trust Transitively]
1005

1006 1007 1008 1009 1010 1011 1012
        imp_trust_own_pkg :: Bool,
          -- ^ Do we require that our own package is trusted?
          -- This is to handle efficiently the case where a Safe module imports
          -- a Trustworthy module that resides in the same package as it.
          -- See Note [RnNames . Trust Own Package]

        imp_orphs :: [Module],
1013 1014
          -- ^ Orphan modules below us in the import tree (and maybe including
          -- us for imported modules)
1015

1016
        imp_finsts :: [Module]
1017 1018
          -- ^ Family instance modules below us in the import tree (and maybe
          -- including us for imported modules)
1019 1020
      }

Simon Marlow's avatar
Simon Marlow committed
1021
mkModDeps :: [(ModuleName, IsBootInterface)]
1022
          -> ModuleNameEnv (ModuleName, IsBootInterface)
Simon Marlow's avatar
Simon Marlow committed
1023
mkModDeps deps = foldl add emptyUFM deps
1024 1025
               where
                 add env elt@(m,_) = addToUFM env m elt
1026

1027
emptyImportAvails :: ImportAvails
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
emptyImportAvails = ImportAvails { imp_mods          = emptyModuleEnv,
                                   imp_dep_mods      = emptyUFM,
                                   imp_dep_pkgs      = [],
                                   imp_trust_pkgs    = [],
                                   imp_trust_own_pkg = False,
                                   imp_orphs         = [],
                                   imp_finsts        = [] }

-- | Union two ImportAvails
--
-- This function is a key part of Import handling, basically
Gabor Greif's avatar
Gabor Greif committed
1039
-- for each import we create a separate ImportAvails structure
1040
-- and then union them all together with this function.
1041 1042
plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
plusImportAvails
1043
  (ImportAvails { imp_mods = mods1,
1044 1045
                  imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
                  imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1046 1047
                  imp_orphs = orphs1, imp_finsts = finsts1 })
  (ImportAvails { imp_mods = mods2,
1048 1049
                  imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
                  imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1050
                  imp_orphs = orphs2, imp_finsts = finsts2 })
1051 1052 1053 1054 1055 1056 1057
  = ImportAvails { imp_mods          = plusModuleEnv_C (++) mods1 mods2,
                   imp_dep_mods      = plusUFM_C plus_mod_dep dmods1 dmods2,
                   imp_dep_pkgs      = dpkgs1 `unionLists` dpkgs2,
                   imp_trust_pkgs    = tpkgs1 `unionLists` tpkgs2,
                   imp_trust_own_pkg = tself1 || tself2,
                   imp_orphs         = orphs1 `unionLists` orphs2,
                   imp_finsts        = finsts1 `unionLists` finsts2 }
1058
  where
1059
    plus_mod_dep (m1, boot1) (m2, boot2)
1060 1061 1062
        = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
                -- Check mod-names match
          (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
1063

Austin Seipp's avatar
Austin Seipp committed
1064 1065 1066
{-
************************************************************************
*                                                                      *
1067
\subsection{Where from}
Austin Seipp's avatar
Austin Seipp committed
1068 1069
*                                                                      *
************************************************************************
1070 1071

The @WhereFrom@ type controls where the renamer looks for an interface file
Austin Seipp's avatar
Austin Seipp committed
1072
-}
1073

1074 1075 1076
data WhereFrom
  = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
  | ImportBySystem                      -- Non user import.
1077
  | ImportByPlugin                      -- Importing a plugin;
1078
                                        -- See Note [Care with plugin imports] in LoadIface
1079 1080

instance Outputable WhereFrom where
Ian Lynagh's avatar
Ian Lynagh committed
1081
  ppr (ImportByUser is_boot) | is_boot     = ptext (sLit "{- SOURCE -}")
1082 1083
                             | otherwise   = empty
  ppr ImportBySystem                       = ptext (sLit "{- SYSTEM -}")
1084
  ppr ImportByPlugin                       = ptext (sLit "{- PLUGIN -}")
1085

Austin Seipp's avatar
Austin Seipp committed
1086 1087 1088 1089 1090 1091 1092 1093 1094
{-
************************************************************************
*                                                                      *
*                       Canonical constraints                          *
*                                                                      *
*   These are the constraints the low-level simplifier works with      *
*                                                                      *
************************************************************************
-}
1095

1096 1097 1098 1099
-- The syntax of xi types:
-- xi ::= a | T xis | xis -> xis | ... | forall a. tau
-- Two important notes:
--      (i) No type families, unless we are under a ForAll
1100 1101
--      (ii) Note that xi types can contain unexpanded type synonyms;
--           however, the (transitive) expansions of those type synonyms
1102 1103 1104
--           will not contain any type functions, unless we are under a ForAll.
-- We enforce the structure of Xi types when we flatten (TcCanonical)

1105 1106 1107 1108 1109
type Xi = Type       -- In many comments, "xi" ranges over Xi

type Cts = Bag Ct

data Ct
1110
  -- Atomic canonical constraints
1111
  = CDictCan {  -- e.g.  Num xi
1112
      cc_ev     :: CtEvidence, -- See Note [Ct/evidence invariant]
1113
      cc_class  :: Class,
1114
      cc_tyargs :: [Xi]        -- cc_tyargs are function-free, hence Xi
1115 1116
    }

1117
  | CIrredEvCan {  -- These stand for yet-unusable predicates
1118
      cc_ev :: CtEvidence   -- See Note [Ct/evidence invariant]
1119
        -- The ctev_pred of the evidence is
1120
        -- of form   (tv xi1 xi2 ... xin)
1121 1122
        --      or   (tv1 ~ ty2)   where the CTyEqCan  kind invariant fails
        --      or   (F tys ~ ty)  where the CFunEqCan kind invariant fails
1123
        -- See Note [CIrredEvCan constraints]
1124 1125
    }