d2c8dd8a436c18f78fd9b60f8a514a8fd03bdf41
[ghc.git] / compiler / typecheck / TcRnTypes.hs
1 {-
2 (c) The University of Glasgow 2006-2012
3 (c) The GRASP Project, Glasgow University, 1992-2002
4
5
6 Various types used during typechecking, please see TcRnMonad as well for
7 operations on these types. You probably want to import it, instead of this
8 module.
9
10 All the monads exported here are built on top of the same IOEnv monad. The
11 monad functions like a Reader monad in the way it passes the environment
12 around. This is done to allow the environment to be manipulated in a stack
13 like fashion when entering expressions... etc.
14
15 For state that is global and should be returned at the end (e.g not part
16 of the stack mechanism), you should use a TcRef (= IORef) to store them.
17 -}
18
19 {-# LANGUAGE CPP, ExistentialQuantification, GeneralizedNewtypeDeriving,
20 ViewPatterns #-}
21
22 module TcRnTypes(
23 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
24 TcRef,
25
26 -- The environment types
27 Env(..),
28 TcGblEnv(..), TcLclEnv(..),
29 IfGblEnv(..), IfLclEnv(..),
30 tcVisibleOrphanMods,
31
32 -- Frontend types (shouldn't really be here)
33 FrontendResult(..),
34
35 -- Renamer types
36 ErrCtxt, RecFieldEnv,
37 ImportAvails(..), emptyImportAvails, plusImportAvails,
38 WhereFrom(..), mkModDeps, modDepsElts,
39
40 -- Typechecker types
41 TcTypeEnv, TcBinderStack, TcBinder(..),
42 TcTyThing(..), PromotionErr(..),
43 IdBindingInfo(..), ClosedTypeId, RhsNames,
44 IsGroupClosed(..),
45 SelfBootInfo(..),
46 pprTcTyThingCategory, pprPECategory, CompleteMatch(..),
47
48 -- Desugaring types
49 DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
50 DsMetaEnv, DsMetaVal(..), CompleteMatchMap,
51 mkCompleteMatchMap, extendCompleteMatchMap,
52
53 -- Template Haskell
54 ThStage(..), SpliceType(..), PendingStuff(..),
55 topStage, topAnnStage, topSpliceStage,
56 ThLevel, impLevel, outerLevel, thLevel,
57 ForeignSrcLang(..),
58
59 -- Arrows
60 ArrowCtxt(..),
61
62 -- TcSigInfo
63 TcSigFun, TcSigInfo(..), TcIdSigInfo(..),
64 TcIdSigInst(..), TcPatSynInfo(..),
65 isPartialSig, hasCompleteSig,
66
67 -- Canonical constraints
68 Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
69 singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
70 isEmptyCts, isCTyEqCan, isCFunEqCan,
71 isPendingScDict, superClassesMightHelp,
72 isCDictCan_Maybe, isCFunEqCan_maybe,
73 isCNonCanonical, isWantedCt, isDerivedCt,
74 isGivenCt, isHoleCt, isOutOfScopeCt, isExprHoleCt, isTypeHoleCt,
75 isUserTypeErrorCt, getUserTypeErrorMsg,
76 ctEvidence, ctLoc, setCtLoc, ctPred, ctFlavour, ctEqRel, ctOrigin,
77 ctEvId, mkTcEqPredLikeEv,
78 mkNonCanonical, mkNonCanonicalCt, mkGivens,
79 mkIrredCt, mkInsolubleCt,
80 ctEvPred, ctEvLoc, ctEvOrigin, ctEvEqRel,
81 ctEvExpr, ctEvCoercion, ctEvEvId,
82 tyCoVarsOfCt, tyCoVarsOfCts,
83 tyCoVarsOfCtList, tyCoVarsOfCtsList,
84
85 WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
86 andWC, unionsWC, mkSimpleWC, mkImplicWC,
87 addInsols, insolublesOnly, addSimples, addImplics,
88 tyCoVarsOfWC, dropDerivedWC, dropDerivedSimples,
89 tyCoVarsOfWCList, insolubleWantedCt, insolubleEqCt,
90 isDroppableCt, insolubleImplic,
91 arisesFromGivens,
92
93 Implication(..), newImplication,
94 ImplicStatus(..), isInsolubleStatus, isSolvedStatus,
95 SubGoalDepth, initialSubGoalDepth, maxSubGoalDepth,
96 bumpSubGoalDepth, subGoalDepthExceeded,
97 CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
98 ctLocTypeOrKind_maybe,
99 ctLocDepth, bumpCtLocDepth, isGivenLoc,
100 setCtLocOrigin, updateCtLocOrigin, setCtLocEnv, setCtLocSpan,
101 CtOrigin(..), exprCtOrigin, lexprCtOrigin, matchesCtOrigin, grhssCtOrigin,
102 isVisibleOrigin, toInvisibleOrigin,
103 TypeOrKind(..), isTypeLevel, isKindLevel,
104 pprCtOrigin, pprCtLoc,
105 pushErrCtxt, pushErrCtxtSameOrigin,
106
107
108 SkolemInfo(..), pprSigSkolInfo, pprSkolInfo,
109 termEvidenceAllowed,
110
111 CtEvidence(..), TcEvDest(..),
112 mkKindLoc, toKindLoc, mkGivenLoc,
113 isWanted, isGiven, isDerived, isGivenOrWDeriv,
114 ctEvRole,
115
116 wrapType, wrapTypeWithImplication,
117
118 -- Constraint solver plugins
119 TcPlugin(..), TcPluginResult(..), TcPluginSolver,
120 TcPluginM, runTcPluginM, unsafeTcPluginTcM,
121 getEvBindsTcPluginM,
122
123 CtFlavour(..), ShadowInfo(..), ctEvFlavour,
124 CtFlavourRole, ctEvFlavourRole, ctFlavourRole,
125 eqCanRewrite, eqCanRewriteFR, eqMayRewriteFR,
126 eqCanDischargeFR,
127 funEqCanDischarge, funEqCanDischargeF,
128
129 -- Pretty printing
130 pprEvVarTheta,
131 pprEvVars, pprEvVarWithType,
132
133 -- Misc other types
134 TcId, TcIdSet,
135 Hole(..), holeOcc,
136 NameShape(..),
137
138 -- Role annotations
139 RoleAnnotEnv, emptyRoleAnnotEnv, mkRoleAnnotEnv,
140 lookupRoleAnnot, getRoleAnnots,
141
142 ) where
143
144 #include "HsVersions.h"
145
146 import GhcPrelude
147
148 import HsSyn
149 import CoreSyn
150 import HscTypes
151 import TcEvidence
152 import Type
153 import Class ( Class )
154 import TyCon ( TyCon, tyConKind )
155 import TyCoRep ( CoercionHole(..), coHoleCoVar )
156 import Coercion ( Coercion, mkHoleCo )
157 import ConLike ( ConLike(..) )
158 import DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
159 import PatSyn ( PatSyn, pprPatSynType )
160 import Id ( idType, idName )
161 import FieldLabel ( FieldLabel )
162 import TcType
163 import Annotations
164 import InstEnv
165 import FamInstEnv
166 import PmExpr
167 import IOEnv
168 import RdrName
169 import Name
170 import NameEnv
171 import NameSet
172 import Avail
173 import Var
174 import FV
175 import VarEnv
176 import Module
177 import SrcLoc
178 import VarSet
179 import ErrUtils
180 import UniqFM
181 import UniqSupply
182 import BasicTypes
183 import Bag
184 import DynFlags
185 import Outputable
186 import ListSetOps
187 import FastString
188 import qualified GHC.LanguageExtensions as LangExt
189 import Fingerprint
190 import Util
191 import PrelNames ( isUnboundName )
192
193 import Control.Monad (ap, liftM, msum)
194 import qualified Control.Monad.Fail as MonadFail
195 import Data.Set ( Set )
196 import qualified Data.Set as S
197
198 import Data.List ( sort )
199 import Data.Map ( Map )
200 import Data.Dynamic ( Dynamic )
201 import Data.Typeable ( TypeRep )
202 import Data.Maybe ( mapMaybe )
203 import GHCi.Message
204 import GHCi.RemoteTypes
205
206 import qualified Language.Haskell.TH as TH
207
208 -- | A 'NameShape' is a substitution on 'Name's that can be used
209 -- to refine the identities of a hole while we are renaming interfaces
210 -- (see 'RnModIface'). Specifically, a 'NameShape' for
211 -- 'ns_module_name' @A@, defines a mapping from @{A.T}@
212 -- (for some 'OccName' @T@) to some arbitrary other 'Name'.
213 --
214 -- The most intruiging thing about a 'NameShape', however, is
215 -- how it's constructed. A 'NameShape' is *implied* by the
216 -- exported 'AvailInfo's of the implementor of an interface:
217 -- if an implementor of signature @<H>@ exports @M.T@, you implicitly
218 -- define a substitution from @{H.T}@ to @M.T@. So a 'NameShape'
219 -- is computed from the list of 'AvailInfo's that are exported
220 -- by the implementation of a module, or successively merged
221 -- together by the export lists of signatures which are joining
222 -- together.
223 --
224 -- It's not the most obvious way to go about doing this, but it
225 -- does seem to work!
226 --
227 -- NB: Can't boot this and put it in NameShape because then we
228 -- start pulling in too many DynFlags things.
229 data NameShape = NameShape {
230 ns_mod_name :: ModuleName,
231 ns_exports :: [AvailInfo],
232 ns_map :: OccEnv Name
233 }
234
235
236 {-
237 ************************************************************************
238 * *
239 Standard monad definition for TcRn
240 All the combinators for the monad can be found in TcRnMonad
241 * *
242 ************************************************************************
243
244 The monad itself has to be defined here, because it is mentioned by ErrCtxt
245 -}
246
247 type TcRnIf a b = IOEnv (Env a b)
248 type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
249 type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
250 type IfG = IfM () -- Top level
251 type IfL = IfM IfLclEnv -- Nested
252 type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
253
254 -- TcRn is the type-checking and renaming monad: the main monad that
255 -- most type-checking takes place in. The global environment is
256 -- 'TcGblEnv', which tracks all of the top-level type-checking
257 -- information we've accumulated while checking a module, while the
258 -- local environment is 'TcLclEnv', which tracks local information as
259 -- we move inside expressions.
260
261 -- | Historical "renaming monad" (now it's just 'TcRn').
262 type RnM = TcRn
263
264 -- | Historical "type-checking monad" (now it's just 'TcRn').
265 type TcM = TcRn
266
267 -- We 'stack' these envs through the Reader like monad infrastructure
268 -- as we move into an expression (although the change is focused in
269 -- the lcl type).
270 data Env gbl lcl
271 = Env {
272 env_top :: HscEnv, -- Top-level stuff that never changes
273 -- Includes all info about imported things
274
275 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
276 -- Unique supply for local variables
277
278 env_gbl :: gbl, -- Info about things defined at the top level
279 -- of the module being compiled
280
281 env_lcl :: lcl -- Nested stuff; changes as we go into
282 }
283
284 instance ContainsDynFlags (Env gbl lcl) where
285 extractDynFlags env = hsc_dflags (env_top env)
286
287 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
288 extractModule env = extractModule (env_gbl env)
289
290
291 {-
292 ************************************************************************
293 * *
294 The interface environments
295 Used when dealing with IfaceDecls
296 * *
297 ************************************************************************
298 -}
299
300 data IfGblEnv
301 = IfGblEnv {
302 -- Some information about where this environment came from;
303 -- useful for debugging.
304 if_doc :: SDoc,
305 -- The type environment for the module being compiled,
306 -- in case the interface refers back to it via a reference that
307 -- was originally a hi-boot file.
308 -- We need the module name so we can test when it's appropriate
309 -- to look in this env.
310 -- See Note [Tying the knot] in TcIface
311 if_rec_types :: Maybe (Module, IfG TypeEnv)
312 -- Allows a read effect, so it can be in a mutable
313 -- variable; c.f. handling the external package type env
314 -- Nothing => interactive stuff, no loops possible
315 }
316
317 data IfLclEnv
318 = IfLclEnv {
319 -- The module for the current IfaceDecl
320 -- So if we see f = \x -> x
321 -- it means M.f = \x -> x, where M is the if_mod
322 -- NB: This is a semantic module, see
323 -- Note [Identity versus semantic module]
324 if_mod :: Module,
325
326 -- Whether or not the IfaceDecl came from a boot
327 -- file or not; we'll use this to choose between
328 -- NoUnfolding and BootUnfolding
329 if_boot :: Bool,
330
331 -- The field is used only for error reporting
332 -- if (say) there's a Lint error in it
333 if_loc :: SDoc,
334 -- Where the interface came from:
335 -- .hi file, or GHCi state, or ext core
336 -- plus which bit is currently being examined
337
338 if_nsubst :: Maybe NameShape,
339
340 -- This field is used to make sure "implicit" declarations
341 -- (anything that cannot be exported in mi_exports) get
342 -- wired up correctly in typecheckIfacesForMerging. Most
343 -- of the time it's @Nothing@. See Note [Resolving never-exported Names in TcIface]
344 -- in TcIface.
345 if_implicits_env :: Maybe TypeEnv,
346
347 if_tv_env :: FastStringEnv TyVar, -- Nested tyvar bindings
348 if_id_env :: FastStringEnv Id -- Nested id binding
349 }
350
351 {-
352 ************************************************************************
353 * *
354 Desugarer monad
355 * *
356 ************************************************************************
357
358 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
359 a @UniqueSupply@ and some annotations, which
360 presumably include source-file location information:
361 -}
362
363 -- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
364 -- variables found in 'Data.Array.Parallel'.
365 --
366 data PArrBuiltin
367 = PArrBuiltin
368 { lengthPVar :: Var -- ^ lengthP
369 , replicatePVar :: Var -- ^ replicateP
370 , singletonPVar :: Var -- ^ singletonP
371 , mapPVar :: Var -- ^ mapP
372 , filterPVar :: Var -- ^ filterP
373 , zipPVar :: Var -- ^ zipP
374 , crossMapPVar :: Var -- ^ crossMapP
375 , indexPVar :: Var -- ^ (!:)
376 , emptyPVar :: Var -- ^ emptyP
377 , appPVar :: Var -- ^ (+:+)
378 , enumFromToPVar :: Var -- ^ enumFromToP
379 , enumFromThenToPVar :: Var -- ^ enumFromThenToP
380 }
381
382 data DsGblEnv
383 = DsGblEnv
384 { ds_mod :: Module -- For SCC profiling
385 , ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
386 , ds_unqual :: PrintUnqualified
387 , ds_msgs :: IORef Messages -- Warning messages
388 , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
389 -- possibly-imported things
390 , ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
391 -- iff '-fvectorise' flag was given as well as
392 -- exported entities of 'Data.Array.Parallel' iff
393 -- '-XParallelArrays' was given; otherwise, empty
394 , ds_parr_bi :: PArrBuiltin -- desugarer names for '-XParallelArrays'
395 , ds_complete_matches :: CompleteMatchMap
396 -- Additional complete pattern matches
397 }
398
399 instance ContainsModule DsGblEnv where
400 extractModule = ds_mod
401
402 data DsLclEnv = DsLclEnv {
403 dsl_meta :: DsMetaEnv, -- Template Haskell bindings
404 dsl_loc :: RealSrcSpan, -- To put in pattern-matching error msgs
405 dsl_dicts :: Bag EvVar, -- Constraints from GADT pattern-matching
406 dsl_tm_cs :: Bag SimpleEq,
407 dsl_pm_iter :: IORef Int -- no iterations for pmcheck
408 }
409
410 -- Inside [| |] brackets, the desugarer looks
411 -- up variables in the DsMetaEnv
412 type DsMetaEnv = NameEnv DsMetaVal
413
414 data DsMetaVal
415 = DsBound Id -- Bound by a pattern inside the [| |].
416 -- Will be dynamically alpha renamed.
417 -- The Id has type THSyntax.Var
418
419 | DsSplice (HsExpr GhcTc) -- These bindings are introduced by
420 -- the PendingSplices on a HsBracketOut
421
422
423 {-
424 ************************************************************************
425 * *
426 Global typechecker environment
427 * *
428 ************************************************************************
429 -}
430
431 -- | 'FrontendResult' describes the result of running the
432 -- frontend of a Haskell module. Usually, you'll get
433 -- a 'FrontendTypecheck', since running the frontend involves
434 -- typechecking a program, but for an hs-boot merge you'll
435 -- just get a ModIface, since no actual typechecking occurred.
436 --
437 -- This data type really should be in HscTypes, but it needs
438 -- to have a TcGblEnv which is only defined here.
439 data FrontendResult
440 = FrontendTypecheck TcGblEnv
441
442 -- Note [Identity versus semantic module]
443 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
444 -- When typechecking an hsig file, it is convenient to keep track
445 -- of two different "this module" identifiers:
446 --
447 -- - The IDENTITY module is simply thisPackage + the module
448 -- name; i.e. it uniquely *identifies* the interface file
449 -- we're compiling. For example, p[A=<A>]:A is an
450 -- identity module identifying the requirement named A
451 -- from library p.
452 --
453 -- - The SEMANTIC module, which is the actual module that
454 -- this signature is intended to represent (e.g. if
455 -- we have a identity module p[A=base:Data.IORef]:A,
456 -- then the semantic module is base:Data.IORef)
457 --
458 -- Which one should you use?
459 --
460 -- - In the desugarer and later phases of compilation,
461 -- identity and semantic modules coincide, since we never compile
462 -- signatures (we just generate blank object files for
463 -- hsig files.)
464 --
465 -- A corrolary of this is that the following invariant holds at any point
466 -- past desugaring,
467 --
468 -- if I have a Module, this_mod, in hand representing the module
469 -- currently being compiled,
470 -- then moduleUnitId this_mod == thisPackage dflags
471 --
472 -- - For any code involving Names, we want semantic modules.
473 -- See lookupIfaceTop in IfaceEnv, mkIface and addFingerprints
474 -- in MkIface, and tcLookupGlobal in TcEnv
475 --
476 -- - When reading interfaces, we want the identity module to
477 -- identify the specific interface we want (such interfaces
478 -- should never be loaded into the EPS). However, if a
479 -- hole module <A> is requested, we look for A.hi
480 -- in the home library we are compiling. (See LoadIface.)
481 -- Similarly, in RnNames we check for self-imports using
482 -- identity modules, to allow signatures to import their implementor.
483 --
484 -- - For recompilation avoidance, you want the identity module,
485 -- since that will actually say the specific interface you
486 -- want to track (and recompile if it changes)
487
488 -- | 'TcGblEnv' describes the top-level of the module at the
489 -- point at which the typechecker is finished work.
490 -- It is this structure that is handed on to the desugarer
491 -- For state that needs to be updated during the typechecking
492 -- phase and returned at end, use a 'TcRef' (= 'IORef').
493 data TcGblEnv
494 = TcGblEnv {
495 tcg_mod :: Module, -- ^ Module being compiled
496 tcg_semantic_mod :: Module, -- ^ If a signature, the backing module
497 -- See also Note [Identity versus semantic module]
498 tcg_src :: HscSource,
499 -- ^ What kind of module (regular Haskell, hs-boot, hsig)
500
501 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
502 tcg_default :: Maybe [Type],
503 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
504
505 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
506 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
507 -- See Note [The interactive package] in HscTypes
508
509 tcg_type_env :: TypeEnv,
510 -- ^ Global type env for the module we are compiling now. All
511 -- TyCons and Classes (for this module) end up in here right away,
512 -- along with their derived constructors, selectors.
513 --
514 -- (Ids defined in this module start in the local envt, though they
515 -- move to the global envt during zonking)
516 --
517 -- NB: for what "things in this module" means, see
518 -- Note [The interactive package] in HscTypes
519
520 tcg_type_env_var :: TcRef TypeEnv,
521 -- Used only to initialise the interface-file
522 -- typechecker in initIfaceTcRn, so that it can see stuff
523 -- bound in this module when dealing with hi-boot recursions
524 -- Updated at intervals (e.g. after dealing with types and classes)
525
526 tcg_inst_env :: InstEnv,
527 -- ^ Instance envt for all /home-package/ modules;
528 -- Includes the dfuns in tcg_insts
529 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
530 tcg_ann_env :: AnnEnv, -- ^ And for annotations
531
532 -- Now a bunch of things about this module that are simply
533 -- accumulated, but never consulted until the end.
534 -- Nevertheless, it's convenient to accumulate them along
535 -- with the rest of the info from this module.
536 tcg_exports :: [AvailInfo], -- ^ What is exported
537 tcg_imports :: ImportAvails,
538 -- ^ Information about what was imported from where, including
539 -- things bound in this module. Also store Safe Haskell info
540 -- here about transitive trusted package requirements.
541 --
542 -- There are not many uses of this field, so you can grep for
543 -- all them.
544 --
545 -- The ImportAvails records information about the following
546 -- things:
547 --
548 -- 1. All of the modules you directly imported (tcRnImports)
549 -- 2. The orphans (only!) of all imported modules in a GHCi
550 -- session (runTcInteractive)
551 -- 3. The module that instantiated a signature
552 -- 4. Each of the signatures that merged in
553 --
554 -- It is used in the following ways:
555 -- - imp_orphs is used to determine what orphan modules should be
556 -- visible in the context (tcVisibleOrphanMods)
557 -- - imp_finsts is used to determine what family instances should
558 -- be visible (tcExtendLocalFamInstEnv)
559 -- - To resolve the meaning of the export list of a module
560 -- (tcRnExports)
561 -- - imp_mods is used to compute usage info (mkIfaceTc, deSugar)
562 -- - imp_trust_own_pkg is used for Safe Haskell in interfaces
563 -- (mkIfaceTc, as well as in HscMain)
564 -- - To create the Dependencies field in interface (mkDependencies)
565
566 tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
567 tcg_used_gres :: TcRef [GlobalRdrElt], -- ^ Records occurrences of imported entities
568 -- See Note [Tracking unused binding and imports]
569
570 tcg_keep :: TcRef NameSet,
571 -- ^ Locally-defined top-level names to keep alive.
572 --
573 -- "Keep alive" means give them an Exported flag, so that the
574 -- simplifier does not discard them as dead code, and so that they
575 -- are exposed in the interface file (but not to export to the
576 -- user).
577 --
578 -- Some things, like dict-fun Ids and default-method Ids are "born"
579 -- with the Exported flag on, for exactly the above reason, but some
580 -- we only discover as we go. Specifically:
581 --
582 -- * The to/from functions for generic data types
583 --
584 -- * Top-level variables appearing free in the RHS of an orphan
585 -- rule
586 --
587 -- * Top-level variables appearing free in a TH bracket
588
589 tcg_th_used :: TcRef Bool,
590 -- ^ @True@ <=> Template Haskell syntax used.
591 --
592 -- We need this so that we can generate a dependency on the
593 -- Template Haskell package, because the desugarer is going
594 -- to emit loads of references to TH symbols. The reference
595 -- is implicit rather than explicit, so we have to zap a
596 -- mutable variable.
597
598 tcg_th_splice_used :: TcRef Bool,
599 -- ^ @True@ <=> A Template Haskell splice was used.
600 --
601 -- Splices disable recompilation avoidance (see #481)
602
603 tcg_th_top_level_locs :: TcRef (Set RealSrcSpan),
604 -- ^ Locations of the top-level splices; used for providing details on
605 -- scope in error messages for out-of-scope variables
606
607 tcg_dfun_n :: TcRef OccSet,
608 -- ^ Allows us to choose unique DFun names.
609
610 tcg_merged :: [(Module, Fingerprint)],
611 -- ^ The requirements we merged with; we always have to recompile
612 -- if any of these changed.
613
614 -- The next fields accumulate the payload of the module
615 -- The binds, rules and foreign-decl fields are collected
616 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
617
618 tcg_rn_exports :: Maybe [(Located (IE GhcRn), Avails)],
619 -- Nothing <=> no explicit export list
620 -- Is always Nothing if we don't want to retain renamed
621 -- exports.
622 -- If present contains each renamed export list item
623 -- together with its exported names.
624
625 tcg_rn_imports :: [LImportDecl GhcRn],
626 -- Keep the renamed imports regardless. They are not
627 -- voluminous and are needed if you want to report unused imports
628
629 tcg_rn_decls :: Maybe (HsGroup GhcRn),
630 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
631 -- decls.
632
633 tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
634
635 tcg_th_topdecls :: TcRef [LHsDecl GhcPs],
636 -- ^ Top-level declarations from addTopDecls
637
638 tcg_th_foreign_files :: TcRef [(ForeignSrcLang, String)],
639 -- ^ Foreign files emitted from TH.
640
641 tcg_th_topnames :: TcRef NameSet,
642 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
643
644 tcg_th_modfinalizers :: TcRef [TcM ()],
645 -- ^ Template Haskell module finalizers.
646 --
647 -- They are computations in the @TcM@ monad rather than @Q@ because we
648 -- set them to use particular local environments.
649
650 tcg_th_coreplugins :: TcRef [String],
651 -- ^ Core plugins added by Template Haskell code.
652
653 tcg_th_state :: TcRef (Map TypeRep Dynamic),
654 tcg_th_remote_state :: TcRef (Maybe (ForeignRef (IORef QState))),
655 -- ^ Template Haskell state
656
657 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
658
659 -- Things defined in this module, or (in GHCi)
660 -- in the declarations for a single GHCi command.
661 -- For the latter, see Note [The interactive package] in HscTypes
662 tcg_tr_module :: Maybe Id, -- Id for $trModule :: GHC.Types.Module
663 -- for which every module has a top-level defn
664 -- except in GHCi in which case we have Nothing
665 tcg_binds :: LHsBinds GhcTc, -- Value bindings in this module
666 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
667 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
668 tcg_warns :: Warnings, -- ...Warnings and deprecations
669 tcg_anns :: [Annotation], -- ...Annotations
670 tcg_tcs :: [TyCon], -- ...TyCons and Classes
671 tcg_insts :: [ClsInst], -- ...Instances
672 tcg_fam_insts :: [FamInst], -- ...Family instances
673 tcg_rules :: [LRuleDecl GhcTc], -- ...Rules
674 tcg_fords :: [LForeignDecl GhcTc], -- ...Foreign import & exports
675 tcg_vects :: [LVectDecl GhcTc], -- ...Vectorisation declarations
676 tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
677
678 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
679 tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
680 -- prog uses hpc instrumentation.
681
682 tcg_self_boot :: SelfBootInfo, -- ^ Whether this module has a
683 -- corresponding hi-boot file
684
685 tcg_main :: Maybe Name, -- ^ The Name of the main
686 -- function, if this module is
687 -- the main module.
688
689 tcg_safeInfer :: TcRef (Bool, WarningMessages),
690 -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
691 -- See Note [Safe Haskell Overlapping Instances Implementation],
692 -- although this is used for more than just that failure case.
693
694 tcg_tc_plugins :: [TcPluginSolver],
695 -- ^ A list of user-defined plugins for the constraint solver.
696
697 tcg_top_loc :: RealSrcSpan,
698 -- ^ The RealSrcSpan this module came from
699
700 tcg_static_wc :: TcRef WantedConstraints,
701 -- ^ Wanted constraints of static forms.
702 -- See Note [Constraints in static forms].
703 tcg_complete_matches :: [CompleteMatch]
704 }
705
706 -- NB: topModIdentity, not topModSemantic!
707 -- Definition sites of orphan identities will be identity modules, not semantic
708 -- modules.
709
710 -- Note [Constraints in static forms]
711 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
712 --
713 -- When a static form produces constraints like
714 --
715 -- f :: StaticPtr (Bool -> String)
716 -- f = static show
717 --
718 -- we collect them in tcg_static_wc and resolve them at the end
719 -- of type checking. They need to be resolved separately because
720 -- we don't want to resolve them in the context of the enclosing
721 -- expression. Consider
722 --
723 -- g :: Show a => StaticPtr (a -> String)
724 -- g = static show
725 --
726 -- If the @Show a0@ constraint that the body of the static form produces was
727 -- resolved in the context of the enclosing expression, then the body of the
728 -- static form wouldn't be closed because the Show dictionary would come from
729 -- g's context instead of coming from the top level.
730
731 tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
732 tcVisibleOrphanMods tcg_env
733 = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))
734
735 instance ContainsModule TcGblEnv where
736 extractModule env = tcg_semantic_mod env
737
738 type RecFieldEnv = NameEnv [FieldLabel]
739 -- Maps a constructor name *in this module*
740 -- to the fields for that constructor.
741 -- This is used when dealing with ".." notation in record
742 -- construction and pattern matching.
743 -- The FieldEnv deals *only* with constructors defined in *this*
744 -- module. For imported modules, we get the same info from the
745 -- TypeEnv
746
747 data SelfBootInfo
748 = NoSelfBoot -- No corresponding hi-boot file
749 | SelfBoot
750 { sb_mds :: ModDetails -- There was a hi-boot file,
751 , sb_tcs :: NameSet } -- defining these TyCons,
752 -- What is sb_tcs used for? See Note [Extra dependencies from .hs-boot files]
753 -- in RnSource
754
755
756 {- Note [Tracking unused binding and imports]
757 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
758 We gather two sorts of usage information
759
760 * tcg_dus (defs/uses)
761 Records *defined* Names (local, top-level)
762 and *used* Names (local or imported)
763
764 Used (a) to report "defined but not used"
765 (see RnNames.reportUnusedNames)
766 (b) to generate version-tracking usage info in interface
767 files (see MkIface.mkUsedNames)
768 This usage info is mainly gathered by the renamer's
769 gathering of free-variables
770
771 * tcg_used_gres
772 Used only to report unused import declarations
773
774 Records each *occurrence* an *imported* (not locally-defined) entity.
775 The occurrence is recorded by keeping a GlobalRdrElt for it.
776 These is not the GRE that is in the GlobalRdrEnv; rather it
777 is recorded *after* the filtering done by pickGREs. So it reflect
778 /how that occurrence is in scope/. See Note [GRE filtering] in
779 RdrName.
780
781
782 ************************************************************************
783 * *
784 The local typechecker environment
785 * *
786 ************************************************************************
787
788 Note [The Global-Env/Local-Env story]
789 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
790 During type checking, we keep in the tcg_type_env
791 * All types and classes
792 * All Ids derived from types and classes (constructors, selectors)
793
794 At the end of type checking, we zonk the local bindings,
795 and as we do so we add to the tcg_type_env
796 * Locally defined top-level Ids
797
798 Why? Because they are now Ids not TcIds. This final GlobalEnv is
799 a) fed back (via the knot) to typechecking the
800 unfoldings of interface signatures
801 b) used in the ModDetails of this module
802 -}
803
804 data TcLclEnv -- Changes as we move inside an expression
805 -- Discarded after typecheck/rename; not passed on to desugarer
806 = TcLclEnv {
807 tcl_loc :: RealSrcSpan, -- Source span
808 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
809 tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
810
811 tcl_th_ctxt :: ThStage, -- Template Haskell context
812 tcl_th_bndrs :: ThBindEnv, -- and binder info
813 -- The ThBindEnv records the TH binding level of in-scope Names
814 -- defined in this module (not imported)
815 -- We can't put this info in the TypeEnv because it's needed
816 -- (and extended) in the renamer, for untyed splices
817
818 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
819
820 tcl_rdr :: LocalRdrEnv, -- Local name envt
821 -- Maintained during renaming, of course, but also during
822 -- type checking, solely so that when renaming a Template-Haskell
823 -- splice we have the right environment for the renamer.
824 --
825 -- Does *not* include global name envt; may shadow it
826 -- Includes both ordinary variables and type variables;
827 -- they are kept distinct because tyvar have a different
828 -- occurrence constructor (Name.TvOcc)
829 -- We still need the unsullied global name env so that
830 -- we can look up record field names
831
832 tcl_env :: TcTypeEnv, -- The local type environment:
833 -- Ids and TyVars defined in this module
834
835 tcl_bndrs :: TcBinderStack, -- Used for reporting relevant bindings,
836 -- and for tidying types
837
838 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
839 -- Namely, the in-scope TyVars bound in tcl_env,
840 -- plus the tyvars mentioned in the types of Ids bound
841 -- in tcl_lenv.
842 -- Why mutable? see notes with tcGetGlobalTyCoVars
843
844 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
845 tcl_errs :: TcRef Messages -- Place to accumulate errors
846 }
847
848 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
849 -- Monadic so that we have a chance
850 -- to deal with bound type variables just before error
851 -- message construction
852
853 -- Bool: True <=> this is a landmark context; do not
854 -- discard it when trimming for display
855
856 type TcTypeEnv = NameEnv TcTyThing
857
858 type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
859 -- Domain = all Ids bound in this module (ie not imported)
860 -- The TopLevelFlag tells if the binding is syntactically top level.
861 -- We need to know this, because the cross-stage persistence story allows
862 -- cross-stage at arbitrary types if the Id is bound at top level.
863 --
864 -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
865 -- bound at top level! See Note [Template Haskell levels] in TcSplice
866
867 {- Note [Given Insts]
868 ~~~~~~~~~~~~~~~~~~
869 Because of GADTs, we have to pass inwards the Insts provided by type signatures
870 and existential contexts. Consider
871 data T a where { T1 :: b -> b -> T [b] }
872 f :: Eq a => T a -> Bool
873 f (T1 x y) = [x]==[y]
874
875 The constructor T1 binds an existential variable 'b', and we need Eq [b].
876 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
877 pass it inwards.
878
879 -}
880
881 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
882 -- bits of data in 'TcGblEnv' which are updated during typechecking and
883 -- returned at the end.
884 type TcRef a = IORef a
885 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
886 type TcId = Id
887 type TcIdSet = IdSet
888
889 ---------------------------
890 -- The TcBinderStack
891 ---------------------------
892
893 type TcBinderStack = [TcBinder]
894 -- This is a stack of locally-bound ids and tyvars,
895 -- innermost on top
896 -- Used only in error reporting (relevantBindings in TcError),
897 -- and in tidying
898 -- We can't use the tcl_env type environment, because it doesn't
899 -- keep track of the nesting order
900
901 data TcBinder
902 = TcIdBndr
903 TcId
904 TopLevelFlag -- Tells whether the binding is syntactically top-level
905 -- (The monomorphic Ids for a recursive group count
906 -- as not-top-level for this purpose.)
907
908 | TcIdBndr_ExpType -- Variant that allows the type to be specified as
909 -- an ExpType
910 Name
911 ExpType
912 TopLevelFlag
913
914 | TcTvBndr -- e.g. case x of P (y::a) -> blah
915 Name -- We bind the lexical name "a" to the type of y,
916 TyVar -- which might be an utterly different (perhaps
917 -- existential) tyvar
918
919 instance Outputable TcBinder where
920 ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl)
921 ppr (TcIdBndr_ExpType id _ top_lvl) = ppr id <> brackets (ppr top_lvl)
922 ppr (TcTvBndr name tv) = ppr name <+> ppr tv
923
924 instance HasOccName TcBinder where
925 occName (TcIdBndr id _) = occName (idName id)
926 occName (TcIdBndr_ExpType name _ _) = occName name
927 occName (TcTvBndr name _) = occName name
928
929 ---------------------------
930 -- Template Haskell stages and levels
931 ---------------------------
932
933 data SpliceType = Typed | Untyped
934
935 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
936 = Splice SpliceType -- Inside a top-level splice
937 -- This code will be run *at compile time*;
938 -- the result replaces the splice
939 -- Binding level = 0
940
941 | RunSplice (TcRef [ForeignRef (TH.Q ())])
942 -- Set when running a splice, i.e. NOT when renaming or typechecking the
943 -- Haskell code for the splice. See Note [RunSplice ThLevel].
944 --
945 -- Contains a list of mod finalizers collected while executing the splice.
946 --
947 -- 'addModFinalizer' inserts finalizers here, and from here they are taken
948 -- to construct an @HsSpliced@ annotation for untyped splices. See Note
949 -- [Delaying modFinalizers in untyped splices] in "RnSplice".
950 --
951 -- For typed splices, the typechecker takes finalizers from here and
952 -- inserts them in the list of finalizers in the global environment.
953 --
954 -- See Note [Collecting modFinalizers in typed splices] in "TcSplice".
955
956 | Comp -- Ordinary Haskell code
957 -- Binding level = 1
958
959 | Brack -- Inside brackets
960 ThStage -- Enclosing stage
961 PendingStuff
962
963 data PendingStuff
964 = RnPendingUntyped -- Renaming the inside of an *untyped* bracket
965 (TcRef [PendingRnSplice]) -- Pending splices in here
966
967 | RnPendingTyped -- Renaming the inside of a *typed* bracket
968
969 | TcPending -- Typechecking the inside of a typed bracket
970 (TcRef [PendingTcSplice]) -- Accumulate pending splices here
971 (TcRef WantedConstraints) -- and type constraints here
972
973 topStage, topAnnStage, topSpliceStage :: ThStage
974 topStage = Comp
975 topAnnStage = Splice Untyped
976 topSpliceStage = Splice Untyped
977
978 instance Outputable ThStage where
979 ppr (Splice _) = text "Splice"
980 ppr (RunSplice _) = text "RunSplice"
981 ppr Comp = text "Comp"
982 ppr (Brack s _) = text "Brack" <> parens (ppr s)
983
984 type ThLevel = Int
985 -- NB: see Note [Template Haskell levels] in TcSplice
986 -- Incremented when going inside a bracket,
987 -- decremented when going inside a splice
988 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
989 -- original "Template meta-programming for Haskell" paper
990
991 impLevel, outerLevel :: ThLevel
992 impLevel = 0 -- Imported things; they can be used inside a top level splice
993 outerLevel = 1 -- Things defined outside brackets
994
995 thLevel :: ThStage -> ThLevel
996 thLevel (Splice _) = 0
997 thLevel (RunSplice _) =
998 -- See Note [RunSplice ThLevel].
999 panic "thLevel: called when running a splice"
1000 thLevel Comp = 1
1001 thLevel (Brack s _) = thLevel s + 1
1002
1003 {- Node [RunSplice ThLevel]
1004 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1005 The 'RunSplice' stage is set when executing a splice, and only when running a
1006 splice. In particular it is not set when the splice is renamed or typechecked.
1007
1008 'RunSplice' is needed to provide a reference where 'addModFinalizer' can insert
1009 the finalizer (see Note [Delaying modFinalizers in untyped splices]), and
1010 'addModFinalizer' runs when doing Q things. Therefore, It doesn't make sense to
1011 set 'RunSplice' when renaming or typechecking the splice, where 'Splice', 'Brak'
1012 or 'Comp' are used instead.
1013
1014 -}
1015
1016 ---------------------------
1017 -- Arrow-notation context
1018 ---------------------------
1019
1020 {- Note [Escaping the arrow scope]
1021 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1022 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
1023 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
1024 For example
1025
1026 proc x -> (e1 -< e2)
1027
1028 Here, x is not in scope in e1, but it is in scope in e2. This can get
1029 a bit complicated:
1030
1031 let x = 3 in
1032 proc y -> (proc z -> e1) -< e2
1033
1034 Here, x and z are in scope in e1, but y is not.
1035
1036 We implement this by
1037 recording the environment when passing a proc (using newArrowScope),
1038 and returning to that (using escapeArrowScope) on the left of -< and the
1039 head of (|..|).
1040
1041 All this can be dealt with by the *renamer*. But the type checker needs
1042 to be involved too. Example (arrowfail001)
1043 class Foo a where foo :: a -> ()
1044 data Bar = forall a. Foo a => Bar a
1045 get :: Bar -> ()
1046 get = proc x -> case x of Bar a -> foo -< a
1047 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
1048 be captured by the pattern match on 'Bar'. Rather it should join the
1049 constraints from further out. So we must capture the constraint bag
1050 from further out in the ArrowCtxt that we push inwards.
1051 -}
1052
1053 data ArrowCtxt -- Note [Escaping the arrow scope]
1054 = NoArrowCtxt
1055 | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
1056
1057
1058 ---------------------------
1059 -- TcTyThing
1060 ---------------------------
1061
1062 -- | A typecheckable thing available in a local context. Could be
1063 -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
1064 -- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
1065 data TcTyThing
1066 = AGlobal TyThing -- Used only in the return type of a lookup
1067
1068 | ATcId -- Ids defined in this module; may not be fully zonked
1069 { tct_id :: TcId
1070 , tct_info :: IdBindingInfo -- See Note [Meaning of IdBindingInfo]
1071 }
1072
1073 | ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
1074 -- variable is bound. We only need the Name
1075 -- for error-message purposes; it is the corresponding
1076 -- Name in the domain of the envt
1077
1078 | ATcTyCon TyCon -- Used temporarily, during kind checking, for the
1079 -- tycons and clases in this recursive group
1080 -- The TyCon is always a TcTyCon. Its kind
1081 -- can be a mono-kind or a poly-kind; in TcTyClsDcls see
1082 -- Note [Type checking recursive type and class declarations]
1083
1084 | APromotionErr PromotionErr
1085
1086 data PromotionErr
1087 = TyConPE -- TyCon used in a kind before we are ready
1088 -- data T :: T -> * where ...
1089 | ClassPE -- Ditto Class
1090
1091 | FamDataConPE -- Data constructor for a data family
1092 -- See Note [AFamDataCon: not promoting data family constructors]
1093 -- in TcEnv.
1094 | PatSynPE -- Pattern synonyms
1095 -- See Note [Don't promote pattern synonyms] in TcEnv
1096
1097 | PatSynExPE -- Pattern synonym existential type variable
1098 -- See Note [Pattern synonym existentials do not scope] in TcPatSyn
1099
1100 | RecDataConPE -- Data constructor in a recursive loop
1101 -- See Note [Recursion and promoting data constructors] in TcTyClsDecls
1102 | NoDataKindsTC -- -XDataKinds not enabled (for a tycon)
1103 | NoDataKindsDC -- -XDataKinds not enabled (for a datacon)
1104 | NoTypeInTypeTC -- -XTypeInType not enabled (for a tycon)
1105 | NoTypeInTypeDC -- -XTypeInType not enabled (for a datacon)
1106
1107 instance Outputable TcTyThing where -- Debugging only
1108 ppr (AGlobal g) = ppr g
1109 ppr elt@(ATcId {}) = text "Identifier" <>
1110 brackets (ppr (tct_id elt) <> dcolon
1111 <> ppr (varType (tct_id elt)) <> comma
1112 <+> ppr (tct_info elt))
1113 ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
1114 <+> dcolon <+> ppr (varType tv)
1115 ppr (ATcTyCon tc) = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc)
1116 ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
1117
1118 -- | IdBindingInfo describes how an Id is bound.
1119 --
1120 -- It is used for the following purposes:
1121 -- a) for static forms in TcExpr.checkClosedInStaticForm and
1122 -- b) to figure out when a nested binding can be generalised,
1123 -- in TcBinds.decideGeneralisationPlan.
1124 --
1125 data IdBindingInfo -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1126 = NotLetBound
1127 | ClosedLet
1128 | NonClosedLet
1129 RhsNames -- Used for (static e) checks only
1130 ClosedTypeId -- Used for generalisation checks
1131 -- and for (static e) checks
1132
1133 -- | IsGroupClosed describes a group of mutually-recursive bindings
1134 data IsGroupClosed
1135 = IsGroupClosed
1136 (NameEnv RhsNames) -- Free var info for the RHS of each binding in the goup
1137 -- Used only for (static e) checks
1138
1139 ClosedTypeId -- True <=> all the free vars of the group are
1140 -- imported or ClosedLet or
1141 -- NonClosedLet with ClosedTypeId=True.
1142 -- In particular, no tyvars, no NotLetBound
1143
1144 type RhsNames = NameSet -- Names of variables, mentioned on the RHS of
1145 -- a definition, that are not Global or ClosedLet
1146
1147 type ClosedTypeId = Bool
1148 -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1149
1150 {- Note [Meaning of IdBindingInfo]
1151 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1152 NotLetBound means that
1153 the Id is not let-bound (e.g. it is bound in a
1154 lambda-abstraction or in a case pattern)
1155
1156 ClosedLet means that
1157 - The Id is let-bound,
1158 - Any free term variables are also Global or ClosedLet
1159 - Its type has no free variables (NB: a top-level binding subject
1160 to the MR might have free vars in its type)
1161 These ClosedLets can definitely be floated to top level; and we
1162 may need to do so for static forms.
1163
1164 Property: ClosedLet
1165 is equivalent to
1166 NonClosedLet emptyNameSet True
1167
1168 (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that
1169 - The Id is let-bound
1170
1171 - The fvs::RhsNames contains the free names of the RHS,
1172 excluding Global and ClosedLet ones.
1173
1174 - For the ClosedTypeId field see Note [Bindings with closed types]
1175
1176 For (static e) to be valid, we need for every 'x' free in 'e',
1177 that x's binding is floatable to the top level. Specifically:
1178 * x's RhsNames must be empty
1179 * x's type has no free variables
1180 See Note [Grand plan for static forms] in StaticPtrTable.hs.
1181 This test is made in TcExpr.checkClosedInStaticForm.
1182 Actually knowing x's RhsNames (rather than just its emptiness
1183 or otherwise) is just so we can produce better error messages
1184
1185 Note [Bindings with closed types: ClosedTypeId]
1186 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1187 Consider
1188
1189 f x = let g ys = map not ys
1190 in ...
1191
1192 Can we generalise 'g' under the OutsideIn algorithm? Yes,
1193 because all g's free variables are top-level; that is they themselves
1194 have no free type variables, and it is the type variables in the
1195 environment that makes things tricky for OutsideIn generalisation.
1196
1197 Here's the invariant:
1198 If an Id has ClosedTypeId=True (in its IdBindingInfo), then
1199 the Id's type is /definitely/ closed (has no free type variables).
1200 Specifically,
1201 a) The Id's acutal type is closed (has no free tyvars)
1202 b) Either the Id has a (closed) user-supplied type signature
1203 or all its free variables are Global/ClosedLet
1204 or NonClosedLet with ClosedTypeId=True.
1205 In particular, none are NotLetBound.
1206
1207 Why is (b) needed? Consider
1208 \x. (x :: Int, let y = x+1 in ...)
1209 Initially x::alpha. If we happen to typecheck the 'let' before the
1210 (x::Int), y's type will have a free tyvar; but if the other way round
1211 it won't. So we treat any let-bound variable with a free
1212 non-let-bound variable as not ClosedTypeId, regardless of what the
1213 free vars of its type actually are.
1214
1215 But if it has a signature, all is well:
1216 \x. ...(let { y::Int; y = x+1 } in
1217 let { v = y+2 } in ...)...
1218 Here the signature on 'v' makes 'y' a ClosedTypeId, so we can
1219 generalise 'v'.
1220
1221 Note that:
1222
1223 * A top-level binding may not have ClosedTypeId=True, if it suffers
1224 from the MR
1225
1226 * A nested binding may be closed (eg 'g' in the example we started
1227 with). Indeed, that's the point; whether a function is defined at
1228 top level or nested is orthogonal to the question of whether or
1229 not it is closed.
1230
1231 * A binding may be non-closed because it mentions a lexically scoped
1232 *type variable* Eg
1233 f :: forall a. blah
1234 f x = let g y = ...(y::a)...
1235
1236 Under OutsideIn we are free to generalise an Id all of whose free
1237 variables have ClosedTypeId=True (or imported). This is an extension
1238 compared to the JFP paper on OutsideIn, which used "top-level" as a
1239 proxy for "closed". (It's not a good proxy anyway -- the MR can make
1240 a top-level binding with a free type variable.)
1241 -}
1242
1243 instance Outputable IdBindingInfo where
1244 ppr NotLetBound = text "NotLetBound"
1245 ppr ClosedLet = text "TopLevelLet"
1246 ppr (NonClosedLet fvs closed_type) =
1247 text "TopLevelLet" <+> ppr fvs <+> ppr closed_type
1248
1249 instance Outputable PromotionErr where
1250 ppr ClassPE = text "ClassPE"
1251 ppr TyConPE = text "TyConPE"
1252 ppr PatSynPE = text "PatSynPE"
1253 ppr PatSynExPE = text "PatSynExPE"
1254 ppr FamDataConPE = text "FamDataConPE"
1255 ppr RecDataConPE = text "RecDataConPE"
1256 ppr NoDataKindsTC = text "NoDataKindsTC"
1257 ppr NoDataKindsDC = text "NoDataKindsDC"
1258 ppr NoTypeInTypeTC = text "NoTypeInTypeTC"
1259 ppr NoTypeInTypeDC = text "NoTypeInTypeDC"
1260
1261 pprTcTyThingCategory :: TcTyThing -> SDoc
1262 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
1263 pprTcTyThingCategory (ATyVar {}) = text "Type variable"
1264 pprTcTyThingCategory (ATcId {}) = text "Local identifier"
1265 pprTcTyThingCategory (ATcTyCon {}) = text "Local tycon"
1266 pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
1267
1268 pprPECategory :: PromotionErr -> SDoc
1269 pprPECategory ClassPE = text "Class"
1270 pprPECategory TyConPE = text "Type constructor"
1271 pprPECategory PatSynPE = text "Pattern synonym"
1272 pprPECategory PatSynExPE = text "Pattern synonym existential"
1273 pprPECategory FamDataConPE = text "Data constructor"
1274 pprPECategory RecDataConPE = text "Data constructor"
1275 pprPECategory NoDataKindsTC = text "Type constructor"
1276 pprPECategory NoDataKindsDC = text "Data constructor"
1277 pprPECategory NoTypeInTypeTC = text "Type constructor"
1278 pprPECategory NoTypeInTypeDC = text "Data constructor"
1279
1280 {-
1281 ************************************************************************
1282 * *
1283 Operations over ImportAvails
1284 * *
1285 ************************************************************************
1286 -}
1287
1288 -- | 'ImportAvails' summarises what was imported from where, irrespective of
1289 -- whether the imported things are actually used or not. It is used:
1290 --
1291 -- * when processing the export list,
1292 --
1293 -- * when constructing usage info for the interface file,
1294 --
1295 -- * to identify the list of directly imported modules for initialisation
1296 -- purposes and for optimised overlap checking of family instances,
1297 --
1298 -- * when figuring out what things are really unused
1299 --
1300 data ImportAvails
1301 = ImportAvails {
1302 imp_mods :: ImportedMods,
1303 -- = ModuleEnv [ImportedModsVal],
1304 -- ^ Domain is all directly-imported modules
1305 --
1306 -- See the documentation on ImportedModsVal in HscTypes for the
1307 -- meaning of the fields.
1308 --
1309 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
1310 -- because we might be importing modules of the same name from
1311 -- different packages. (currently not the case, but might be in the
1312 -- future).
1313
1314 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
1315 -- ^ Home-package modules needed by the module being compiled
1316 --
1317 -- It doesn't matter whether any of these dependencies
1318 -- are actually /used/ when compiling the module; they
1319 -- are listed if they are below it at all. For
1320 -- example, suppose M imports A which imports X. Then
1321 -- compiling M might not need to consult X.hi, but X
1322 -- is still listed in M's dependencies.
1323
1324 imp_dep_pkgs :: Set InstalledUnitId,
1325 -- ^ Packages needed by the module being compiled, whether directly,
1326 -- or via other modules in this package, or via modules imported
1327 -- from other packages.
1328
1329 imp_trust_pkgs :: Set InstalledUnitId,
1330 -- ^ This is strictly a subset of imp_dep_pkgs and records the
1331 -- packages the current module needs to trust for Safe Haskell
1332 -- compilation to succeed. A package is required to be trusted if
1333 -- we are dependent on a trustworthy module in that package.
1334 -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1335 -- where True for the bool indicates the package is required to be
1336 -- trusted is the more logical design, doing so complicates a lot
1337 -- of code not concerned with Safe Haskell.
1338 -- See Note [RnNames . Tracking Trust Transitively]
1339
1340 imp_trust_own_pkg :: Bool,
1341 -- ^ Do we require that our own package is trusted?
1342 -- This is to handle efficiently the case where a Safe module imports
1343 -- a Trustworthy module that resides in the same package as it.
1344 -- See Note [RnNames . Trust Own Package]
1345
1346 imp_orphs :: [Module],
1347 -- ^ Orphan modules below us in the import tree (and maybe including
1348 -- us for imported modules)
1349
1350 imp_finsts :: [Module]
1351 -- ^ Family instance modules below us in the import tree (and maybe
1352 -- including us for imported modules)
1353 }
1354
1355 mkModDeps :: [(ModuleName, IsBootInterface)]
1356 -> ModuleNameEnv (ModuleName, IsBootInterface)
1357 mkModDeps deps = foldl add emptyUFM deps
1358 where
1359 add env elt@(m,_) = addToUFM env m elt
1360
1361 modDepsElts
1362 :: ModuleNameEnv (ModuleName, IsBootInterface)
1363 -> [(ModuleName, IsBootInterface)]
1364 modDepsElts = sort . nonDetEltsUFM
1365 -- It's OK to use nonDetEltsUFM here because sorting by module names
1366 -- restores determinism
1367
1368 emptyImportAvails :: ImportAvails
1369 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
1370 imp_dep_mods = emptyUFM,
1371 imp_dep_pkgs = S.empty,
1372 imp_trust_pkgs = S.empty,
1373 imp_trust_own_pkg = False,
1374 imp_orphs = [],
1375 imp_finsts = [] }
1376
1377 -- | Union two ImportAvails
1378 --
1379 -- This function is a key part of Import handling, basically
1380 -- for each import we create a separate ImportAvails structure
1381 -- and then union them all together with this function.
1382 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
1383 plusImportAvails
1384 (ImportAvails { imp_mods = mods1,
1385 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
1386 imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1387 imp_orphs = orphs1, imp_finsts = finsts1 })
1388 (ImportAvails { imp_mods = mods2,
1389 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
1390 imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1391 imp_orphs = orphs2, imp_finsts = finsts2 })
1392 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
1393 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
1394 imp_dep_pkgs = dpkgs1 `S.union` dpkgs2,
1395 imp_trust_pkgs = tpkgs1 `S.union` tpkgs2,
1396 imp_trust_own_pkg = tself1 || tself2,
1397 imp_orphs = orphs1 `unionLists` orphs2,
1398 imp_finsts = finsts1 `unionLists` finsts2 }
1399 where
1400 plus_mod_dep r1@(m1, boot1) r2@(m2, boot2)
1401 | ASSERT2( m1 == m2, (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
1402 boot1 = r2
1403 | otherwise = r1
1404 -- If either side can "see" a non-hi-boot interface, use that
1405 -- Reusing existing tuples saves 10% of allocations on test
1406 -- perf/compiler/MultiLayerModules
1407
1408 {-
1409 ************************************************************************
1410 * *
1411 \subsection{Where from}
1412 * *
1413 ************************************************************************
1414
1415 The @WhereFrom@ type controls where the renamer looks for an interface file
1416 -}
1417
1418 data WhereFrom
1419 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
1420 | ImportBySystem -- Non user import.
1421 | ImportByPlugin -- Importing a plugin;
1422 -- See Note [Care with plugin imports] in LoadIface
1423
1424 instance Outputable WhereFrom where
1425 ppr (ImportByUser is_boot) | is_boot = text "{- SOURCE -}"
1426 | otherwise = empty
1427 ppr ImportBySystem = text "{- SYSTEM -}"
1428 ppr ImportByPlugin = text "{- PLUGIN -}"
1429
1430
1431 {- *********************************************************************
1432 * *
1433 Type signatures
1434 * *
1435 ********************************************************************* -}
1436
1437 -- These data types need to be here only because
1438 -- TcSimplify uses them, and TcSimplify is fairly
1439 -- low down in the module hierarchy
1440
1441 type TcSigFun = Name -> Maybe TcSigInfo
1442
1443 data TcSigInfo = TcIdSig TcIdSigInfo
1444 | TcPatSynSig TcPatSynInfo
1445
1446 data TcIdSigInfo -- See Note [Complete and partial type signatures]
1447 = CompleteSig -- A complete signature with no wildcards,
1448 -- so the complete polymorphic type is known.
1449 { sig_bndr :: TcId -- The polymorphic Id with that type
1450
1451 , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods,
1452 -- the Name in the FunSigCtxt is not the same
1453 -- as the TcId; the former is 'op', while the
1454 -- latter is '$dmop' or some such
1455
1456 , sig_loc :: SrcSpan -- Location of the type signature
1457 }
1458
1459 | PartialSig -- A partial type signature (i.e. includes one or more
1460 -- wildcards). In this case it doesn't make sense to give
1461 -- the polymorphic Id, because we are going to /infer/ its
1462 -- type, so we can't make the polymorphic Id ab-initio
1463 { psig_name :: Name -- Name of the function; used when report wildcards
1464 , psig_hs_ty :: LHsSigWcType GhcRn -- The original partial signature in
1465 -- HsSyn form
1466 , sig_ctxt :: UserTypeCtxt
1467 , sig_loc :: SrcSpan -- Location of the type signature
1468 }
1469
1470
1471 {- Note [Complete and partial type signatures]
1472 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1473 A type signature is partial when it contains one or more wildcards
1474 (= type holes). The wildcard can either be:
1475 * A (type) wildcard occurring in sig_theta or sig_tau. These are
1476 stored in sig_wcs.
1477 f :: Bool -> _
1478 g :: Eq _a => _a -> _a -> Bool
1479 * Or an extra-constraints wildcard, stored in sig_cts:
1480 h :: (Num a, _) => a -> a
1481
1482 A type signature is a complete type signature when there are no
1483 wildcards in the type signature, i.e. iff sig_wcs is empty and
1484 sig_extra_cts is Nothing.
1485 -}
1486
1487 data TcIdSigInst
1488 = TISI { sig_inst_sig :: TcIdSigInfo
1489
1490 , sig_inst_skols :: [(Name, TcTyVar)]
1491 -- Instantiated type and kind variables, SigTvs
1492 -- The Name is the Name that the renamer chose;
1493 -- but the TcTyVar may come from instantiating
1494 -- the type and hence have a different unique.
1495 -- No need to keep track of whether they are truly lexically
1496 -- scoped because the renamer has named them uniquely
1497 -- See Note [Binding scoped type variables] in TcSigs
1498
1499 , sig_inst_theta :: TcThetaType
1500 -- Instantiated theta. In the case of a
1501 -- PartialSig, sig_theta does not include
1502 -- the extra-constraints wildcard
1503
1504 , sig_inst_tau :: TcSigmaType -- Instantiated tau
1505 -- See Note [sig_inst_tau may be polymorphic]
1506
1507 -- Relevant for partial signature only
1508 , sig_inst_wcs :: [(Name, TcTyVar)]
1509 -- Like sig_inst_skols, but for wildcards. The named
1510 -- wildcards scope over the binding, and hence their
1511 -- Names may appear in type signatures in the binding
1512
1513 , sig_inst_wcx :: Maybe TcTyVar
1514 -- Extra-constraints wildcard to fill in, if any
1515 }
1516
1517 {- Note [sig_inst_tau may be polymorphic]
1518 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1519 Note that "sig_inst_tau" might actually be a polymorphic type,
1520 if the original function had a signature like
1521 forall a. Eq a => forall b. Ord b => ....
1522 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
1523 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
1524
1525 Note [Wildcards in partial signatures]
1526 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1527 The wildcards in psig_wcs may stand for a type mentioning
1528 the universally-quantified tyvars of psig_ty
1529
1530 E.g. f :: forall a. _ -> a
1531 f x = x
1532 We get sig_inst_skols = [a]
1533 sig_inst_tau = _22 -> a
1534 sig_inst_wcs = [_22]
1535 and _22 in the end is unified with the type 'a'
1536
1537 Moreover the kind of a wildcard in sig_inst_wcs may mention
1538 the universally-quantified tyvars sig_inst_skols
1539 e.g. f :: t a -> t _
1540 Here we get
1541 sig_inst_skols = [k:*, (t::k ->*), (a::k)]
1542 sig_inst_tau = t a -> t _22
1543 sig_inst_wcs = [ _22::k ]
1544 -}
1545
1546 data TcPatSynInfo
1547 = TPSI {
1548 patsig_name :: Name,
1549 patsig_implicit_bndrs :: [TyVarBinder], -- Implicitly-bound kind vars (Inferred) and
1550 -- implicitly-bound type vars (Specified)
1551 -- See Note [The pattern-synonym signature splitting rule] in TcPatSyn
1552 patsig_univ_bndrs :: [TyVar], -- Bound by explicit user forall
1553 patsig_req :: TcThetaType,
1554 patsig_ex_bndrs :: [TyVar], -- Bound by explicit user forall
1555 patsig_prov :: TcThetaType,
1556 patsig_body_ty :: TcSigmaType
1557 }
1558
1559 instance Outputable TcSigInfo where
1560 ppr (TcIdSig idsi) = ppr idsi
1561 ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi
1562
1563 instance Outputable TcIdSigInfo where
1564 ppr (CompleteSig { sig_bndr = bndr })
1565 = ppr bndr <+> dcolon <+> ppr (idType bndr)
1566 ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty })
1567 = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty
1568
1569 instance Outputable TcIdSigInst where
1570 ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols
1571 , sig_inst_theta = theta, sig_inst_tau = tau })
1572 = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ])
1573
1574 instance Outputable TcPatSynInfo where
1575 ppr (TPSI{ patsig_name = name}) = ppr name
1576
1577 isPartialSig :: TcIdSigInst -> Bool
1578 isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True
1579 isPartialSig _ = False
1580
1581 -- | No signature or a partial signature
1582 hasCompleteSig :: TcSigFun -> Name -> Bool
1583 hasCompleteSig sig_fn name
1584 = case sig_fn name of
1585 Just (TcIdSig (CompleteSig {})) -> True
1586 _ -> False
1587
1588
1589 {-
1590 ************************************************************************
1591 * *
1592 * Canonical constraints *
1593 * *
1594 * These are the constraints the low-level simplifier works with *
1595 * *
1596 ************************************************************************
1597 -}
1598
1599 -- The syntax of xi (ΞΎ) types:
1600 -- xi ::= a | T xis | xis -> xis | ... | forall a. tau
1601 -- Two important notes:
1602 -- (i) No type families, unless we are under a ForAll
1603 -- (ii) Note that xi types can contain unexpanded type synonyms;
1604 -- however, the (transitive) expansions of those type synonyms
1605 -- will not contain any type functions, unless we are under a ForAll.
1606 -- We enforce the structure of Xi types when we flatten (TcCanonical)
1607
1608 type Xi = Type -- In many comments, "xi" ranges over Xi
1609
1610 type Cts = Bag Ct
1611
1612 data Ct
1613 -- Atomic canonical constraints
1614 = CDictCan { -- e.g. Num xi
1615 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1616
1617 cc_class :: Class,
1618 cc_tyargs :: [Xi], -- cc_tyargs are function-free, hence Xi
1619
1620 cc_pend_sc :: Bool -- See Note [The superclass story] in TcCanonical
1621 -- True <=> (a) cc_class has superclasses
1622 -- (b) we have not (yet) added those
1623 -- superclasses as Givens
1624 }
1625
1626 | CIrredCan { -- These stand for yet-unusable predicates
1627 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1628 cc_insol :: Bool -- True <=> definitely an error, can never be solved
1629 -- False <=> might be soluble
1630
1631 -- For the might-be-soluble case, the ctev_pred of the evidence is
1632 -- of form (tv xi1 xi2 ... xin) with a tyvar at the head
1633 -- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
1634 -- or (F tys ~ ty) where the CFunEqCan kind invariant fails
1635 -- See Note [CIrredCan constraints]
1636
1637 -- The definitely-insoluble case is for things like
1638 -- Int ~ Bool tycons don't match
1639 -- a ~ [a] occurs check
1640 }
1641
1642 | CTyEqCan { -- tv ~ rhs
1643 -- Invariants:
1644 -- * See Note [Applying the inert substitution] in TcFlatten
1645 -- * tv not in tvs(rhs) (occurs check)
1646 -- * If tv is a TauTv, then rhs has no foralls
1647 -- (this avoids substituting a forall for the tyvar in other types)
1648 -- * typeKind ty `tcEqKind` typeKind tv; Note [Ct kind invariant]
1649 -- * rhs may have at most one top-level cast
1650 -- * rhs (perhaps under the one cast) is not necessarily function-free,
1651 -- but it has no top-level function.
1652 -- E.g. a ~ [F b] is fine
1653 -- but a ~ F b is not
1654 -- * If the equality is representational, rhs has no top-level newtype
1655 -- See Note [No top-level newtypes on RHS of representational
1656 -- equalities] in TcCanonical
1657 -- * If rhs (perhaps under the cast) is also a tv, then it is oriented
1658 -- to give best chance of
1659 -- unification happening; eg if rhs is touchable then lhs is too
1660 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1661 cc_tyvar :: TcTyVar,
1662 cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
1663 -- See invariants above
1664
1665 cc_eq_rel :: EqRel -- INVARIANT: cc_eq_rel = ctEvEqRel cc_ev
1666 }
1667
1668 | CFunEqCan { -- F xis ~ fsk
1669 -- Invariants:
1670 -- * isTypeFamilyTyCon cc_fun
1671 -- * typeKind (F xis) = tyVarKind fsk; Note [Ct kind invariant]
1672 -- * always Nominal role
1673 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1674 cc_fun :: TyCon, -- A type function
1675
1676 cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
1677 -- Either under-saturated or exactly saturated
1678 -- *never* over-saturated (because if so
1679 -- we should have decomposed)
1680
1681 cc_fsk :: TcTyVar -- [Given] always a FlatSkolTv
1682 -- [Wanted] always a FlatMetaTv
1683 -- See Note [The flattening story] in TcFlatten
1684 }
1685
1686 | CNonCanonical { -- See Note [NonCanonical Semantics] in TcSMonad
1687 cc_ev :: CtEvidence
1688 }
1689
1690 | CHoleCan { -- See Note [Hole constraints]
1691 -- Treated as an "insoluble" constraint
1692 -- See Note [Insoluble constraints]
1693 cc_ev :: CtEvidence,
1694 cc_hole :: Hole
1695 }
1696
1697 -- | An expression or type hole
1698 data Hole = ExprHole UnboundVar
1699 -- ^ Either an out-of-scope variable or a "true" hole in an
1700 -- expression (TypedHoles)
1701 | TypeHole OccName
1702 -- ^ A hole in a type (PartialTypeSignatures)
1703
1704 instance Outputable Hole where
1705 ppr (ExprHole ub) = ppr ub
1706 ppr (TypeHole occ) = text "TypeHole" <> parens (ppr occ)
1707
1708 holeOcc :: Hole -> OccName
1709 holeOcc (ExprHole uv) = unboundVarOcc uv
1710 holeOcc (TypeHole occ) = occ
1711
1712 {- Note [Hole constraints]
1713 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1714 CHoleCan constraints are used for two kinds of holes,
1715 distinguished by cc_hole:
1716
1717 * For holes in expressions (including variables not in scope)
1718 e.g. f x = g _ x
1719
1720 * For holes in type signatures
1721 e.g. f :: _ -> _
1722 f x = [x,True]
1723
1724 Note [CIrredCan constraints]
1725 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1726 CIrredCan constraints are used for constraints that are "stuck"
1727 - we can't solve them (yet)
1728 - we can't use them to solve other constraints
1729 - but they may become soluble if we substitute for some
1730 of the type variables in the constraint
1731
1732 Example 1: (c Int), where c :: * -> Constraint. We can't do anything
1733 with this yet, but if later c := Num, *then* we can solve it
1734
1735 Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
1736 We don't want to use this to substitute 'b' for 'a', in case
1737 'k' is subequently unifed with (say) *->*, because then
1738 we'd have ill-kinded types floating about. Rather we want
1739 to defer using the equality altogether until 'k' get resolved.
1740
1741 Note [Ct/evidence invariant]
1742 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1743 If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
1744 of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
1745 ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
1746 This holds by construction; look at the unique place where CDictCan is
1747 built (in TcCanonical).
1748
1749 In contrast, the type of the evidence *term* (ctev_dest / ctev_evar) in
1750 the evidence may *not* be fully zonked; we are careful not to look at it
1751 during constraint solving. See Note [Evidence field of CtEvidence].
1752
1753 Note [Ct kind invariant]
1754 ~~~~~~~~~~~~~~~~~~~~~~~~
1755 CTyEqCan and CFunEqCan both require that the kind of the lhs matches the kind
1756 of the rhs. This is necessary because both constraints are used for substitutions
1757 during solving. If the kinds differed, then the substitution would take a well-kinded
1758 type to an ill-kinded one.
1759
1760 -}
1761
1762 mkNonCanonical :: CtEvidence -> Ct
1763 mkNonCanonical ev = CNonCanonical { cc_ev = ev }
1764
1765 mkNonCanonicalCt :: Ct -> Ct
1766 mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
1767
1768 mkIrredCt :: CtEvidence -> Ct
1769 mkIrredCt ev = CIrredCan { cc_ev = ev, cc_insol = False }
1770
1771 mkInsolubleCt :: CtEvidence -> Ct
1772 mkInsolubleCt ev = CIrredCan { cc_ev = ev, cc_insol = True }
1773
1774 mkGivens :: CtLoc -> [EvId] -> [Ct]
1775 mkGivens loc ev_ids
1776 = map mk ev_ids
1777 where
1778 mk ev_id = mkNonCanonical (CtGiven { ctev_evar = ev_id
1779 , ctev_pred = evVarPred ev_id
1780 , ctev_loc = loc })
1781
1782 ctEvidence :: Ct -> CtEvidence
1783 ctEvidence = cc_ev
1784
1785 ctLoc :: Ct -> CtLoc
1786 ctLoc = ctEvLoc . ctEvidence
1787
1788 setCtLoc :: Ct -> CtLoc -> Ct
1789 setCtLoc ct loc = ct { cc_ev = (cc_ev ct) { ctev_loc = loc } }
1790
1791 ctOrigin :: Ct -> CtOrigin
1792 ctOrigin = ctLocOrigin . ctLoc
1793
1794 ctPred :: Ct -> PredType
1795 -- See Note [Ct/evidence invariant]
1796 ctPred ct = ctEvPred (cc_ev ct)
1797
1798 ctEvId :: Ct -> EvVar
1799 -- The evidence Id for this Ct
1800 ctEvId ct = ctEvEvId (ctEvidence ct)
1801
1802 -- | Makes a new equality predicate with the same role as the given
1803 -- evidence.
1804 mkTcEqPredLikeEv :: CtEvidence -> TcType -> TcType -> TcType
1805 mkTcEqPredLikeEv ev
1806 = case predTypeEqRel pred of
1807 NomEq -> mkPrimEqPred
1808 ReprEq -> mkReprPrimEqPred
1809 where
1810 pred = ctEvPred ev
1811
1812 -- | Get the flavour of the given 'Ct'
1813 ctFlavour :: Ct -> CtFlavour
1814 ctFlavour = ctEvFlavour . ctEvidence
1815
1816 -- | Get the equality relation for the given 'Ct'
1817 ctEqRel :: Ct -> EqRel
1818 ctEqRel = ctEvEqRel . ctEvidence
1819
1820 instance Outputable Ct where
1821 ppr ct = ppr (cc_ev ct) <+> parens pp_sort
1822 where
1823 pp_sort = case ct of
1824 CTyEqCan {} -> text "CTyEqCan"
1825 CFunEqCan {} -> text "CFunEqCan"
1826 CNonCanonical {} -> text "CNonCanonical"
1827 CDictCan { cc_pend_sc = pend_sc }
1828 | pend_sc -> text "CDictCan(psc)"
1829 | otherwise -> text "CDictCan"
1830 CIrredCan { cc_insol = insol }
1831 | insol -> text "CIrredCan(insol)"
1832 | otherwise -> text "CIrredCan(sol)"
1833 CHoleCan { cc_hole = hole } -> text "CHoleCan:" <+> ppr hole
1834
1835 {-
1836 ************************************************************************
1837 * *
1838 Simple functions over evidence variables
1839 * *
1840 ************************************************************************
1841 -}
1842
1843 ---------------- Getting free tyvars -------------------------
1844
1845 -- | Returns free variables of constraints as a non-deterministic set
1846 tyCoVarsOfCt :: Ct -> TcTyCoVarSet
1847 tyCoVarsOfCt = fvVarSet . tyCoFVsOfCt
1848
1849 -- | Returns free variables of constraints as a deterministically ordered.
1850 -- list. See Note [Deterministic FV] in FV.
1851 tyCoVarsOfCtList :: Ct -> [TcTyCoVar]
1852 tyCoVarsOfCtList = fvVarList . tyCoFVsOfCt
1853
1854 -- | Returns free variables of constraints as a composable FV computation.
1855 -- See Note [Deterministic FV] in FV.
1856 tyCoFVsOfCt :: Ct -> FV
1857 tyCoFVsOfCt (CTyEqCan { cc_tyvar = tv, cc_rhs = xi })
1858 = tyCoFVsOfType xi `unionFV` FV.unitFV tv
1859 `unionFV` tyCoFVsOfType (tyVarKind tv)
1860 tyCoFVsOfCt (CFunEqCan { cc_tyargs = tys, cc_fsk = fsk })
1861 = tyCoFVsOfTypes tys `unionFV` FV.unitFV fsk
1862 `unionFV` tyCoFVsOfType (tyVarKind fsk)
1863 tyCoFVsOfCt (CDictCan { cc_tyargs = tys }) = tyCoFVsOfTypes tys
1864 tyCoFVsOfCt (CIrredCan { cc_ev = ev }) = tyCoFVsOfType (ctEvPred ev)
1865 tyCoFVsOfCt (CHoleCan { cc_ev = ev }) = tyCoFVsOfType (ctEvPred ev)
1866 tyCoFVsOfCt (CNonCanonical { cc_ev = ev }) = tyCoFVsOfType (ctEvPred ev)
1867
1868 -- | Returns free variables of a bag of constraints as a non-deterministic
1869 -- set. See Note [Deterministic FV] in FV.
1870 tyCoVarsOfCts :: Cts -> TcTyCoVarSet
1871 tyCoVarsOfCts = fvVarSet . tyCoFVsOfCts
1872
1873 -- | Returns free variables of a bag of constraints as a deterministically
1874 -- odered list. See Note [Deterministic FV] in FV.
1875 tyCoVarsOfCtsList :: Cts -> [TcTyCoVar]
1876 tyCoVarsOfCtsList = fvVarList . tyCoFVsOfCts
1877
1878 -- | Returns free variables of a bag of constraints as a composable FV
1879 -- computation. See Note [Deterministic FV] in FV.
1880 tyCoFVsOfCts :: Cts -> FV
1881 tyCoFVsOfCts = foldrBag (unionFV . tyCoFVsOfCt) emptyFV
1882
1883 -- | Returns free variables of WantedConstraints as a non-deterministic
1884 -- set. See Note [Deterministic FV] in FV.
1885 tyCoVarsOfWC :: WantedConstraints -> TyCoVarSet
1886 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1887 tyCoVarsOfWC = fvVarSet . tyCoFVsOfWC
1888
1889 -- | Returns free variables of WantedConstraints as a deterministically
1890 -- ordered list. See Note [Deterministic FV] in FV.
1891 tyCoVarsOfWCList :: WantedConstraints -> [TyCoVar]
1892 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1893 tyCoVarsOfWCList = fvVarList . tyCoFVsOfWC
1894
1895 -- | Returns free variables of WantedConstraints as a composable FV
1896 -- computation. See Note [Deterministic FV] in FV.
1897 tyCoFVsOfWC :: WantedConstraints -> FV
1898 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1899 tyCoFVsOfWC (WC { wc_simple = simple, wc_impl = implic })
1900 = tyCoFVsOfCts simple `unionFV`
1901 tyCoFVsOfBag tyCoFVsOfImplic implic
1902
1903 -- | Returns free variables of Implication as a composable FV computation.
1904 -- See Note [Deterministic FV] in FV.
1905 tyCoFVsOfImplic :: Implication -> FV
1906 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1907 tyCoFVsOfImplic (Implic { ic_skols = skols
1908 , ic_given = givens
1909 , ic_wanted = wanted })
1910 = FV.delFVs (mkVarSet skols `unionVarSet` mkVarSet givens)
1911 (tyCoFVsOfWC wanted `unionFV` tyCoFVsOfTypes (map evVarPred givens))
1912
1913 tyCoFVsOfBag :: (a -> FV) -> Bag a -> FV
1914 tyCoFVsOfBag tvs_of = foldrBag (unionFV . tvs_of) emptyFV
1915
1916 ---------------------------
1917 dropDerivedWC :: WantedConstraints -> WantedConstraints
1918 -- See Note [Dropping derived constraints]
1919 dropDerivedWC wc@(WC { wc_simple = simples })
1920 = wc { wc_simple = dropDerivedSimples simples }
1921 -- The wc_impl implications are already (recursively) filtered
1922
1923 --------------------------
1924 dropDerivedSimples :: Cts -> Cts
1925 -- Drop all Derived constraints, but make [W] back into [WD],
1926 -- so that if we re-simplify these constraints we will get all
1927 -- the right derived constraints re-generated. Forgetting this
1928 -- step led to #12936
1929 dropDerivedSimples simples = mapMaybeBag dropDerivedCt simples
1930
1931 dropDerivedCt :: Ct -> Maybe Ct
1932 dropDerivedCt ct
1933 = case ctEvFlavour ev of
1934 Wanted WOnly -> Just (ct' { cc_ev = ev_wd })
1935 Wanted _ -> Just ct'
1936 _ | isDroppableCt ct -> Nothing
1937 | otherwise -> Just ct
1938 where
1939 ev = ctEvidence ct
1940 ev_wd = ev { ctev_nosh = WDeriv }
1941 ct' = setPendingScDict ct -- See Note [Resetting cc_pend_sc]
1942
1943 {- Note [Resetting cc_pend_sc]
1944 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
1945 When we discard Derived constraints, in dropDerivedSimples, we must
1946 set the cc_pend_sc flag to True, so that if we re-process this
1947 CDictCan we will re-generate its derived superclasses. Otherwise
1948 we might miss some fundeps. Trac #13662 showed this up.
1949
1950 See Note [The superclass story] in TcCanonical.
1951 -}
1952
1953 isDroppableCt :: Ct -> Bool
1954 isDroppableCt ct
1955 = isDerived ev && not keep_deriv
1956 -- Drop only derived constraints, and then only if they
1957 -- obey Note [Dropping derived constraints]
1958 where
1959 ev = ctEvidence ct
1960 loc = ctEvLoc ev
1961 orig = ctLocOrigin loc
1962
1963 keep_deriv
1964 = case ct of
1965 CHoleCan {} -> True
1966 CIrredCan { cc_insol = insoluble }
1967 -> keep_eq insoluble
1968 _ -> keep_eq False
1969
1970 keep_eq definitely_insoluble
1971 | isGivenOrigin orig -- Arising only from givens
1972 = definitely_insoluble -- Keep only definitely insoluble
1973 | otherwise
1974 = case orig of
1975 KindEqOrigin {} -> True -- Why?
1976
1977 -- See Note [Dropping derived constraints]
1978 -- For fundeps, drop wanted/wanted interactions
1979 FunDepOrigin2 {} -> True -- Top-level/Wanted
1980 FunDepOrigin1 _ loc1 _ loc2
1981 | g1 || g2 -> True -- Given/Wanted errors: keep all
1982 | otherwise -> False -- Wanted/Wanted errors: discard
1983 where
1984 g1 = isGivenLoc loc1
1985 g2 = isGivenLoc loc2
1986
1987 _ -> False
1988
1989 arisesFromGivens :: Ct -> Bool
1990 arisesFromGivens ct
1991 = case ctEvidence ct of
1992 CtGiven {} -> True
1993 CtWanted {} -> False
1994 CtDerived { ctev_loc = loc } -> isGivenLoc loc
1995
1996 isGivenLoc :: CtLoc -> Bool
1997 isGivenLoc loc = isGivenOrigin (ctLocOrigin loc)
1998
1999 isGivenOrigin :: CtOrigin -> Bool
2000 isGivenOrigin (GivenOrigin {}) = True
2001 isGivenOrigin (FunDepOrigin1 _ l1 _ l2) = isGivenLoc l1 && isGivenLoc l2
2002 isGivenOrigin (FunDepOrigin2 _ o1 _ _) = isGivenOrigin o1
2003 isGivenOrigin _ = False
2004
2005 {- Note [Dropping derived constraints]
2006 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2007 In general we discard derived constraints at the end of constraint solving;
2008 see dropDerivedWC. For example
2009
2010 * Superclasses: if we have an unsolved [W] (Ord a), we don't want to
2011 complain about an unsolved [D] (Eq a) as well.
2012
2013 * If we have [W] a ~ Int, [W] a ~ Bool, improvement will generate
2014 [D] Int ~ Bool, and we don't want to report that because it's
2015 incomprehensible. That is why we don't rewrite wanteds with wanteds!
2016
2017 But (tiresomely) we do keep *some* Derived constraints:
2018
2019 * Type holes are derived constraints, because they have no evidence
2020 and we want to keep them, so we get the error report
2021
2022 * Insoluble kind equalities (e.g. [D] * ~ (* -> *)), with
2023 KindEqOrigin, may arise from a type equality a ~ Int#, say. See
2024 Note [Equalities with incompatible kinds] in TcCanonical.
2025
2026 * We keep most derived equalities arising from functional dependencies
2027 - Given/Given interactions (subset of FunDepOrigin1):
2028 The definitely-insoluble ones reflect unreachable code.
2029
2030 Others not-definitely-insoluble ones like [D] a ~ Int do not
2031 reflect unreachable code; indeed if fundeps generated proofs, it'd
2032 be a useful equality. See Trac #14763. So we discard them.
2033
2034 - Given/Wanted interacGiven or Wanted interacting with an
2035 instance declaration (FunDepOrigin2)
2036
2037 - Given/Wanted interactions (FunDepOrigin1); see Trac #9612
2038
2039 - But for Wanted/Wanted interactions we do /not/ want to report an
2040 error (Trac #13506). Consider [W] C Int Int, [W] C Int Bool, with
2041 a fundep on class C. We don't want to report an insoluble Int~Bool;
2042 c.f. "wanteds do not rewrite wanteds".
2043
2044 To distinguish these cases we use the CtOrigin.
2045
2046 NB: we keep *all* derived insolubles under some circumstances:
2047
2048 * They are looked at by simplifyInfer, to decide whether to
2049 generalise. Example: [W] a ~ Int, [W] a ~ Bool
2050 We get [D] Int ~ Bool, and indeed the constraints are insoluble,
2051 and we want simplifyInfer to see that, even though we don't
2052 ultimately want to generate an (inexplicable) error message from it
2053
2054
2055 ************************************************************************
2056 * *
2057 CtEvidence
2058 The "flavor" of a canonical constraint
2059 * *
2060 ************************************************************************
2061 -}
2062
2063 isWantedCt :: Ct -> Bool
2064 isWantedCt = isWanted . cc_ev
2065
2066 isGivenCt :: Ct -> Bool
2067 isGivenCt = isGiven . cc_ev
2068
2069 isDerivedCt :: Ct -> Bool
2070 isDerivedCt = isDerived . cc_ev
2071
2072 isCTyEqCan :: Ct -> Bool
2073 isCTyEqCan (CTyEqCan {}) = True
2074 isCTyEqCan (CFunEqCan {}) = False
2075 isCTyEqCan _ = False
2076
2077 isCDictCan_Maybe :: Ct -> Maybe Class
2078 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
2079 isCDictCan_Maybe _ = Nothing
2080
2081 isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
2082 isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
2083 isCFunEqCan_maybe _ = Nothing
2084
2085 isCFunEqCan :: Ct -> Bool
2086 isCFunEqCan (CFunEqCan {}) = True
2087 isCFunEqCan _ = False
2088
2089 isCNonCanonical :: Ct -> Bool
2090 isCNonCanonical (CNonCanonical {}) = True
2091 isCNonCanonical _ = False
2092
2093 isHoleCt:: Ct -> Bool
2094 isHoleCt (CHoleCan {}) = True
2095 isHoleCt _ = False
2096
2097 isOutOfScopeCt :: Ct -> Bool
2098 -- We treat expression holes representing out-of-scope variables a bit
2099 -- differently when it comes to error reporting
2100 isOutOfScopeCt (CHoleCan { cc_hole = ExprHole (OutOfScope {}) }) = True
2101 isOutOfScopeCt _ = False
2102
2103 isExprHoleCt :: Ct -> Bool
2104 isExprHoleCt (CHoleCan { cc_hole = ExprHole {} }) = True
2105 isExprHoleCt _ = False
2106
2107 isTypeHoleCt :: Ct -> Bool
2108 isTypeHoleCt (CHoleCan { cc_hole = TypeHole {} }) = True
2109 isTypeHoleCt _ = False
2110
2111
2112 {- Note [Custom type errors in constraints]
2113 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2114
2115 When GHC reports a type-error about an unsolved-constraint, we check
2116 to see if the constraint contains any custom-type errors, and if so
2117 we report them. Here are some examples of constraints containing type
2118 errors:
2119
2120 TypeError msg -- The actual constraint is a type error
2121
2122 TypError msg ~ Int -- Some type was supposed to be Int, but ended up
2123 -- being a type error instead
2124
2125 Eq (TypeError msg) -- A class constraint is stuck due to a type error
2126
2127 F (TypeError msg) ~ a -- A type function failed to evaluate due to a type err
2128
2129 It is also possible to have constraints where the type error is nested deeper,
2130 for example see #11990, and also:
2131
2132 Eq (F (TypeError msg)) -- Here the type error is nested under a type-function
2133 -- call, which failed to evaluate because of it,
2134 -- and so the `Eq` constraint was unsolved.
2135 -- This may happen when one function calls another
2136 -- and the called function produced a custom type error.
2137 -}
2138
2139 -- | A constraint is considered to be a custom type error, if it contains
2140 -- custom type errors anywhere in it.
2141 -- See Note [Custom type errors in constraints]
2142 getUserTypeErrorMsg :: Ct -> Maybe Type
2143 getUserTypeErrorMsg ct = findUserTypeError (ctPred ct)
2144 where
2145 findUserTypeError t = msum ( userTypeError_maybe t
2146 : map findUserTypeError (subTys t)
2147 )
2148
2149 subTys t = case splitAppTys t of
2150 (t,[]) ->
2151 case splitTyConApp_maybe t of
2152 Nothing -> []
2153 Just (_,ts) -> ts
2154 (t,ts) -> t : ts
2155
2156
2157
2158
2159 isUserTypeErrorCt :: Ct -> Bool
2160 isUserTypeErrorCt ct = case getUserTypeErrorMsg ct of
2161 Just _ -> True
2162 _ -> False
2163
2164 isPendingScDict :: Ct -> Maybe Ct
2165 -- Says whether cc_pend_sc is True, AND if so flips the flag
2166 isPendingScDict ct@(CDictCan { cc_pend_sc = True })
2167 = Just (ct { cc_pend_sc = False })
2168 isPendingScDict _ = Nothing
2169
2170 setPendingScDict :: Ct -> Ct
2171 -- Set the cc_pend_sc flag to True
2172 setPendingScDict ct@(CDictCan { cc_pend_sc = False })
2173 = ct { cc_pend_sc = True }
2174 setPendingScDict ct = ct
2175
2176 superClassesMightHelp :: Ct -> Bool
2177 -- ^ True if taking superclasses of givens, or of wanteds (to perhaps
2178 -- expose more equalities or functional dependencies) might help to
2179 -- solve this constraint. See Note [When superclasses help]
2180 superClassesMightHelp ct
2181 = isWantedCt ct && not (is_ip ct)
2182 where
2183 is_ip (CDictCan { cc_class = cls }) = isIPClass cls
2184 is_ip _ = False
2185
2186 {- Note [When superclasses help]
2187 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2188 First read Note [The superclass story] in TcCanonical.
2189
2190 We expand superclasses and iterate only if there is at unsolved wanted
2191 for which expansion of superclasses (e.g. from given constraints)
2192 might actually help. The function superClassesMightHelp tells if
2193 doing this superclass expansion might help solve this constraint.
2194 Note that
2195
2196 * Superclasses help only for Wanted constraints. Derived constraints
2197 are not really "unsolved" and we certainly don't want them to
2198 trigger superclass expansion. This was a good part of the loop
2199 in Trac #11523
2200
2201 * Even for Wanted constraints, we say "no" for implicit parameters.
2202 we have [W] ?x::ty, expanding superclasses won't help:
2203 - Superclasses can't be implicit parameters
2204 - If we have a [G] ?x:ty2, then we'll have another unsolved
2205 [D] ty ~ ty2 (from the functional dependency)
2206 which will trigger superclass expansion.
2207
2208 It's a bit of a special case, but it's easy to do. The runtime cost
2209 is low because the unsolved set is usually empty anyway (errors
2210 aside), and the first non-imlicit-parameter will terminate the search.
2211
2212 The special case is worth it (Trac #11480, comment:2) because it
2213 applies to CallStack constraints, which aren't type errors. If we have
2214 f :: (C a) => blah
2215 f x = ...undefined...
2216 we'll get a CallStack constraint. If that's the only unsolved
2217 constraint it'll eventually be solved by defaulting. So we don't
2218 want to emit warnings about hitting the simplifier's iteration
2219 limit. A CallStack constraint really isn't an unsolved
2220 constraint; it can always be solved by defaulting.
2221 -}
2222
2223 singleCt :: Ct -> Cts
2224 singleCt = unitBag
2225
2226 andCts :: Cts -> Cts -> Cts
2227 andCts = unionBags
2228
2229 listToCts :: [Ct] -> Cts
2230 listToCts = listToBag
2231
2232 ctsElts :: Cts -> [Ct]
2233 ctsElts = bagToList
2234
2235 consCts :: Ct -> Cts -> Cts
2236 consCts = consBag
2237
2238 snocCts :: Cts -> Ct -> Cts
2239 snocCts = snocBag
2240
2241 extendCtsList :: Cts -> [Ct] -> Cts
2242 extendCtsList cts xs | null xs = cts
2243 | otherwise = cts `unionBags` listToBag xs
2244
2245 andManyCts :: [Cts] -> Cts
2246 andManyCts = unionManyBags
2247
2248 emptyCts :: Cts
2249 emptyCts = emptyBag
2250
2251 isEmptyCts :: Cts -> Bool
2252 isEmptyCts = isEmptyBag
2253
2254 pprCts :: Cts -> SDoc
2255 pprCts cts = vcat (map ppr (bagToList cts))
2256
2257 {-
2258 ************************************************************************
2259 * *
2260 Wanted constraints
2261 These are forced to be in TcRnTypes because
2262 TcLclEnv mentions WantedConstraints
2263 WantedConstraint mentions CtLoc
2264 CtLoc mentions ErrCtxt
2265 ErrCtxt mentions TcM
2266 * *
2267 v%************************************************************************
2268 -}
2269
2270 data WantedConstraints
2271 = WC { wc_simple :: Cts -- Unsolved constraints, all wanted
2272 , wc_impl :: Bag Implication
2273 }
2274
2275 emptyWC :: WantedConstraints
2276 emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag }
2277
2278 mkSimpleWC :: [CtEvidence] -> WantedConstraints
2279 mkSimpleWC cts
2280 = WC { wc_simple = listToBag (map mkNonCanonical cts)
2281 , wc_impl = emptyBag }
2282
2283 mkImplicWC :: Bag Implication -> WantedConstraints
2284 mkImplicWC implic
2285 = WC { wc_simple = emptyBag, wc_impl = implic }
2286
2287 isEmptyWC :: WantedConstraints -> Bool
2288 isEmptyWC (WC { wc_simple = f, wc_impl = i })
2289 = isEmptyBag f && isEmptyBag i
2290
2291 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
2292 andWC (WC { wc_simple = f1, wc_impl = i1 })
2293 (WC { wc_simple = f2, wc_impl = i2 })
2294 = WC { wc_simple = f1 `unionBags` f2
2295 , wc_impl = i1 `unionBags` i2 }
2296
2297 unionsWC :: [WantedConstraints] -> WantedConstraints
2298 unionsWC = foldr andWC emptyWC
2299
2300 addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
2301 addSimples wc cts
2302 = wc { wc_simple = wc_simple wc `unionBags` cts }
2303 -- Consider: Put the new constraints at the front, so they get solved first
2304
2305 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
2306 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
2307
2308 addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
2309 addInsols wc cts
2310 = wc { wc_simple = wc_simple wc `unionBags` cts }
2311
2312 insolublesOnly :: WantedConstraints -> WantedConstraints
2313 -- Keep only the definitely-insoluble constraints
2314 insolublesOnly (WC { wc_simple = simples, wc_impl = implics })
2315 = WC { wc_simple = filterBag insolubleWantedCt simples
2316 , wc_impl = mapBag implic_insols_only implics }
2317 where
2318 implic_insols_only implic
2319 = implic { ic_wanted = insolublesOnly (ic_wanted implic) }
2320
2321 isSolvedStatus :: ImplicStatus -> Bool
2322 isSolvedStatus (IC_Solved {}) = True
2323 isSolvedStatus _ = False
2324
2325 isInsolubleStatus :: ImplicStatus -> Bool
2326 isInsolubleStatus IC_Insoluble = True
2327 isInsolubleStatus _ = False
2328
2329 insolubleImplic :: Implication -> Bool
2330 insolubleImplic ic = isInsolubleStatus (ic_status ic)
2331
2332 insolubleWC :: WantedConstraints -> Bool
2333 insolubleWC (WC { wc_impl = implics, wc_simple = simples })
2334 = anyBag insolubleWantedCt simples
2335 || anyBag insolubleImplic implics
2336
2337 insolubleWantedCt :: Ct -> Bool
2338 -- Definitely insoluble, in particular /excluding/ type-hole constraints
2339 insolubleWantedCt ct
2340 | isGivenCt ct = False -- See Note [Given insolubles]
2341 | isHoleCt ct = isOutOfScopeCt ct -- See Note [Insoluble holes]
2342 | insolubleEqCt ct = True
2343 | otherwise = False
2344
2345 insolubleEqCt :: Ct -> Bool
2346 -- Returns True of /equality/ constraints
2347 -- that are /definitely/ insoluble
2348 -- It won't detect some definite errors like
2349 -- F a ~ T (F a)
2350 -- where F is a type family, which actually has an occurs check
2351 --
2352 -- The function is tuned for application /after/ constraint solving
2353 -- i.e. assuming canonicalisation has been done
2354 -- E.g. It'll reply True for a ~ [a]
2355 -- but False for [a] ~ a
2356 -- and
2357 -- True for Int ~ F a Int
2358 -- but False for Maybe Int ~ F a Int Int
2359 -- (where F is an arity-1 type function)
2360 insolubleEqCt (CIrredCan { cc_insol = insol }) = insol
2361 insolubleEqCt _ = False
2362
2363 instance Outputable WantedConstraints where
2364 ppr (WC {wc_simple = s, wc_impl = i})
2365 = text "WC" <+> braces (vcat
2366 [ ppr_bag (text "wc_simple") s
2367 , ppr_bag (text "wc_impl") i ])
2368
2369 ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
2370 ppr_bag doc bag
2371 | isEmptyBag bag = empty
2372 | otherwise = hang (doc <+> equals)
2373 2 (foldrBag (($$) . ppr) empty bag)
2374
2375 {- Note [Given insolubles]
2376 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2377 Consider (Trac #14325, comment:)
2378 class (a~b) => C a b
2379
2380 foo :: C a c => a -> c
2381 foo x = x
2382
2383 hm3 :: C (f b) b => b -> f b
2384 hm3 x = foo x
2385
2386 In the RHS of hm3, from the [G] C (f b) b we get the insoluble
2387 [G] f b ~# b. Then we also get an unsolved [W] C b (f b).
2388 Residual implication looks like
2389 forall b. C (f b) b => [G] f b ~# b
2390 [W] C f (f b)
2391
2392 We do /not/ want to set the implication status to IC_Insoluble,
2393 because that'll suppress reports of [W] C b (f b). But we
2394 may not report the insoluble [G] f b ~# b either (see Note [Given errors]
2395 in TcErrors), so we may fail to report anything at all! Yikes.
2396
2397 Bottom line: insolubleWC (called in TcSimplify.setImplicationStatus)
2398 should ignore givens even if they are insoluble.
2399
2400 Note [Insoluble holes]
2401 ~~~~~~~~~~~~~~~~~~~~~~
2402 Hole constraints that ARE NOT treated as truly insoluble:
2403 a) type holes, arising from PartialTypeSignatures,
2404 b) "true" expression holes arising from TypedHoles
2405
2406 An "expression hole" or "type hole" constraint isn't really an error
2407 at all; it's a report saying "_ :: Int" here. But an out-of-scope
2408 variable masquerading as expression holes IS treated as truly
2409 insoluble, so that it trumps other errors during error reporting.
2410 Yuk!
2411
2412 ************************************************************************
2413 * *
2414 Implication constraints
2415 * *
2416 ************************************************************************
2417 -}
2418
2419 data Implication
2420 = Implic { -- Invariants for a tree of implications:
2421 -- see TcType Note [TcLevel and untouchable type variables]
2422
2423 ic_tclvl :: TcLevel, -- TcLevel of unification variables
2424 -- allocated /inside/ this implication
2425
2426 ic_skols :: [TcTyVar], -- Introduced skolems
2427 ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
2428 -- See Note [Shadowing in a constraint]
2429
2430 ic_given :: [EvVar], -- Given evidence variables
2431 -- (order does not matter)
2432 -- See Invariant (GivenInv) in TcType
2433
2434 ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
2435 -- False <=> ic_givens might have equalities
2436
2437 ic_env :: TcLclEnv, -- Gives the source location and error context
2438 -- for the implication, and hence for all the
2439 -- given evidence variables
2440
2441 ic_wanted :: WantedConstraints, -- The wanteds
2442 -- See Invariang (WantedInf) in TcType
2443
2444 ic_binds :: EvBindsVar, -- Points to the place to fill in the
2445 -- abstraction and bindings.
2446
2447 -- The ic_need fields keep track of which Given evidence
2448 -- is used by this implication or its children
2449 -- NB: including stuff used by nested implications that have since
2450 -- been discarded
2451 ic_need_inner :: VarSet, -- Includes all used Given evidence
2452 ic_need_outer :: VarSet, -- Includes only the free Given evidence
2453 -- i.e. ic_need_inner after deleting
2454 -- (a) givens (b) binders of ic_binds
2455
2456 ic_status :: ImplicStatus
2457 }
2458
2459 newImplication :: Implication
2460 newImplication
2461 = Implic { -- These fields must be initialisad
2462 ic_tclvl = panic "newImplic:tclvl"
2463 , ic_binds = panic "newImplic:binds"
2464 , ic_info = panic "newImplic:info"
2465 , ic_env = panic "newImplic:env"
2466
2467 -- The rest have sensible default values
2468 , ic_skols = []
2469 , ic_given = []
2470 , ic_wanted = emptyWC
2471 , ic_no_eqs = False
2472 , ic_status = IC_Unsolved
2473 , ic_need_inner = emptyVarSet
2474 , ic_need_outer = emptyVarSet }
2475
2476 data ImplicStatus
2477 = IC_Solved -- All wanteds in the tree are solved, all the way down
2478 { ics_dead :: [EvVar] } -- Subset of ic_given that are not needed
2479 -- See Note [Tracking redundant constraints] in TcSimplify
2480
2481 | IC_Insoluble -- At least one insoluble constraint in the tree
2482
2483 | IC_Unsolved -- Neither of the above; might go either way
2484
2485 instance Outputable Implication where
2486 ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
2487 , ic_given = given, ic_no_eqs = no_eqs
2488 , ic_wanted = wanted, ic_status = status
2489 , ic_binds = binds, ic_need_inner = need_in
2490 , ic_need_outer = need_out, ic_info = info })
2491 = hang (text "Implic" <+> lbrace)
2492 2 (sep [ text "TcLevel =" <+> ppr tclvl
2493 , text "Skolems =" <+> pprTyVars skols
2494 , text "No-eqs =" <+> ppr no_eqs
2495 , text "Status =" <+> ppr status
2496 , hang (text "Given =") 2 (pprEvVars given)
2497 , hang (text "Wanted =") 2 (ppr wanted)
2498 , text "Binds =" <+> ppr binds
2499 , text "Needed inner =" <+> ppr need_in
2500 , text "Needed outer =" <+> ppr need_out
2501 , pprSkolInfo info ] <+> rbrace)
2502
2503 instance Outputable ImplicStatus where
2504 ppr IC_Insoluble = text "Insoluble"
2505 ppr IC_Unsolved = text "Unsolved"
2506 ppr (IC_Solved { ics_dead = dead })
2507 = text "Solved" <+> (braces (text "Dead givens =" <+> ppr dead))
2508
2509 {-
2510 Note [Needed evidence variables]
2511 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2512 Th ic_need_evs field holds the free vars of ic_binds, and all the
2513 ic_binds in nested implications.
2514
2515 * Main purpose: if one of the ic_givens is not mentioned in here, it
2516 is redundant.
2517
2518 * solveImplication may drop an implication altogether if it has no
2519 remaining 'wanteds'. But we still track the free vars of its
2520 evidence binds, even though it has now disappeared.
2521
2522 Note [Shadowing in a constraint]
2523 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2524 We assume NO SHADOWING in a constraint. Specifically
2525 * The unification variables are all implicitly quantified at top
2526 level, and are all unique
2527 * The skolem variables bound in ic_skols are all freah when the
2528 implication is created.
2529 So we can safely substitute. For example, if we have
2530 forall a. a~Int => ...(forall b. ...a...)...
2531 we can push the (a~Int) constraint inwards in the "givens" without
2532 worrying that 'b' might clash.
2533
2534 Note [Skolems in an implication]
2535 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2536 The skolems in an implication are not there to perform a skolem escape
2537 check. That happens because all the environment variables are in the
2538 untouchables, and therefore cannot be unified with anything at all,
2539 let alone the skolems.
2540
2541 Instead, ic_skols is used only when considering floating a constraint
2542 outside the implication in TcSimplify.floatEqualities or
2543 TcSimplify.approximateImplications
2544
2545 Note [Insoluble constraints]
2546 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2547 Some of the errors that we get during canonicalization are best
2548 reported when all constraints have been simplified as much as
2549 possible. For instance, assume that during simplification the
2550 following constraints arise:
2551
2552 [Wanted] F alpha ~ uf1
2553 [Wanted] beta ~ uf1 beta
2554
2555 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
2556 we will simply see a message:
2557 'Can't construct the infinite type beta ~ uf1 beta'
2558 and the user has no idea what the uf1 variable is.
2559
2560 Instead our plan is that we will NOT fail immediately, but:
2561 (1) Record the "frozen" error in the ic_insols field
2562 (2) Isolate the offending constraint from the rest of the inerts
2563 (3) Keep on simplifying/canonicalizing
2564
2565 At the end, we will hopefully have substituted uf1 := F alpha, and we
2566 will be able to report a more informative error:
2567 'Can't construct the infinite type beta ~ F alpha beta'
2568
2569 Insoluble constraints *do* include Derived constraints. For example,
2570 a functional dependency might give rise to [D] Int ~ Bool, and we must
2571 report that. If insolubles did not contain Deriveds, reportErrors would
2572 never see it.
2573
2574
2575 ************************************************************************
2576 * *
2577 Pretty printing
2578 * *
2579 ************************************************************************
2580 -}
2581
2582 pprEvVars :: [EvVar] -> SDoc -- Print with their types
2583 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
2584
2585 pprEvVarTheta :: [EvVar] -> SDoc
2586 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
2587
2588 pprEvVarWithType :: EvVar -> SDoc
2589 pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
2590
2591
2592
2593 -- | Wraps the given type with the constraints (via ic_given) in the given
2594 -- implication, according to the variables mentioned (via ic_skols)
2595 -- in the implication.
2596 wrapTypeWithImplication :: Type -> Implication -> Type
2597 wrapTypeWithImplication ty impl =
2598 wrapType ty (ic_skols impl) (map idType $ ic_given impl)
2599
2600 wrapType :: Type -> [TyVar] -> [PredType] -> Type
2601 wrapType ty skols givens =
2602 wrapWithAllSkols $ mkFunTys givens ty
2603 where forAllTy :: Type -> TyVar -> Type
2604 forAllTy ty tv = mkForAllTy tv Specified ty
2605 wrapWithAllSkols ty = foldl forAllTy ty skols
2606
2607
2608 {-
2609 ************************************************************************
2610 * *
2611 CtEvidence
2612 * *
2613 ************************************************************************
2614
2615 Note [Evidence field of CtEvidence]
2616 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2617 During constraint solving we never look at the type of ctev_evar/ctev_dest;
2618 instead we look at the ctev_pred field. The evtm/evar field
2619 may be un-zonked.
2620
2621 Note [Bind new Givens immediately]
2622 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2623 For Givens we make new EvVars and bind them immediately. Two main reasons:
2624 * Gain sharing. E.g. suppose we start with g :: C a b, where
2625 class D a => C a b
2626 class (E a, F a) => D a
2627 If we generate all g's superclasses as separate EvTerms we might
2628 get selD1 (selC1 g) :: E a
2629 selD2 (selC1 g) :: F a
2630 selC1 g :: D a
2631 which we could do more economically as:
2632 g1 :: D a = selC1 g
2633 g2 :: E a = selD1 g1
2634 g3 :: F a = selD2 g1
2635
2636 * For *coercion* evidence we *must* bind each given:
2637 class (a~b) => C a b where ....
2638 f :: C a b => ....
2639 Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
2640 But that superclass selector can't (yet) appear in a coercion
2641 (see evTermCoercion), so the easy thing is to bind it to an Id.
2642
2643 So a Given has EvVar inside it rather than (as previously) an EvTerm.
2644
2645 Note [Given in ctEvCoercion]
2646 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2647 When retrieving the evidence from a Given equality, we update the type of the EvVar
2648 from the ctev_pred field. In Note [Evidence field of CtEvidence], we claim that
2649 the type of the evidence is never looked at -- but this isn't true in the case of
2650 a coercion that is used in a type. (See the comments in Note [Flattening] in TcFlatten
2651 about the FTRNotFollowed case of flattenTyVar.) So, right here where we are retrieving
2652 the coercion from a Given, we update the type to make sure it's zonked.
2653
2654 -}
2655
2656 -- | A place for type-checking evidence to go after it is generated.
2657 -- Wanted equalities are always HoleDest; other wanteds are always
2658 -- EvVarDest.
2659 data TcEvDest
2660 = EvVarDest EvVar -- ^ bind this var to the evidence
2661 -- EvVarDest is always used for non-type-equalities
2662 -- e.g. class constraints
2663
2664 | HoleDest CoercionHole -- ^ fill in this hole with the evidence
2665 -- HoleDest is always used for type-equalities
2666 -- See Note [Coercion holes] in TyCoRep
2667
2668 data CtEvidence
2669 = CtGiven -- Truly given, not depending on subgoals
2670 { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
2671 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
2672 , ctev_loc :: CtLoc }
2673
2674
2675 | CtWanted -- Wanted goal
2676 { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
2677 , ctev_dest :: TcEvDest
2678 , ctev_nosh :: ShadowInfo -- See Note [Constraint flavours]
2679 , ctev_loc :: CtLoc }
2680
2681 | CtDerived -- A goal that we don't really have to solve and can't
2682 -- immediately rewrite anything other than a derived
2683 -- (there's no evidence!) but if we do manage to solve
2684 -- it may help in solving other goals.
2685 { ctev_pred :: TcPredType
2686 , ctev_loc :: CtLoc }
2687
2688 ctEvPred :: CtEvidence -> TcPredType
2689 -- The predicate of a flavor
2690 ctEvPred = ctev_pred
2691
2692 ctEvLoc :: CtEvidence -> CtLoc
2693 ctEvLoc = ctev_loc
2694
2695 ctEvOrigin :: CtEvidence -> CtOrigin
2696 ctEvOrigin = ctLocOrigin . ctEvLoc
2697
2698 -- | Get the equality relation relevant for a 'CtEvidence'
2699 ctEvEqRel :: CtEvidence -> EqRel
2700 ctEvEqRel = predTypeEqRel . ctEvPred
2701
2702 -- | Get the role relevant for a 'CtEvidence'
2703 ctEvRole :: CtEvidence -> Role
2704 ctEvRole = eqRelRole . ctEvEqRel
2705
2706 ctEvExpr :: CtEvidence -> EvExpr
2707 ctEvExpr ev@(CtWanted { ctev_dest = HoleDest _ }) = evCoercion $ ctEvCoercion ev
2708 ctEvExpr ev = evId (ctEvEvId ev)
2709
2710 -- Always returns a coercion whose type is precisely ctev_pred of the CtEvidence.
2711 -- See also Note [Given in ctEvCoercion]
2712 ctEvCoercion :: CtEvidence -> Coercion
2713 ctEvCoercion (CtGiven { ctev_pred = pred_ty, ctev_evar = ev_id })
2714 = mkTcCoVarCo (setVarType ev_id pred_ty) -- See Note [Given in ctEvCoercion]
2715 ctEvCoercion (CtWanted { ctev_dest = dest })
2716 | HoleDest hole <- dest
2717 = -- ctEvCoercion is only called on type equalities
2718 -- and they always have HoleDests
2719 mkHoleCo hole
2720 ctEvCoercion ev
2721 = pprPanic "ctEvCoercion" (ppr ev)
2722
2723 ctEvEvId :: CtEvidence -> EvVar
2724 ctEvEvId (CtWanted { ctev_dest = EvVarDest ev }) = ev
2725 ctEvEvId (CtWanted { ctev_dest = HoleDest h }) = coHoleCoVar h
2726 ctEvEvId (CtGiven { ctev_evar = ev }) = ev
2727 ctEvEvId ctev@(CtDerived {}) = pprPanic "ctEvId:" (ppr ctev)
2728
2729 instance Outputable TcEvDest where
2730 ppr (HoleDest h) = text "hole" <> ppr h
2731 ppr (EvVarDest ev) = ppr ev
2732
2733 instance Outputable CtEvidence where
2734 ppr ev = ppr (ctEvFlavour ev)
2735 <+> pp_ev
2736 <+> braces (ppr (ctl_depth (ctEvLoc ev))) <> dcolon
2737 -- Show the sub-goal depth too
2738 <+> ppr (ctEvPred ev)
2739 where
2740 pp_ev = case ev of
2741 CtGiven { ctev_evar = v } -> ppr v
2742 CtWanted {ctev_dest = d } -> ppr d
2743 CtDerived {} -> text "_"
2744
2745 isWanted :: CtEvidence -> Bool
2746 isWanted (CtWanted {}) = True
2747 isWanted _ = False
2748
2749 isGiven :: CtEvidence -> Bool
2750 isGiven (CtGiven {}) = True
2751 isGiven _ = False
2752
2753 isDerived :: CtEvidence -> Bool
2754 isDerived (CtDerived {}) = True
2755 isDerived _ = False
2756
2757 {-
2758 %************************************************************************
2759 %* *
2760 CtFlavour
2761 %* *
2762 %************************************************************************
2763
2764 Note [Constraint flavours]
2765 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2766 Constraints come in four flavours:
2767
2768 * [G] Given: we have evidence
2769
2770 * [W] Wanted WOnly: we want evidence
2771
2772 * [D] Derived: any solution must satisfy this constraint, but
2773 we don't need evidence for it. Examples include:
2774 - superclasses of [W] class constraints
2775 - equalities arising from functional dependencies
2776 or injectivity
2777
2778 * [WD] Wanted WDeriv: a single constraint that represents
2779 both [W] and [D]
2780 We keep them paired as one both for efficiency, and because
2781 when we have a finite map F tys -> CFunEqCan, it's inconvenient
2782 to have two CFunEqCans in the range
2783
2784 The ctev_nosh field of a Wanted distinguishes between [W] and [WD]
2785
2786 Wanted constraints are born as [WD], but are split into [W] and its
2787 "shadow" [D] in TcSMonad.maybeEmitShadow.
2788
2789 See Note [The improvement story and derived shadows] in TcSMonad
2790 -}
2791
2792 data CtFlavour -- See Note [Constraint flavours]
2793 = Given
2794 | Wanted ShadowInfo
2795 | Derived
2796 deriving Eq
2797
2798 data ShadowInfo
2799 = WDeriv -- [WD] This Wanted constraint has no Derived shadow,
2800 -- so it behaves like a pair of a Wanted and a Derived
2801 | WOnly -- [W] It has a separate derived shadow
2802 -- See Note [Derived shadows]
2803 deriving( Eq )
2804
2805 isGivenOrWDeriv :: CtFlavour -> Bool
2806 isGivenOrWDeriv Given = True
2807 isGivenOrWDeriv (Wanted WDeriv) = True
2808 isGivenOrWDeriv _ = False
2809
2810 instance Outputable CtFlavour where
2811 ppr Given = text "[G]"
2812 ppr (Wanted WDeriv) = text "[WD]"
2813 ppr (Wanted WOnly) = text "[W]"
2814 ppr Derived = text "[D]"
2815
2816 ctEvFlavour :: CtEvidence -> CtFlavour
2817 ctEvFlavour (CtWanted { ctev_nosh = nosh }) = Wanted nosh
2818 ctEvFlavour (CtGiven {}) = Given
2819 ctEvFlavour (CtDerived {}) = Derived
2820
2821 -- | Whether or not one 'Ct' can rewrite another is determined by its
2822 -- flavour and its equality relation. See also
2823 -- Note [Flavours with roles] in TcSMonad
2824 type CtFlavourRole = (CtFlavour, EqRel)
2825
2826 -- | Extract the flavour, role, and boxity from a 'CtEvidence'
2827 ctEvFlavourRole :: CtEvidence -> CtFlavourRole
2828 ctEvFlavourRole ev = (ctEvFlavour ev, ctEvEqRel ev)
2829
2830 -- | Extract the flavour and role from a 'Ct'
2831 ctFlavourRole :: Ct -> CtFlavourRole
2832 -- Uses short-cuts to role for special cases
2833 ctFlavourRole (CDictCan { cc_ev = ev })
2834 = (ctEvFlavour ev, NomEq)
2835 ctFlavourRole (CTyEqCan { cc_ev = ev, cc_eq_rel = eq_rel })
2836 = (ctEvFlavour ev, eq_rel)
2837 ctFlavourRole (CFunEqCan { cc_ev = ev })
2838 = (ctEvFlavour ev, NomEq)
2839 ctFlavourRole (CHoleCan { cc_ev = ev })
2840 = (ctEvFlavour ev, NomEq)
2841 ctFlavourRole ct
2842 = ctEvFlavourRole (cc_ev ct)
2843
2844 {- Note [eqCanRewrite]
2845 ~~~~~~~~~~~~~~~~~~~~~~
2846 (eqCanRewrite ct1 ct2) holds if the constraint ct1 (a CTyEqCan of form
2847 tv ~ ty) can be used to rewrite ct2. It must satisfy the properties of
2848 a can-rewrite relation, see Definition [Can-rewrite relation] in
2849 TcSMonad.
2850
2851 With the solver handling Coercible constraints like equality constraints,
2852 the rewrite conditions must take role into account, never allowing
2853 a representational equality to rewrite a nominal one.
2854
2855 Note [Wanteds do not rewrite Wanteds]
2856 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2857 We don't allow Wanteds to rewrite Wanteds, because that can give rise
2858 to very confusing type error messages. A good example is Trac #8450.
2859 Here's another
2860 f :: a -> Bool
2861 f x = ( [x,'c'], [x,True] ) `seq` True
2862 Here we get
2863 [W] a ~ Char
2864 [W] a ~ Bool
2865 but we do not want to complain about Bool ~ Char!
2866
2867 Note [Deriveds do rewrite Deriveds]
2868 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2869 However we DO allow Deriveds to rewrite Deriveds, because that's how
2870 improvement works; see Note [The improvement story] in TcInteract.
2871
2872 However, for now at least I'm only letting (Derived,NomEq) rewrite
2873 (Derived,NomEq) and not doing anything for ReprEq. If we have
2874 eqCanRewriteFR (Derived, NomEq) (Derived, _) = True
2875 then we lose property R2 of Definition [Can-rewrite relation]
2876 in TcSMonad
2877 R2. If f1 >= f, and f2 >= f,
2878 then either f1 >= f2 or f2 >= f1
2879 Consider f1 = (Given, ReprEq)
2880 f2 = (Derived, NomEq)
2881 f = (Derived, ReprEq)
2882
2883 I thought maybe we could never get Derived ReprEq constraints, but
2884 we can; straight from the Wanteds during improvement. And from a Derived
2885 ReprEq we could conceivably get a Derived NomEq improvement (by decomposing
2886 a type constructor with Nomninal role), and hence unify.
2887 -}
2888
2889 eqCanRewrite :: EqRel -> EqRel -> Bool
2890 eqCanRewrite NomEq _ = True
2891 eqCanRewrite ReprEq ReprEq = True
2892 eqCanRewrite ReprEq NomEq = False
2893
2894 eqCanRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
2895 -- Can fr1 actually rewrite fr2?
2896 -- Very important function!
2897 -- See Note [eqCanRewrite]
2898 -- See Note [Wanteds do not rewrite Wanteds]
2899 -- See Note [Deriveds do rewrite Deriveds]
2900 eqCanRewriteFR (Given, r1) (_, r2) = eqCanRewrite r1 r2
2901 eqCanRewriteFR (Wanted WDeriv, NomEq) (Derived, NomEq) = True
2902 eqCanRewriteFR (Derived, NomEq) (Derived, NomEq) = True
2903 eqCanRewriteFR _ _ = False
2904
2905 eqMayRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
2906 -- Is it /possible/ that fr1 can rewrite fr2?
2907 -- This is used when deciding which inerts to kick out,
2908 -- at which time a [WD] inert may be split into [W] and [D]
2909 eqMayRewriteFR (Wanted WDeriv, NomEq) (Wanted WDeriv, NomEq) = True
2910 eqMayRewriteFR (Derived, NomEq) (Wanted WDeriv, NomEq) = True
2911 eqMayRewriteFR fr1 fr2 = eqCanRewriteFR fr1 fr2
2912
2913 -----------------
2914 {- Note [funEqCanDischarge]
2915 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2916 Suppose we have two CFunEqCans with the same LHS:
2917 (x1:F ts ~ f1) `funEqCanDischarge` (x2:F ts ~ f2)
2918 Can we drop x2 in favour of x1, either unifying
2919 f2 (if it's a flatten meta-var) or adding a new Given
2920 (f1 ~ f2), if x2 is a Given?
2921
2922 Answer: yes if funEqCanDischarge is true.
2923 -}
2924
2925 funEqCanDischarge
2926 :: CtEvidence -> CtEvidence
2927 -> ( SwapFlag -- NotSwapped => lhs can discharge rhs
2928 -- Swapped => rhs can discharge lhs
2929 , Bool) -- True <=> upgrade non-discharded one
2930 -- from [W] to [WD]
2931 -- See Note [funEqCanDischarge]
2932 funEqCanDischarge ev1 ev2
2933 = ASSERT2( ctEvEqRel ev1 == NomEq, ppr ev1 )
2934 ASSERT2( ctEvEqRel ev2 == NomEq, ppr ev2 )
2935 -- CFunEqCans are all Nominal, hence asserts
2936 funEqCanDischargeF (ctEvFlavour ev1) (ctEvFlavour ev2)
2937
2938 funEqCanDischargeF :: CtFlavour -> CtFlavour -> (SwapFlag, Bool)
2939 funEqCanDischargeF Given _ = (NotSwapped, False)
2940 funEqCanDischargeF _ Given = (IsSwapped, False)
2941 funEqCanDischargeF (Wanted WDeriv) _ = (NotSwapped, False)
2942 funEqCanDischargeF _ (Wanted WDeriv) = (IsSwapped, True)
2943 funEqCanDischargeF (Wanted WOnly) (Wanted WOnly) = (NotSwapped, False)
2944 funEqCanDischargeF (Wanted WOnly) Derived = (NotSwapped, True)
2945 funEqCanDischargeF Derived (Wanted WOnly) = (IsSwapped, True)
2946 funEqCanDischargeF Derived Derived = (NotSwapped, False)
2947
2948
2949 {- Note [eqCanDischarge]
2950 ~~~~~~~~~~~~~~~~~~~~~~~~
2951 Suppose we have two identical CTyEqCan equality constraints
2952 (i.e. both LHS and RHS are the same)
2953 (x1:a~t) `eqCanDischarge` (xs:a~t)
2954 Can we just drop x2 in favour of x1?
2955
2956 Answer: yes if eqCanDischarge is true.
2957
2958 Note that we do /not/ allow Wanted to discharge Derived.
2959 We must keep both. Why? Because the Derived may rewrite
2960 other Deriveds in the model whereas the Wanted cannot.
2961
2962 However a Wanted can certainly discharge an identical Wanted. So
2963 eqCanDischarge does /not/ define a can-rewrite relation in the
2964 sense of Definition [Can-rewrite relation] in TcSMonad.
2965
2966 We /do/ say that a [W] can discharge a [WD]. In evidence terms it
2967 certainly can, and the /caller/ arranges that the otherwise-lost [D]
2968 is spat out as a new Derived. -}
2969
2970 eqCanDischargeFR :: CtFlavourRole -> CtFlavourRole -> Bool
2971 -- See Note [eqCanDischarge]
2972 eqCanDischargeFR (f1,r1) (f2, r2) = eqCanRewrite r1 r2
2973 && eqCanDischargeF f1 f2
2974
2975 eqCanDischargeF :: CtFlavour -> CtFlavour -> Bool
2976 eqCanDischargeF Given _ = True
2977 eqCanDischargeF (Wanted _) (Wanted _) = True
2978 eqCanDischargeF (Wanted WDeriv) Derived = True
2979 eqCanDischargeF Derived Derived = True
2980 eqCanDischargeF _ _ = False
2981
2982
2983 {-
2984 ************************************************************************
2985 * *
2986 SubGoalDepth
2987 * *
2988 ************************************************************************
2989
2990 Note [SubGoalDepth]
2991 ~~~~~~~~~~~~~~~~~~~
2992 The 'SubGoalDepth' takes care of stopping the constraint solver from looping.
2993
2994 The counter starts at zero and increases. It includes dictionary constraints,
2995 equality simplification, and type family reduction. (Why combine these? Because
2996 it's actually quite easy to mistake one for another, in sufficiently involved
2997 scenarios, like ConstraintKinds.)
2998
2999 The flag -fcontext-stack=n (not very well named!) fixes the maximium
3000 level.
3001
3002 * The counter includes the depth of type class instance declarations. Example:
3003 [W] d{7} : Eq [Int]
3004 That is d's dictionary-constraint depth is 7. If we use the instance
3005 $dfEqList :: Eq a => Eq [a]
3006 to simplify it, we get
3007 d{7} = $dfEqList d'{8}
3008 where d'{8} : Eq Int, and d' has depth 8.
3009
3010 For civilised (decidable) instance declarations, each increase of
3011 depth removes a type constructor from the type, so the depth never
3012 gets big; i.e. is bounded by the structural depth of the type.
3013
3014 * The counter also increments when resolving
3015 equalities involving type functions. Example:
3016 Assume we have a wanted at depth 7:
3017 [W] d{7} : F () ~ a
3018 If there is a type function equation "F () = Int", this would be rewritten to
3019 [W] d{8} : Int ~ a
3020 and remembered as having depth 8.
3021
3022 Again, without UndecidableInstances, this counter is bounded, but without it
3023 can resolve things ad infinitum. Hence there is a maximum level.
3024
3025 * Lastly, every time an equality is rewritten, the counter increases. Again,
3026 rewriting an equality constraint normally makes progress, but it's possible
3027 the "progress" is just the reduction of an infinitely-reducing type family.
3028 Hence we need to track the rewrites.
3029
3030 When compiling a program requires a greater depth, then GHC recommends turning
3031 off this check entirely by setting -freduction-depth=0. This is because the
3032 exact number that works is highly variable, and is likely to change even between
3033 minor releases. Because this check is solely to prevent infinite compilation
3034 times, it seems safe to disable it when a user has ascertained that their program
3035 doesn't loop at the type level.
3036
3037 -}
3038
3039 -- | See Note [SubGoalDepth]
3040 newtype SubGoalDepth = SubGoalDepth Int
3041 deriving (Eq, Ord, Outputable)
3042
3043 initialSubGoalDepth :: SubGoalDepth
3044 initialSubGoalDepth = SubGoalDepth 0
3045
3046 bumpSubGoalDepth :: SubGoalDepth -> SubGoalDepth
3047 bumpSubGoalDepth (SubGoalDepth n) = SubGoalDepth (n + 1)
3048
3049 maxSubGoalDepth :: SubGoalDepth -> SubGoalDepth -> SubGoalDepth
3050 maxSubGoalDepth (SubGoalDepth n) (SubGoalDepth m) = SubGoalDepth (n `max` m)
3051
3052 subGoalDepthExceeded :: DynFlags -> SubGoalDepth -> Bool
3053 subGoalDepthExceeded dflags (SubGoalDepth d)
3054 = mkIntWithInf d > reductionDepth dflags
3055
3056 {-
3057 ************************************************************************
3058 * *
3059 CtLoc
3060 * *
3061 ************************************************************************
3062
3063 The 'CtLoc' gives information about where a constraint came from.
3064 This is important for decent error message reporting because
3065 dictionaries don't appear in the original source code.
3066 type will evolve...
3067
3068 -}
3069
3070 data CtLoc = CtLoc { ctl_origin :: CtOrigin
3071 , ctl_env :: TcLclEnv
3072 , ctl_t_or_k :: Maybe TypeOrKind -- OK if we're not sure
3073 , ctl_depth :: !SubGoalDepth }
3074
3075 -- The TcLclEnv includes particularly
3076 -- source location: tcl_loc :: RealSrcSpan
3077 -- context: tcl_ctxt :: [ErrCtxt]
3078 -- binder stack: tcl_bndrs :: TcBinderStack
3079 -- level: tcl_tclvl :: TcLevel
3080
3081 mkKindLoc :: TcType -> TcType -- original *types* being compared
3082 -> CtLoc -> CtLoc
3083 mkKindLoc s1 s2 loc = setCtLocOrigin (toKindLoc loc)
3084 (KindEqOrigin s1 (Just s2) (ctLocOrigin loc)
3085 (ctLocTypeOrKind_maybe loc))
3086
3087 -- | Take a CtLoc and moves it to the kind level
3088 toKindLoc :: CtLoc -> CtLoc
3089 toKindLoc loc = loc { ctl_t_or_k = Just KindLevel }
3090
3091 mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
3092 mkGivenLoc tclvl skol_info env
3093 = CtLoc { ctl_origin = GivenOrigin skol_info
3094 , ctl_env = env { tcl_tclvl = tclvl }
3095 , ctl_t_or_k = Nothing -- this only matters for error msgs
3096 , ctl_depth = initialSubGoalDepth }
3097
3098 ctLocEnv :: CtLoc -> TcLclEnv
3099 ctLocEnv = ctl_env
3100
3101 ctLocLevel :: CtLoc -> TcLevel
3102 ctLocLevel loc = tcl_tclvl (ctLocEnv loc)
3103
3104 ctLocDepth :: CtLoc -> SubGoalDepth
3105 ctLocDepth = ctl_depth
3106
3107 ctLocOrigin :: CtLoc -> CtOrigin
3108 ctLocOrigin = ctl_origin
3109
3110 ctLocSpan :: CtLoc -> RealSrcSpan
3111 ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
3112
3113 ctLocTypeOrKind_maybe :: CtLoc -> Maybe TypeOrKind
3114 ctLocTypeOrKind_maybe = ctl_t_or_k
3115
3116 setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
3117 setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
3118
3119 bumpCtLocDepth :: CtLoc -> CtLoc
3120 bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth d }
3121
3122 setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
3123 setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
3124
3125 updateCtLocOrigin :: CtLoc -> (CtOrigin -> CtOrigin) -> CtLoc
3126 updateCtLocOrigin ctl@(CtLoc { ctl_origin = orig }) upd
3127 = ctl { ctl_origin = upd orig }
3128
3129 setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
3130 setCtLocEnv ctl env = ctl { ctl_env = env }
3131
3132 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
3133 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
3134 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
3135
3136 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
3137 -- Just add information w/o updating the origin!
3138 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
3139 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
3140
3141 {-
3142 ************************************************************************
3143 * *
3144 SkolemInfo
3145 * *
3146 ************************************************************************
3147 -}
3148
3149 -- SkolemInfo gives the origin of *given* constraints
3150 -- a) type variables are skolemised
3151 -- b) an implication constraint is generated
3152 data SkolemInfo
3153 = SigSkol -- A skolem that is created by instantiating
3154 -- a programmer-supplied type signature
3155 -- Location of the binding site is on the TyVar
3156 -- See Note [SigSkol SkolemInfo]
3157 UserTypeCtxt -- What sort of signature
3158 TcType -- Original type signature (before skolemisation)
3159 [(Name,TcTyVar)] -- Maps the original name of the skolemised tyvar
3160 -- to its instantiated version
3161
3162 | ClsSkol Class -- Bound at a class decl
3163
3164 | DerivSkol Type -- Bound by a 'deriving' clause;
3165 -- the type is the instance we are trying to derive
3166
3167 | InstSkol -- Bound at an instance decl
3168 | InstSC TypeSize -- A "given" constraint obtained by superclass selection.
3169 -- If (C ty1 .. tyn) is the largest class from
3170 -- which we made a superclass selection in the chain,
3171 -- then TypeSize = sizeTypes [ty1, .., tyn]
3172 -- See Note [Solving superclass constraints] in TcInstDcls
3173
3174 | DataSkol -- Bound at a data type declaration
3175 | FamInstSkol -- Bound at a family instance decl
3176 | PatSkol -- An existential type variable bound by a pattern for
3177 ConLike -- a data constructor with an existential type.
3178 (HsMatchContext Name)
3179 -- e.g. data T = forall a. Eq a => MkT a
3180 -- f (MkT x) = ...
3181 -- The pattern MkT x will allocate an existential type
3182 -- variable for 'a'.
3183
3184 | ArrowSkol -- An arrow form (see TcArrows)
3185
3186 | IPSkol [HsIPName] -- Binding site of an implicit parameter
3187
3188 | RuleSkol RuleName -- The LHS of a RULE
3189
3190 | InferSkol [(Name,TcType)]
3191 -- We have inferred a type for these (mutually-recursivive)
3192 -- polymorphic Ids, and are now checking that their RHS
3193 -- constraints are satisfied.
3194
3195 | BracketSkol -- Template Haskell bracket
3196
3197 | UnifyForAllSkol -- We are unifying two for-all types
3198 TcType -- The instantiated type *inside* the forall
3199
3200 | UnkSkol -- Unhelpful info (until I improve it)
3201
3202 instance Outputable SkolemInfo where
3203 ppr = pprSkolInfo
3204
3205 termEvidenceAllowed :: SkolemInfo -> Bool
3206 -- Whether an implication constraint with this SkolemInfo
3207 -- is permitted to have term-level evidence. There is
3208 -- only one that is not, associated with unifiying
3209 -- forall-types
3210 termEvidenceAllowed (UnifyForAllSkol {}) = False
3211 termEvidenceAllowed _ = True
3212
3213 pprSkolInfo :: SkolemInfo -> SDoc
3214 -- Complete the sentence "is a rigid type variable bound by..."
3215 pprSkolInfo (SigSkol cx ty _) = pprSigSkolInfo cx ty
3216 pprSkolInfo (IPSkol ips) = text "the implicit-parameter binding" <> plural ips <+> text "for"
3217 <+> pprWithCommas ppr ips
3218 pprSkolInfo (ClsSkol cls) = text "the class declaration for" <+> quotes (ppr cls)
3219 pprSkolInfo (DerivSkol pred) = text "the deriving clause for" <+> quotes (ppr pred)
3220 pprSkolInfo InstSkol = text "the instance declaration"
3221 pprSkolInfo (InstSC n) = text "the instance declaration" <> whenPprDebug (parens (ppr n))
3222 pprSkolInfo DataSkol = text "a data type declaration"
3223 pprSkolInfo FamInstSkol = text "a family instance declaration"
3224 pprSkolInfo BracketSkol = text "a Template Haskell bracket"
3225 pprSkolInfo (RuleSkol name) = text "the RULE" <+> pprRuleName name
3226 pprSkolInfo ArrowSkol = text "an arrow form"
3227 pprSkolInfo (PatSkol cl mc) = sep [ pprPatSkolInfo cl
3228 , text "in" <+> pprMatchContext mc ]
3229 pprSkolInfo (InferSkol ids) = hang (text "the inferred type" <> plural ids <+> text "of")
3230 2 (vcat [ ppr name <+> dcolon <+> ppr ty
3231 | (name,ty) <- ids ])
3232 pprSkolInfo (UnifyForAllSkol ty) = text "the type" <+> ppr ty
3233
3234 -- UnkSkol
3235 -- For type variables the others are dealt with by pprSkolTvBinding.
3236 -- For Insts, these cases should not happen
3237 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) text "UnkSkol"
3238
3239 pprSigSkolInfo :: UserTypeCtxt -> TcType -> SDoc
3240 -- The type is already tidied
3241 pprSigSkolInfo ctxt ty
3242 = case ctxt of
3243 FunSigCtxt f _ -> vcat [ text "the type signature for:"
3244 , nest 2 (pprPrefixOcc f <+> dcolon <+> ppr ty) ]
3245 PatSynCtxt {} -> pprUserTypeCtxt ctxt -- See Note [Skolem info for pattern synonyms]
3246 _ -> vcat [ pprUserTypeCtxt ctxt <> colon
3247 , nest 2 (ppr ty) ]
3248
3249 pprPatSkolInfo :: ConLike -> SDoc
3250 pprPatSkolInfo (RealDataCon dc)
3251 = sep [ text "a pattern with constructor:"
3252 , nest 2 $ ppr dc <+> dcolon
3253 <+> pprType (dataConUserType dc) <> comma ]
3254 -- pprType prints forall's regardless of -fprint-explicit-foralls
3255 -- which is what we want here, since we might be saying
3256 -- type variable 't' is bound by ...
3257
3258 pprPatSkolInfo (PatSynCon ps)
3259 = sep [ text "a pattern with pattern synonym:"
3260 , nest 2 $ ppr ps <+> dcolon
3261 <+> pprPatSynType ps <> comma ]
3262
3263 {- Note [Skolem info for pattern synonyms]
3264 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3265 For pattern synonym SkolemInfo we have
3266 SigSkol (PatSynCtxt p) ty _
3267 but the type 'ty' is not very helpful. The full pattern-synonym type
3268 has the provided and required pieces, which it is inconvenient to
3269 record and display here. So we simply don't display the type at all,
3270 contenting outselves with just the name of the pattern synonym, which
3271 is fine. We could do more, but it doesn't seem worth it.
3272
3273 Note [SigSkol SkolemInfo]
3274 ~~~~~~~~~~~~~~~~~~~~~~~~~
3275 Suppose we (deeply) skolemise a type
3276 f :: forall a. a -> forall b. b -> a
3277 Then we'll instantiate [a :-> a', b :-> b'], and with the instantiated
3278 a' -> b' -> a.
3279 But when, in an error message, we report that "b is a rigid type
3280 variable bound by the type signature for f", we want to show the foralls
3281 in the right place. So we proceed as follows:
3282
3283 * In SigSkol we record
3284 - the original signature forall a. a -> forall b. b -> a
3285 - the instantiation mapping [a :-> a', b :-> b']
3286
3287 * Then when tidying in TcMType.tidySkolemInfo, we first tidy a' to
3288 whatever it tidies to, say a''; and then we walk over the type
3289 replacing the binder a by the tidied version a'', to give
3290 forall a''. a'' -> forall b''. b'' -> a''
3291 We need to do this under function arrows, to match what deeplySkolemise
3292 does.
3293
3294 * Typically a'' will have a nice pretty name like "a", but the point is
3295 that the foral-bound variables of the signature we report line up with
3296 the instantiated skolems lying around in other types.
3297
3298
3299 ************************************************************************
3300 * *
3301 CtOrigin
3302 * *
3303 ************************************************************************
3304 -}
3305
3306 data CtOrigin
3307 = GivenOrigin SkolemInfo
3308
3309 -- All the others are for *wanted* constraints
3310 | OccurrenceOf Name -- Occurrence of an overloaded identifier
3311 | OccurrenceOfRecSel RdrName -- Occurrence of a record selector
3312 | AppOrigin -- An application of some kind
3313
3314 | SpecPragOrigin UserTypeCtxt -- Specialisation pragma for
3315 -- function or instance
3316
3317 | TypeEqOrigin { uo_actual :: TcType
3318 , uo_expected :: TcType
3319 , uo_thing :: Maybe SDoc
3320 -- ^ The thing that has type "actual"
3321 , uo_visible :: Bool
3322 -- ^ Is at least one of the three elements above visible?
3323 -- (Errors from the polymorphic subsumption check are considered
3324 -- visible.) Only used for prioritizing error messages.
3325 }
3326
3327 | KindEqOrigin -- See Note [Equalities with incompatible kinds] in TcCanonical.
3328 TcType (Maybe TcType) -- A kind equality arising from unifying these two types
3329 CtOrigin -- originally arising from this
3330 (Maybe TypeOrKind) -- the level of the eq this arises from
3331
3332 | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
3333 | OverLabelOrigin FastString -- Occurrence of an overloaded label
3334
3335 | LiteralOrigin (HsOverLit GhcRn) -- Occurrence of a literal
3336 | NegateOrigin -- Occurrence of syntactic negation
3337
3338 | ArithSeqOrigin (ArithSeqInfo GhcRn) -- [x..], [x..y] etc
3339 | PArrSeqOrigin (ArithSeqInfo GhcRn) -- [:x..y:] and [:x,y..z:]
3340 | SectionOrigin
3341 | TupleOrigin -- (..,..)
3342 | ExprSigOrigin -- e :: ty
3343 | PatSigOrigin -- p :: ty
3344 | PatOrigin -- Instantiating a polytyped pattern at a constructor
3345 | ProvCtxtOrigin -- The "provided" context of a pattern synonym signature
3346 (PatSynBind GhcRn GhcRn) -- Information about the pattern synonym, in
3347 -- particular the name and the right-hand side
3348 | RecordUpdOrigin
3349 | ViewPatOrigin
3350
3351 | ScOrigin TypeSize -- Typechecking superclasses of an instance declaration
3352 -- If the instance head is C ty1 .. tyn
3353 -- then TypeSize = sizeTypes [ty1, .., tyn]
3354 -- See Note [Solving superclass constraints] in TcInstDcls
3355
3356 | DerivOrigin -- Typechecking deriving
3357 | DerivOriginDC DataCon Int
3358 -- Checking constraints arising from this data con and field index
3359 | DerivOriginCoerce Id Type Type
3360 -- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
3361 -- `ty1` to `ty2`.
3362 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
3363 | DefaultOrigin -- Typechecking a default decl
3364 | DoOrigin -- Arising from a do expression
3365 | DoPatOrigin (LPat GhcRn) -- Arising from a failable pattern in
3366 -- a do expression
3367 | MCompOrigin -- Arising from a monad comprehension
3368 | MCompPatOrigin (LPat GhcRn) -- Arising from a failable pattern in a
3369 -- monad comprehension
3370 | IfOrigin -- Arising from an if statement
3371 | ProcOrigin -- Arising from a proc expression
3372 | AnnOrigin -- An annotation
3373
3374 | FunDepOrigin1 -- A functional dependency from combining
3375 PredType CtLoc -- This constraint arising from ...
3376 PredType CtLoc -- and this constraint arising from ...
3377
3378 | FunDepOrigin2 -- A functional dependency from combining
3379 PredType CtOrigin -- This constraint arising from ...
3380 PredType SrcSpan -- and this top-level instance
3381 -- We only need a CtOrigin on the first, because the location
3382 -- is pinned on the entire error message
3383
3384 | HoleOrigin
3385 | UnboundOccurrenceOf OccName
3386 | ListOrigin -- An overloaded list
3387 | StaticOrigin -- A static form
3388 | FailablePattern (LPat GhcTcId) -- A failable pattern in do-notation for the
3389 -- MonadFail Proposal (MFP). Obsolete when
3390 -- actual desugaring to MonadFail.fail is
3391 -- live.
3392 | Shouldn'tHappenOrigin String
3393 -- the user should never see this one,
3394 -- unless ImpredicativeTypes is on, where all
3395 -- bets are off
3396 | InstProvidedOrigin Module ClsInst
3397 -- Skolem variable arose when we were testing if an instance
3398 -- is solvable or not.
3399
3400 -- | Flag to see whether we're type-checking terms or kind-checking types
3401 data TypeOrKind = TypeLevel | KindLevel
3402 deriving Eq
3403
3404 instance Outputable TypeOrKind where
3405 ppr TypeLevel = text "TypeLevel"
3406 ppr KindLevel = text "KindLevel"
3407
3408 isTypeLevel :: TypeOrKind -> Bool
3409 isTypeLevel TypeLevel = True
3410 isTypeLevel KindLevel = False
3411
3412 isKindLevel :: TypeOrKind -> Bool
3413 isKindLevel TypeLevel = False
3414 isKindLevel KindLevel = True
3415
3416 -- An origin is visible if the place where the constraint arises is manifest
3417 -- in user code. Currently, all origins are visible except for invisible
3418 -- TypeEqOrigins. This is used when choosing which error of
3419 -- several to report
3420 isVisibleOrigin :: CtOrigin -> Bool
3421 isVisibleOrigin (TypeEqOrigin { uo_visible = vis }) = vis
3422 isVisibleOrigin (KindEqOrigin _ _ sub_orig _) = isVisibleOrigin sub_orig
3423 isVisibleOrigin _ = True
3424
3425 -- Converts a visible origin to an invisible one, if possible. Currently,
3426 -- this works only for TypeEqOrigin
3427 toInvisibleOrigin :: CtOrigin -> CtOrigin
3428 toInvisibleOrigin orig@(TypeEqOrigin {}) = orig { uo_visible = False }
3429 toInvisibleOrigin orig = orig
3430
3431 instance Outputable CtOrigin where
3432 ppr = pprCtOrigin
3433
3434 ctoHerald :: SDoc
3435 ctoHerald = text "arising from"
3436
3437 -- | Extract a suitable CtOrigin from a HsExpr
3438 lexprCtOrigin :: LHsExpr GhcRn -> CtOrigin
3439 lexprCtOrigin (L _ e) = exprCtOrigin e
3440
3441 exprCtOrigin :: HsExpr GhcRn -> CtOrigin
3442 exprCtOrigin (HsVar (L _ name)) = OccurrenceOf name
3443 exprCtOrigin (HsUnboundVar uv) = UnboundOccurrenceOf (unboundVarOcc uv)
3444 exprCtOrigin (HsConLikeOut {}) = panic "exprCtOrigin HsConLikeOut"
3445 exprCtOrigin (HsRecFld f) = OccurrenceOfRecSel (rdrNameAmbiguousFieldOcc f)
3446 exprCtOrigin (HsOverLabel _ l) = OverLabelOrigin l
3447 exprCtOrigin (HsIPVar ip) = IPOccOrigin ip
3448 exprCtOrigin (HsOverLit lit) = LiteralOrigin lit
3449 exprCtOrigin (HsLit {}) = Shouldn'tHappenOrigin "concrete literal"
3450 exprCtOrigin (HsLam matches) = matchesCtOrigin matches
3451 exprCtOrigin (HsLamCase ms) = matchesCtOrigin ms
3452 exprCtOrigin (HsApp e1 _) = lexprCtOrigin e1
3453 exprCtOrigin (HsAppType e1 _) = lexprCtOrigin e1
3454 exprCtOrigin (HsAppTypeOut {}) = panic "exprCtOrigin HsAppTypeOut"
3455 exprCtOrigin (OpApp _ op _ _) = lexprCtOrigin op
3456 exprCtOrigin (NegApp e _) = lexprCtOrigin e
3457 exprCtOrigin (HsPar e) = lexprCtOrigin e
3458 exprCtOrigin (SectionL _ _) = SectionOrigin
3459 exprCtOrigin (SectionR _ _) = SectionOrigin
3460 exprCtOrigin (ExplicitTuple {}) = Shouldn'tHappenOrigin "explicit tuple"
3461 exprCtOrigin ExplicitSum{} = Shouldn'tHappenOrigin "explicit sum"
3462 exprCtOrigin (HsCase _ matches) = matchesCtOrigin matches
3463 exprCtOrigin (HsIf (Just syn) _ _ _) = exprCtOrigin (syn_expr syn)
3464 exprCtOrigin (HsIf {}) = Shouldn'tHappenOrigin "if expression"
3465 exprCtOrigin (HsMultiIf _ rhs) = lGRHSCtOrigin rhs
3466 exprCtOrigin (HsLet _ e) = lexprCtOrigin e
3467 exprCtOrigin (HsDo _ _ _) = DoOrigin
3468 exprCtOrigin (ExplicitList {}) = Shouldn'tHappenOrigin "list"
3469 exprCtOrigin (ExplicitPArr {}) = Shouldn'tHappenOrigin "parallel array"
3470 exprCtOrigin (RecordCon {}) = Shouldn'tHappenOrigin "record construction"
3471 exprCtOrigin (RecordUpd {}) = Shouldn'tHappenOrigin "record update"
3472 exprCtOrigin (ExprWithTySig {}) = ExprSigOrigin
3473 exprCtOrigin (ExprWithTySigOut {}) = panic "exprCtOrigin ExprWithTySigOut"
3474 exprCtOrigin (ArithSeq {}) = Shouldn'tHappenOrigin "arithmetic sequence"
3475 exprCtOrigin (PArrSeq {}) = Shouldn'tHappenOrigin "parallel array sequence"
3476 exprCtOrigin (HsSCC _ _ e) = lexprCtOrigin e
3477 exprCtOrigin (HsCoreAnn _ _ e) = lexprCtOrigin e
3478 exprCtOrigin (HsBracket {}) = Shouldn'tHappenOrigin "TH bracket"
3479 exprCtOrigin (HsRnBracketOut {})= Shouldn'tHappenOrigin "HsRnBracketOut"
3480 exprCtOrigin (HsTcBracketOut {})= panic "exprCtOrigin HsTcBracketOut"
3481 exprCtOrigin (HsSpliceE {}) = Shouldn'tHappenOrigin "TH splice"
3482 exprCtOrigin (HsProc {}) = Shouldn'tHappenOrigin "proc"
3483 exprCtOrigin (HsStatic {}) = Shouldn'tHappenOrigin "static expression"
3484 exprCtOrigin (HsArrApp {}) = panic "exprCtOrigin HsArrApp"
3485 exprCtOrigin (HsArrForm {}) = panic "exprCtOrigin HsArrForm"
3486 exprCtOrigin (HsTick _ e) = lexprCtOrigin e
3487 exprCtOrigin (HsBinTick _ _ e) = lexprCtOrigin e
3488 exprCtOrigin (HsTickPragma _ _ _ e) = lexprCtOrigin e
3489 exprCtOrigin EWildPat = panic "exprCtOrigin EWildPat"
3490 exprCtOrigin (EAsPat {}) = panic "exprCtOrigin EAsPat"
3491 exprCtOrigin (EViewPat {}) = panic "exprCtOrigin EViewPat"
3492 exprCtOrigin (ELazyPat {}) = panic "exprCtOrigin ELazyPat"
3493 exprCtOrigin (HsWrap {}) = panic "exprCtOrigin HsWrap"
3494
3495 -- | Extract a suitable CtOrigin from a MatchGroup
3496 matchesCtOrigin :: MatchGroup GhcRn (LHsExpr GhcRn) -> CtOrigin
3497 matchesCtOrigin (MG { mg_alts = alts })
3498 | L _ [L _ match] <- alts
3499 , Match { m_grhss = grhss } <- match
3500 = grhssCtOrigin grhss
3501
3502 | otherwise
3503 = Shouldn'tHappenOrigin "multi-way match"
3504
3505 -- | Extract a suitable CtOrigin from guarded RHSs
3506 grhssCtOrigin :: GRHSs GhcRn (LHsExpr GhcRn) -> CtOrigin
3507 grhssCtOrigin (GRHSs { grhssGRHSs = lgrhss }) = lGRHSCtOrigin lgrhss
3508
3509 -- | Extract a suitable CtOrigin from a list of guarded RHSs
3510 lGRHSCtOrigin :: [LGRHS GhcRn (LHsExpr GhcRn)] -> CtOrigin
3511 lGRHSCtOrigin [L _ (GRHS _ (L _ e))] = exprCtOrigin e
3512 lGRHSCtOrigin _ = Shouldn'tHappenOrigin "multi-way GRHS"
3513
3514 pprCtLoc :: CtLoc -> SDoc
3515 -- "arising from ... at ..."
3516 -- Not an instance of Outputable because of the "arising from" prefix
3517 pprCtLoc (CtLoc { ctl_origin = o, ctl_env = lcl})
3518 = sep [ pprCtOrigin o
3519 , text "at" <+> ppr (tcl_loc lcl)]
3520
3521 pprCtOrigin :: CtOrigin -> SDoc
3522 -- "arising from ..."
3523 -- Not an instance of Outputable because of the "arising from" prefix
3524 pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
3525
3526 pprCtOrigin (SpecPragOrigin ctxt)
3527 = case ctxt of
3528 FunSigCtxt n _ -> text "a SPECIALISE pragma for" <+> quotes (ppr n)
3529 SpecInstCtxt -> text "a SPECIALISE INSTANCE pragma"
3530 _ -> text "a SPECIALISE pragma" -- Never happens I think
3531
3532 pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
3533 = hang (ctoHerald <+> text "a functional dependency between constraints:")
3534 2 (vcat [ hang (quotes (ppr pred1)) 2 (pprCtLoc loc1)
3535 , hang (quotes (ppr pred2)) 2 (pprCtLoc loc2) ])
3536
3537 pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
3538 = hang (ctoHerald <+> text "a functional dependency between:")
3539 2 (vcat [ hang (text "constraint" <+> quotes (ppr pred1))
3540 2 (pprCtOrigin orig1 )
3541 , hang (text "instance" <+> quotes (ppr pred2))
3542 2 (text "at" <+> ppr loc2) ])
3543
3544 pprCtOrigin (KindEqOrigin t1 (Just t2) _ _)
3545 = hang (ctoHerald <+> text "a kind equality arising from")
3546 2 (sep [ppr t1, char '~', ppr t2])
3547
3548 pprCtOrigin (KindEqOrigin t1 Nothing _ _)
3549 = hang (ctoHerald <+> text "a kind equality when matching")
3550 2 (ppr t1)
3551
3552 pprCtOrigin (UnboundOccurrenceOf name)
3553 = ctoHerald <+> text "an undeclared identifier" <+> quotes (ppr name)
3554
3555 pprCtOrigin (DerivOriginDC dc n)
3556 = hang (ctoHerald <+> text "the" <+> speakNth n
3557 <+> text "field of" <+> quotes (ppr dc))
3558 2 (parens (text "type" <+> quotes (ppr ty)))
3559 where
3560 ty = dataConOrigArgTys dc !! (n-1)
3561
3562 pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
3563 = hang (ctoHerald <+> text "the coercion of the method" <+> quotes (ppr meth))
3564 2 (sep [ text "from type" <+> quotes (ppr ty1)
3565 , nest 2 $ text "to type" <+> quotes (ppr ty2) ])
3566
3567 pprCtOrigin (DoPatOrigin pat)
3568 = ctoHerald <+> text "a do statement"
3569 $$
3570 text "with the failable pattern" <+> quotes (ppr pat)
3571
3572 pprCtOrigin (MCompPatOrigin pat)
3573 = ctoHerald <+> hsep [ text "the failable pattern"
3574 , quotes (ppr pat)
3575 , text "in a statement in a monad comprehension" ]
3576 pprCtOrigin (FailablePattern pat)
3577 = ctoHerald <+> text "the failable pattern" <+> quotes (ppr pat)
3578 $$
3579 text "(this will become an error in a future GHC release)"
3580
3581 pprCtOrigin (Shouldn'tHappenOrigin note)
3582 = sdocWithDynFlags $ \dflags ->
3583 if xopt LangExt.ImpredicativeTypes dflags
3584 then text "a situation created by impredicative types"
3585 else
3586 vcat [ text "<< This should not appear in error messages. If you see this"
3587 , text "in an error message, please report a bug mentioning" <+> quotes (text note) <+> text "at"
3588 , text "https://ghc.haskell.org/trac/ghc/wiki/ReportABug >>" ]
3589
3590 pprCtOrigin (ProvCtxtOrigin PSB{ psb_id = (L _ name) })
3591 = hang (ctoHerald <+> text "the \"provided\" constraints claimed by")
3592 2 (text "the signature of" <+> quotes (ppr name))
3593
3594 pprCtOrigin (InstProvidedOrigin mod cls_inst)
3595 = vcat [ text "arising when attempting to show that"
3596 , ppr cls_inst
3597 , text "is provided by" <+> quotes (ppr mod)]
3598
3599 pprCtOrigin simple_origin
3600 = ctoHerald <+> pprCtO simple_origin
3601
3602 -- | Short one-liners
3603 pprCtO :: CtOrigin -> SDoc
3604 pprCtO (OccurrenceOf name) = hsep [text "a use of", quotes (ppr name)]
3605 pprCtO (OccurrenceOfRecSel name) = hsep [text "a use of", quotes (ppr name)]
3606 pprCtO AppOrigin = text "an application"
3607 pprCtO (IPOccOrigin name) = hsep [text "a use of implicit parameter", quotes (ppr name)]
3608 pprCtO (OverLabelOrigin l) = hsep [text "the overloaded label"
3609 ,quotes (char '#' <> ppr l)]
3610 pprCtO RecordUpdOrigin = text "a record update"
3611 pprCtO ExprSigOrigin = text "an expression type signature"
3612 pprCtO PatSigOrigin = text "a pattern type signature"
3613 pprCtO PatOrigin = text "a pattern"
3614 pprCtO ViewPatOrigin = text "a view pattern"
3615 pprCtO IfOrigin = text "an if expression"
3616 pprCtO (LiteralOrigin lit) = hsep [text "the literal", quotes (ppr lit)]
3617 pprCtO (ArithSeqOrigin seq) = hsep [text "the arithmetic sequence", quotes (ppr seq)]
3618 pprCtO (PArrSeqOrigin seq) = hsep [text "the parallel array sequence", quotes (ppr seq)]
3619 pprCtO SectionOrigin = text "an operator section"
3620 pprCtO TupleOrigin = text "a tuple"
3621 pprCtO NegateOrigin = text "a use of syntactic negation"
3622 pprCtO (ScOrigin n) = text "the superclasses of an instance declaration"
3623 <> whenPprDebug (parens (ppr n))
3624 pprCtO DerivOrigin = text "the 'deriving' clause of a data type declaration"
3625 pprCtO StandAloneDerivOrigin = text "a 'deriving' declaration"
3626 pprCtO DefaultOrigin = text "a 'default' declaration"
3627 pprCtO DoOrigin = text "a do statement"
3628 pprCtO MCompOrigin = text "a statement in a monad comprehension"
3629 pprCtO ProcOrigin = text "a proc expression"
3630 pprCtO (TypeEqOrigin t1 t2 _ _)= text "a type equality" <+> sep [ppr t1, char '~', ppr t2]
3631 pprCtO AnnOrigin = text "an annotation"
3632 pprCtO HoleOrigin = text "a use of" <+> quotes (text "_")
3633 pprCtO ListOrigin = text "an overloaded list"
3634 pprCtO StaticOrigin = text "a static form"
3635 pprCtO _ = panic "pprCtOrigin"
3636
3637 {-
3638 Constraint Solver Plugins
3639 -------------------------
3640 -}
3641
3642 type TcPluginSolver = [Ct] -- given
3643 -> [Ct] -- derived
3644 -> [Ct] -- wanted
3645 -> TcPluginM TcPluginResult
3646
3647 newtype TcPluginM a = TcPluginM (EvBindsVar -> TcM a)
3648
3649 instance Functor TcPluginM where
3650 fmap = liftM
3651
3652 instance Applicative TcPluginM where
3653 pure x = TcPluginM (const $ pure x)
3654 (<*>) = ap
3655
3656 instance Monad TcPluginM where
3657 fail = MonadFail.fail
3658 TcPluginM m >>= k =
3659 TcPluginM (\ ev -> do a <- m ev
3660 runTcPluginM (k a) ev)
3661
3662 instance MonadFail.MonadFail TcPluginM where
3663 fail x = TcPluginM (const $ fail x)
3664
3665 runTcPluginM :: TcPluginM a -> EvBindsVar -> TcM a
3666 runTcPluginM (TcPluginM m) = m
3667
3668 -- | This function provides an escape for direct access to
3669 -- the 'TcM` monad. It should not be used lightly, and
3670 -- the provided 'TcPluginM' API should be favoured instead.
3671 unsafeTcPluginTcM :: TcM a -> TcPluginM a
3672 unsafeTcPluginTcM = TcPluginM . const
3673
3674 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
3675 -- constraint solving. Returns 'Nothing' if invoked during
3676 -- 'tcPluginInit' or 'tcPluginStop'.
3677 getEvBindsTcPluginM :: TcPluginM EvBindsVar
3678 getEvBindsTcPluginM = TcPluginM return
3679
3680
3681 data TcPlugin = forall s. TcPlugin
3682 { tcPluginInit :: TcPluginM s
3683 -- ^ Initialize plugin, when entering type-checker.
3684
3685 , tcPluginSolve :: s -> TcPluginSolver
3686 -- ^ Solve some constraints.
3687 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
3688
3689 , tcPluginStop :: s -> TcPluginM ()
3690 -- ^ Clean up after the plugin, when exiting the type-checker.
3691 }
3692
3693 data TcPluginResult
3694 = TcPluginContradiction [Ct]
3695 -- ^ The plugin found a contradiction.
3696 -- The returned constraints are removed from the inert set,
3697 -- and recorded as insoluble.
3698
3699 | TcPluginOk [(EvTerm,Ct)] [Ct]
3700 -- ^ The first field is for constraints that were solved.
3701 -- These are removed from the inert set,
3702 -- and the evidence for them is recorded.
3703 -- The second field contains new work, that should be processed by
3704 -- the constraint solver.
3705
3706 {- *********************************************************************
3707 * *
3708 Role annotations
3709 * *
3710 ********************************************************************* -}
3711
3712 type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn)
3713
3714 mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv
3715 mkRoleAnnotEnv role_annot_decls
3716 = mkNameEnv [ (name, ra_decl)
3717 | ra_decl <- role_annot_decls
3718 , let name = roleAnnotDeclName (unLoc ra_decl)
3719 , not (isUnboundName name) ]
3720 -- Some of the role annots will be unbound;
3721 -- we don't wish to include these
3722
3723 emptyRoleAnnotEnv :: RoleAnnotEnv
3724 emptyRoleAnnotEnv = emptyNameEnv
3725
3726 lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn)
3727 lookupRoleAnnot = lookupNameEnv
3728
3729 getRoleAnnots :: [Name] -> RoleAnnotEnv
3730 -> ([LRoleAnnotDecl GhcRn], RoleAnnotEnv)
3731 getRoleAnnots bndrs role_env
3732 = ( mapMaybe (lookupRoleAnnot role_env) bndrs
3733 , delListFromNameEnv role_env bndrs )