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