2a2f05eea5a0e8ca37a6a912ac26ba77262d0c41
[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 | RecDataConPE -- Data constructor in a recursive loop
1111 -- See Note [Recursion and promoting data constructors] in TcTyClsDecls
1112 | NoDataKindsTC -- -XDataKinds not enabled (for a tycon)
1113 | NoDataKindsDC -- -XDataKinds not enabled (for a datacon)
1114
1115 instance Outputable TcTyThing where -- Debugging only
1116 ppr (AGlobal g) = ppr g
1117 ppr elt@(ATcId {}) = text "Identifier" <>
1118 brackets (ppr (tct_id elt) <> dcolon
1119 <> ppr (varType (tct_id elt)) <> comma
1120 <+> ppr (tct_info elt))
1121 ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
1122 <+> dcolon <+> ppr (varType tv)
1123 ppr (ATcTyCon tc) = text "ATcTyCon" <+> ppr tc <+> dcolon <+> ppr (tyConKind tc)
1124 ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
1125
1126 -- | IdBindingInfo describes how an Id is bound.
1127 --
1128 -- It is used for the following purposes:
1129 -- a) for static forms in TcExpr.checkClosedInStaticForm and
1130 -- b) to figure out when a nested binding can be generalised,
1131 -- in TcBinds.decideGeneralisationPlan.
1132 --
1133 data IdBindingInfo -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1134 = NotLetBound
1135 | ClosedLet
1136 | NonClosedLet
1137 RhsNames -- Used for (static e) checks only
1138 ClosedTypeId -- Used for generalisation checks
1139 -- and for (static e) checks
1140
1141 -- | IsGroupClosed describes a group of mutually-recursive bindings
1142 data IsGroupClosed
1143 = IsGroupClosed
1144 (NameEnv RhsNames) -- Free var info for the RHS of each binding in the goup
1145 -- Used only for (static e) checks
1146
1147 ClosedTypeId -- True <=> all the free vars of the group are
1148 -- imported or ClosedLet or
1149 -- NonClosedLet with ClosedTypeId=True.
1150 -- In particular, no tyvars, no NotLetBound
1151
1152 type RhsNames = NameSet -- Names of variables, mentioned on the RHS of
1153 -- a definition, that are not Global or ClosedLet
1154
1155 type ClosedTypeId = Bool
1156 -- See Note [Meaning of IdBindingInfo and ClosedTypeId]
1157
1158 {- Note [Meaning of IdBindingInfo]
1159 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1160 NotLetBound means that
1161 the Id is not let-bound (e.g. it is bound in a
1162 lambda-abstraction or in a case pattern)
1163
1164 ClosedLet means that
1165 - The Id is let-bound,
1166 - Any free term variables are also Global or ClosedLet
1167 - Its type has no free variables (NB: a top-level binding subject
1168 to the MR might have free vars in its type)
1169 These ClosedLets can definitely be floated to top level; and we
1170 may need to do so for static forms.
1171
1172 Property: ClosedLet
1173 is equivalent to
1174 NonClosedLet emptyNameSet True
1175
1176 (NonClosedLet (fvs::RhsNames) (cl::ClosedTypeId)) means that
1177 - The Id is let-bound
1178
1179 - The fvs::RhsNames contains the free names of the RHS,
1180 excluding Global and ClosedLet ones.
1181
1182 - For the ClosedTypeId field see Note [Bindings with closed types]
1183
1184 For (static e) to be valid, we need for every 'x' free in 'e',
1185 that x's binding is floatable to the top level. Specifically:
1186 * x's RhsNames must be empty
1187 * x's type has no free variables
1188 See Note [Grand plan for static forms] in StaticPtrTable.hs.
1189 This test is made in TcExpr.checkClosedInStaticForm.
1190 Actually knowing x's RhsNames (rather than just its emptiness
1191 or otherwise) is just so we can produce better error messages
1192
1193 Note [Bindings with closed types: ClosedTypeId]
1194 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1195 Consider
1196
1197 f x = let g ys = map not ys
1198 in ...
1199
1200 Can we generalise 'g' under the OutsideIn algorithm? Yes,
1201 because all g's free variables are top-level; that is they themselves
1202 have no free type variables, and it is the type variables in the
1203 environment that makes things tricky for OutsideIn generalisation.
1204
1205 Here's the invariant:
1206 If an Id has ClosedTypeId=True (in its IdBindingInfo), then
1207 the Id's type is /definitely/ closed (has no free type variables).
1208 Specifically,
1209 a) The Id's acutal type is closed (has no free tyvars)
1210 b) Either the Id has a (closed) user-supplied type signature
1211 or all its free variables are Global/ClosedLet
1212 or NonClosedLet with ClosedTypeId=True.
1213 In particular, none are NotLetBound.
1214
1215 Why is (b) needed? Consider
1216 \x. (x :: Int, let y = x+1 in ...)
1217 Initially x::alpha. If we happen to typecheck the 'let' before the
1218 (x::Int), y's type will have a free tyvar; but if the other way round
1219 it won't. So we treat any let-bound variable with a free
1220 non-let-bound variable as not ClosedTypeId, regardless of what the
1221 free vars of its type actually are.
1222
1223 But if it has a signature, all is well:
1224 \x. ...(let { y::Int; y = x+1 } in
1225 let { v = y+2 } in ...)...
1226 Here the signature on 'v' makes 'y' a ClosedTypeId, so we can
1227 generalise 'v'.
1228
1229 Note that:
1230
1231 * A top-level binding may not have ClosedTypeId=True, if it suffers
1232 from the MR
1233
1234 * A nested binding may be closed (eg 'g' in the example we started
1235 with). Indeed, that's the point; whether a function is defined at
1236 top level or nested is orthogonal to the question of whether or
1237 not it is closed.
1238
1239 * A binding may be non-closed because it mentions a lexically scoped
1240 *type variable* Eg
1241 f :: forall a. blah
1242 f x = let g y = ...(y::a)...
1243
1244 Under OutsideIn we are free to generalise an Id all of whose free
1245 variables have ClosedTypeId=True (or imported). This is an extension
1246 compared to the JFP paper on OutsideIn, which used "top-level" as a
1247 proxy for "closed". (It's not a good proxy anyway -- the MR can make
1248 a top-level binding with a free type variable.)
1249
1250 Note [Type variables in the type environment]
1251 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1252 The type environment has a binding for each lexically-scoped
1253 type variable that is in scope. For example
1254
1255 f :: forall a. a -> a
1256 f x = (x :: a)
1257
1258 g1 :: [a] -> a
1259 g1 (ys :: [b]) = head ys :: b
1260
1261 g2 :: [Int] -> Int
1262 g2 (ys :: [c]) = head ys :: c
1263
1264 * The forall'd variable 'a' in the signature scopes over f's RHS.
1265
1266 * The pattern-bound type variable 'b' in 'g1' scopes over g1's
1267 RHS; note that it is bound to a skolem 'a' which is not itself
1268 lexically in scope.
1269
1270 * The pattern-bound type variable 'c' in 'g2' is bound to
1271 Int; that is, pattern-bound type variables can stand for
1272 arbitrary types. (see
1273 GHC proposal #128 "Allow ScopedTypeVariables to refer to types"
1274 https://github.com/ghc-proposals/ghc-proposals/pull/128,
1275 and the paper
1276 "Type variables in patterns", Haskell Symposium 2018.
1277
1278
1279 This is implemented by the constructor
1280 ATyVar Name TcTyVar
1281 in the type environment.
1282
1283 * The Name is the name of the original, lexically scoped type
1284 variable
1285
1286 * The TcTyVar is sometimes a skolem (like in 'f'), and sometimes
1287 a unification variable (like in 'g1', 'g2'). We never zonk the
1288 type environment so in the latter case it always stays as a
1289 unification variable, although that variable may be later
1290 unified with a type (such as Int in 'g2').
1291 -}
1292
1293 instance Outputable IdBindingInfo where
1294 ppr NotLetBound = text "NotLetBound"
1295 ppr ClosedLet = text "TopLevelLet"
1296 ppr (NonClosedLet fvs closed_type) =
1297 text "TopLevelLet" <+> ppr fvs <+> ppr closed_type
1298
1299 instance Outputable PromotionErr where
1300 ppr ClassPE = text "ClassPE"
1301 ppr TyConPE = text "TyConPE"
1302 ppr PatSynPE = text "PatSynPE"
1303 ppr FamDataConPE = text "FamDataConPE"
1304 ppr (ConstrainedDataConPE pred) = text "ConstrainedDataConPE"
1305 <+> parens (ppr pred)
1306 ppr RecDataConPE = text "RecDataConPE"
1307 ppr NoDataKindsTC = text "NoDataKindsTC"
1308 ppr NoDataKindsDC = text "NoDataKindsDC"
1309
1310 pprTcTyThingCategory :: TcTyThing -> SDoc
1311 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
1312 pprTcTyThingCategory (ATyVar {}) = text "Type variable"
1313 pprTcTyThingCategory (ATcId {}) = text "Local identifier"
1314 pprTcTyThingCategory (ATcTyCon {}) = text "Local tycon"
1315 pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
1316
1317 pprPECategory :: PromotionErr -> SDoc
1318 pprPECategory ClassPE = text "Class"
1319 pprPECategory TyConPE = text "Type constructor"
1320 pprPECategory PatSynPE = text "Pattern synonym"
1321 pprPECategory FamDataConPE = text "Data constructor"
1322 pprPECategory ConstrainedDataConPE{} = text "Data constructor"
1323 pprPECategory RecDataConPE = text "Data constructor"
1324 pprPECategory NoDataKindsTC = text "Type constructor"
1325 pprPECategory NoDataKindsDC = text "Data constructor"
1326
1327 {-
1328 ************************************************************************
1329 * *
1330 Operations over ImportAvails
1331 * *
1332 ************************************************************************
1333 -}
1334
1335 -- | 'ImportAvails' summarises what was imported from where, irrespective of
1336 -- whether the imported things are actually used or not. It is used:
1337 --
1338 -- * when processing the export list,
1339 --
1340 -- * when constructing usage info for the interface file,
1341 --
1342 -- * to identify the list of directly imported modules for initialisation
1343 -- purposes and for optimised overlap checking of family instances,
1344 --
1345 -- * when figuring out what things are really unused
1346 --
1347 data ImportAvails
1348 = ImportAvails {
1349 imp_mods :: ImportedMods,
1350 -- = ModuleEnv [ImportedModsVal],
1351 -- ^ Domain is all directly-imported modules
1352 --
1353 -- See the documentation on ImportedModsVal in HscTypes for the
1354 -- meaning of the fields.
1355 --
1356 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
1357 -- because we might be importing modules of the same name from
1358 -- different packages. (currently not the case, but might be in the
1359 -- future).
1360
1361 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
1362 -- ^ Home-package modules needed by the module being compiled
1363 --
1364 -- It doesn't matter whether any of these dependencies
1365 -- are actually /used/ when compiling the module; they
1366 -- are listed if they are below it at all. For
1367 -- example, suppose M imports A which imports X. Then
1368 -- compiling M might not need to consult X.hi, but X
1369 -- is still listed in M's dependencies.
1370
1371 imp_dep_pkgs :: Set InstalledUnitId,
1372 -- ^ Packages needed by the module being compiled, whether directly,
1373 -- or via other modules in this package, or via modules imported
1374 -- from other packages.
1375
1376 imp_trust_pkgs :: Set InstalledUnitId,
1377 -- ^ This is strictly a subset of imp_dep_pkgs and records the
1378 -- packages the current module needs to trust for Safe Haskell
1379 -- compilation to succeed. A package is required to be trusted if
1380 -- we are dependent on a trustworthy module in that package.
1381 -- While perhaps making imp_dep_pkgs a tuple of (UnitId, Bool)
1382 -- where True for the bool indicates the package is required to be
1383 -- trusted is the more logical design, doing so complicates a lot
1384 -- of code not concerned with Safe Haskell.
1385 -- See Note [RnNames . Tracking Trust Transitively]
1386
1387 imp_trust_own_pkg :: Bool,
1388 -- ^ Do we require that our own package is trusted?
1389 -- This is to handle efficiently the case where a Safe module imports
1390 -- a Trustworthy module that resides in the same package as it.
1391 -- See Note [RnNames . Trust Own Package]
1392
1393 imp_orphs :: [Module],
1394 -- ^ Orphan modules below us in the import tree (and maybe including
1395 -- us for imported modules)
1396
1397 imp_finsts :: [Module]
1398 -- ^ Family instance modules below us in the import tree (and maybe
1399 -- including us for imported modules)
1400 }
1401
1402 mkModDeps :: [(ModuleName, IsBootInterface)]
1403 -> ModuleNameEnv (ModuleName, IsBootInterface)
1404 mkModDeps deps = foldl' add emptyUFM deps
1405 where
1406 add env elt@(m,_) = addToUFM env m elt
1407
1408 modDepsElts
1409 :: ModuleNameEnv (ModuleName, IsBootInterface)
1410 -> [(ModuleName, IsBootInterface)]
1411 modDepsElts = sort . nonDetEltsUFM
1412 -- It's OK to use nonDetEltsUFM here because sorting by module names
1413 -- restores determinism
1414
1415 emptyImportAvails :: ImportAvails
1416 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
1417 imp_dep_mods = emptyUFM,
1418 imp_dep_pkgs = S.empty,
1419 imp_trust_pkgs = S.empty,
1420 imp_trust_own_pkg = False,
1421 imp_orphs = [],
1422 imp_finsts = [] }
1423
1424 -- | Union two ImportAvails
1425 --
1426 -- This function is a key part of Import handling, basically
1427 -- for each import we create a separate ImportAvails structure
1428 -- and then union them all together with this function.
1429 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
1430 plusImportAvails
1431 (ImportAvails { imp_mods = mods1,
1432 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
1433 imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1434 imp_orphs = orphs1, imp_finsts = finsts1 })
1435 (ImportAvails { imp_mods = mods2,
1436 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
1437 imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1438 imp_orphs = orphs2, imp_finsts = finsts2 })
1439 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
1440 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
1441 imp_dep_pkgs = dpkgs1 `S.union` dpkgs2,
1442 imp_trust_pkgs = tpkgs1 `S.union` tpkgs2,
1443 imp_trust_own_pkg = tself1 || tself2,
1444 imp_orphs = orphs1 `unionLists` orphs2,
1445 imp_finsts = finsts1 `unionLists` finsts2 }
1446 where
1447 plus_mod_dep r1@(m1, boot1) r2@(m2, boot2)
1448 | ASSERT2( m1 == m2, (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
1449 boot1 = r2
1450 | otherwise = r1
1451 -- If either side can "see" a non-hi-boot interface, use that
1452 -- Reusing existing tuples saves 10% of allocations on test
1453 -- perf/compiler/MultiLayerModules
1454
1455 {-
1456 ************************************************************************
1457 * *
1458 \subsection{Where from}
1459 * *
1460 ************************************************************************
1461
1462 The @WhereFrom@ type controls where the renamer looks for an interface file
1463 -}
1464
1465 data WhereFrom
1466 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
1467 | ImportBySystem -- Non user import.
1468 | ImportByPlugin -- Importing a plugin;
1469 -- See Note [Care with plugin imports] in LoadIface
1470
1471 instance Outputable WhereFrom where
1472 ppr (ImportByUser is_boot) | is_boot = text "{- SOURCE -}"
1473 | otherwise = empty
1474 ppr ImportBySystem = text "{- SYSTEM -}"
1475 ppr ImportByPlugin = text "{- PLUGIN -}"
1476
1477
1478 {- *********************************************************************
1479 * *
1480 Type signatures
1481 * *
1482 ********************************************************************* -}
1483
1484 -- These data types need to be here only because
1485 -- TcSimplify uses them, and TcSimplify is fairly
1486 -- low down in the module hierarchy
1487
1488 type TcSigFun = Name -> Maybe TcSigInfo
1489
1490 data TcSigInfo = TcIdSig TcIdSigInfo
1491 | TcPatSynSig TcPatSynInfo
1492
1493 data TcIdSigInfo -- See Note [Complete and partial type signatures]
1494 = CompleteSig -- A complete signature with no wildcards,
1495 -- so the complete polymorphic type is known.
1496 { sig_bndr :: TcId -- The polymorphic Id with that type
1497
1498 , sig_ctxt :: UserTypeCtxt -- In the case of type-class default methods,
1499 -- the Name in the FunSigCtxt is not the same
1500 -- as the TcId; the former is 'op', while the
1501 -- latter is '$dmop' or some such
1502
1503 , sig_loc :: SrcSpan -- Location of the type signature
1504 }
1505
1506 | PartialSig -- A partial type signature (i.e. includes one or more
1507 -- wildcards). In this case it doesn't make sense to give
1508 -- the polymorphic Id, because we are going to /infer/ its
1509 -- type, so we can't make the polymorphic Id ab-initio
1510 { psig_name :: Name -- Name of the function; used when report wildcards
1511 , psig_hs_ty :: LHsSigWcType GhcRn -- The original partial signature in
1512 -- HsSyn form
1513 , sig_ctxt :: UserTypeCtxt
1514 , sig_loc :: SrcSpan -- Location of the type signature
1515 }
1516
1517
1518 {- Note [Complete and partial type signatures]
1519 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1520 A type signature is partial when it contains one or more wildcards
1521 (= type holes). The wildcard can either be:
1522 * A (type) wildcard occurring in sig_theta or sig_tau. These are
1523 stored in sig_wcs.
1524 f :: Bool -> _
1525 g :: Eq _a => _a -> _a -> Bool
1526 * Or an extra-constraints wildcard, stored in sig_cts:
1527 h :: (Num a, _) => a -> a
1528
1529 A type signature is a complete type signature when there are no
1530 wildcards in the type signature, i.e. iff sig_wcs is empty and
1531 sig_extra_cts is Nothing.
1532 -}
1533
1534 data TcIdSigInst
1535 = TISI { sig_inst_sig :: TcIdSigInfo
1536
1537 , sig_inst_skols :: [(Name, TcTyVar)]
1538 -- Instantiated type and kind variables, TyVarTvs
1539 -- The Name is the Name that the renamer chose;
1540 -- but the TcTyVar may come from instantiating
1541 -- the type and hence have a different unique.
1542 -- No need to keep track of whether they are truly lexically
1543 -- scoped because the renamer has named them uniquely
1544 -- See Note [Binding scoped type variables] in TcSigs
1545
1546 , sig_inst_theta :: TcThetaType
1547 -- Instantiated theta. In the case of a
1548 -- PartialSig, sig_theta does not include
1549 -- the extra-constraints wildcard
1550
1551 , sig_inst_tau :: TcSigmaType -- Instantiated tau
1552 -- See Note [sig_inst_tau may be polymorphic]
1553
1554 -- Relevant for partial signature only
1555 , sig_inst_wcs :: [(Name, TcTyVar)]
1556 -- Like sig_inst_skols, but for wildcards. The named
1557 -- wildcards scope over the binding, and hence their
1558 -- Names may appear in type signatures in the binding
1559
1560 , sig_inst_wcx :: Maybe TcType
1561 -- Extra-constraints wildcard to fill in, if any
1562 -- If this exists, it is surely of the form (meta_tv |> co)
1563 -- (where the co might be reflexive). This is filled in
1564 -- only from the return value of TcHsType.tcWildCardOcc
1565 }
1566
1567 {- Note [sig_inst_tau may be polymorphic]
1568 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1569 Note that "sig_inst_tau" might actually be a polymorphic type,
1570 if the original function had a signature like
1571 forall a. Eq a => forall b. Ord b => ....
1572 But that's ok: tcMatchesFun (called by tcRhs) can deal with that
1573 It happens, too! See Note [Polymorphic methods] in TcClassDcl.
1574
1575 Note [Wildcards in partial signatures]
1576 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1577 The wildcards in psig_wcs may stand for a type mentioning
1578 the universally-quantified tyvars of psig_ty
1579
1580 E.g. f :: forall a. _ -> a
1581 f x = x
1582 We get sig_inst_skols = [a]
1583 sig_inst_tau = _22 -> a
1584 sig_inst_wcs = [_22]
1585 and _22 in the end is unified with the type 'a'
1586
1587 Moreover the kind of a wildcard in sig_inst_wcs may mention
1588 the universally-quantified tyvars sig_inst_skols
1589 e.g. f :: t a -> t _
1590 Here we get
1591 sig_inst_skols = [k:*, (t::k ->*), (a::k)]
1592 sig_inst_tau = t a -> t _22
1593 sig_inst_wcs = [ _22::k ]
1594 -}
1595
1596 data TcPatSynInfo
1597 = TPSI {
1598 patsig_name :: Name,
1599 patsig_implicit_bndrs :: [TyVarBinder], -- Implicitly-bound kind vars (Inferred) and
1600 -- implicitly-bound type vars (Specified)
1601 -- See Note [The pattern-synonym signature splitting rule] in TcPatSyn
1602 patsig_univ_bndrs :: [TyVar], -- Bound by explicit user forall
1603 patsig_req :: TcThetaType,
1604 patsig_ex_bndrs :: [TyVar], -- Bound by explicit user forall
1605 patsig_prov :: TcThetaType,
1606 patsig_body_ty :: TcSigmaType
1607 }
1608
1609 instance Outputable TcSigInfo where
1610 ppr (TcIdSig idsi) = ppr idsi
1611 ppr (TcPatSynSig tpsi) = text "TcPatSynInfo" <+> ppr tpsi
1612
1613 instance Outputable TcIdSigInfo where
1614 ppr (CompleteSig { sig_bndr = bndr })
1615 = ppr bndr <+> dcolon <+> ppr (idType bndr)
1616 ppr (PartialSig { psig_name = name, psig_hs_ty = hs_ty })
1617 = text "psig" <+> ppr name <+> dcolon <+> ppr hs_ty
1618
1619 instance Outputable TcIdSigInst where
1620 ppr (TISI { sig_inst_sig = sig, sig_inst_skols = skols
1621 , sig_inst_theta = theta, sig_inst_tau = tau })
1622 = hang (ppr sig) 2 (vcat [ ppr skols, ppr theta <+> darrow <+> ppr tau ])
1623
1624 instance Outputable TcPatSynInfo where
1625 ppr (TPSI{ patsig_name = name}) = ppr name
1626
1627 isPartialSig :: TcIdSigInst -> Bool
1628 isPartialSig (TISI { sig_inst_sig = PartialSig {} }) = True
1629 isPartialSig _ = False
1630
1631 -- | No signature or a partial signature
1632 hasCompleteSig :: TcSigFun -> Name -> Bool
1633 hasCompleteSig sig_fn name
1634 = case sig_fn name of
1635 Just (TcIdSig (CompleteSig {})) -> True
1636 _ -> False
1637
1638
1639 {-
1640 ************************************************************************
1641 * *
1642 * Canonical constraints *
1643 * *
1644 * These are the constraints the low-level simplifier works with *
1645 * *
1646 ************************************************************************
1647 -}
1648
1649 -- The syntax of xi (ΞΎ) types:
1650 -- xi ::= a | T xis | xis -> xis | ... | forall a. tau
1651 -- Two important notes:
1652 -- (i) No type families, unless we are under a ForAll
1653 -- (ii) Note that xi types can contain unexpanded type synonyms;
1654 -- however, the (transitive) expansions of those type synonyms
1655 -- will not contain any type functions, unless we are under a ForAll.
1656 -- We enforce the structure of Xi types when we flatten (TcCanonical)
1657
1658 type Xi = Type -- In many comments, "xi" ranges over Xi
1659
1660 type Cts = Bag Ct
1661
1662 data Ct
1663 -- Atomic canonical constraints
1664 = CDictCan { -- e.g. Num xi
1665 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1666
1667 cc_class :: Class,
1668 cc_tyargs :: [Xi], -- cc_tyargs are function-free, hence Xi
1669
1670 cc_pend_sc :: Bool -- See Note [The superclass story] in TcCanonical
1671 -- True <=> (a) cc_class has superclasses
1672 -- (b) we have not (yet) added those
1673 -- superclasses as Givens
1674 }
1675
1676 | CIrredCan { -- These stand for yet-unusable predicates
1677 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1678 cc_insol :: Bool -- True <=> definitely an error, can never be solved
1679 -- False <=> might be soluble
1680
1681 -- For the might-be-soluble case, the ctev_pred of the evidence is
1682 -- of form (tv xi1 xi2 ... xin) with a tyvar at the head
1683 -- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
1684 -- or (F tys ~ ty) where the CFunEqCan kind invariant fails
1685 -- See Note [CIrredCan constraints]
1686
1687 -- The definitely-insoluble case is for things like
1688 -- Int ~ Bool tycons don't match
1689 -- a ~ [a] occurs check
1690 }
1691
1692 | CTyEqCan { -- tv ~ rhs
1693 -- Invariants:
1694 -- * See Note [Applying the inert substitution] in TcFlatten
1695 -- * tv not in tvs(rhs) (occurs check)
1696 -- * If tv is a TauTv, then rhs has no foralls
1697 -- (this avoids substituting a forall for the tyvar in other types)
1698 -- * tcTypeKind ty `tcEqKind` tcTypeKind tv; Note [Ct kind invariant]
1699 -- * rhs may have at most one top-level cast
1700 -- * rhs (perhaps under the one cast) is not necessarily function-free,
1701 -- but it has no top-level function.
1702 -- E.g. a ~ [F b] is fine
1703 -- but a ~ F b is not
1704 -- * If the equality is representational, rhs has no top-level newtype
1705 -- See Note [No top-level newtypes on RHS of representational
1706 -- equalities] in TcCanonical
1707 -- * If rhs (perhaps under the cast) is also a tv, then it is oriented
1708 -- to give best chance of
1709 -- unification happening; eg if rhs is touchable then lhs is too
1710 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1711 cc_tyvar :: TcTyVar,
1712 cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
1713 -- See invariants above
1714
1715 cc_eq_rel :: EqRel -- INVARIANT: cc_eq_rel = ctEvEqRel cc_ev
1716 }
1717
1718 | CFunEqCan { -- F xis ~ fsk
1719 -- Invariants:
1720 -- * isTypeFamilyTyCon cc_fun
1721 -- * tcTypeKind (F xis) = tyVarKind fsk; Note [Ct kind invariant]
1722 -- * always Nominal role
1723 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1724 cc_fun :: TyCon, -- A type function
1725
1726 cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
1727 -- Either under-saturated or exactly saturated
1728 -- *never* over-saturated (because if so
1729 -- we should have decomposed)
1730
1731 cc_fsk :: TcTyVar -- [G] always a FlatSkolTv
1732 -- [W], [WD], or [D] always a FlatMetaTv
1733 -- See Note [The flattening story] in TcFlatten
1734 }
1735
1736 | CNonCanonical { -- See Note [NonCanonical Semantics] in TcSMonad
1737 cc_ev :: CtEvidence
1738 }
1739
1740 | CHoleCan { -- See Note [Hole constraints]
1741 -- Treated as an "insoluble" constraint
1742 -- See Note [Insoluble constraints]
1743 cc_ev :: CtEvidence,
1744 cc_hole :: Hole
1745 }
1746
1747 | CQuantCan QCInst -- A quantified constraint
1748 -- NB: I expect to make more of the cases in Ct
1749 -- look like this, with the payload in an
1750 -- auxiliary type
1751
1752 ------------
1753 data QCInst -- A much simplified version of ClsInst
1754 -- See Note [Quantified constraints] in TcCanonical
1755 = QCI { qci_ev :: CtEvidence -- Always of type forall tvs. context => ty
1756 -- Always Given
1757 , qci_tvs :: [TcTyVar] -- The tvs
1758 , qci_pred :: TcPredType -- The ty
1759 , qci_pend_sc :: Bool -- Same as cc_pend_sc flag in CDictCan
1760 -- Invariant: True => qci_pred is a ClassPred
1761 }
1762
1763 instance Outputable QCInst where
1764 ppr (QCI { qci_ev = ev }) = ppr ev
1765
1766 ------------
1767 -- | An expression or type hole
1768 data Hole = ExprHole UnboundVar
1769 -- ^ Either an out-of-scope variable or a "true" hole in an
1770 -- expression (TypedHoles)
1771 | TypeHole OccName
1772 -- ^ A hole in a type (PartialTypeSignatures)
1773
1774 instance Outputable Hole where
1775 ppr (ExprHole ub) = ppr ub
1776 ppr (TypeHole occ) = text "TypeHole" <> parens (ppr occ)
1777
1778 holeOcc :: Hole -> OccName
1779 holeOcc (ExprHole uv) = unboundVarOcc uv
1780 holeOcc (TypeHole occ) = occ
1781
1782 {- Note [Hole constraints]
1783 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1784 CHoleCan constraints are used for two kinds of holes,
1785 distinguished by cc_hole:
1786
1787 * For holes in expressions (including variables not in scope)
1788 e.g. f x = g _ x
1789
1790 * For holes in type signatures
1791 e.g. f :: _ -> _
1792 f x = [x,True]
1793
1794 Note [CIrredCan constraints]
1795 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1796 CIrredCan constraints are used for constraints that are "stuck"
1797 - we can't solve them (yet)
1798 - we can't use them to solve other constraints
1799 - but they may become soluble if we substitute for some
1800 of the type variables in the constraint
1801
1802 Example 1: (c Int), where c :: * -> Constraint. We can't do anything
1803 with this yet, but if later c := Num, *then* we can solve it
1804
1805 Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
1806 We don't want to use this to substitute 'b' for 'a', in case
1807 'k' is subsequently unifed with (say) *->*, because then
1808 we'd have ill-kinded types floating about. Rather we want
1809 to defer using the equality altogether until 'k' get resolved.
1810
1811 Note [Ct/evidence invariant]
1812 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1813 If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
1814 of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
1815 ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
1816 This holds by construction; look at the unique place where CDictCan is
1817 built (in TcCanonical).
1818
1819 In contrast, the type of the evidence *term* (ctev_dest / ctev_evar) in
1820 the evidence may *not* be fully zonked; we are careful not to look at it
1821 during constraint solving. See Note [Evidence field of CtEvidence].
1822
1823 Note [Ct kind invariant]
1824 ~~~~~~~~~~~~~~~~~~~~~~~~
1825 CTyEqCan and CFunEqCan both require that the kind of the lhs matches the kind
1826 of the rhs. This is necessary because both constraints are used for substitutions
1827 during solving. If the kinds differed, then the substitution would take a well-kinded
1828 type to an ill-kinded one.
1829
1830 -}
1831
1832 mkNonCanonical :: CtEvidence -> Ct
1833 mkNonCanonical ev = CNonCanonical { cc_ev = ev }
1834
1835 mkNonCanonicalCt :: Ct -> Ct
1836 mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
1837
1838 mkIrredCt :: CtEvidence -> Ct
1839 mkIrredCt ev = CIrredCan { cc_ev = ev, cc_insol = False }
1840
1841 mkInsolubleCt :: CtEvidence -> Ct
1842 mkInsolubleCt ev = CIrredCan { cc_ev = ev, cc_insol = True }
1843
1844 mkGivens :: CtLoc -> [EvId] -> [Ct]
1845 mkGivens loc ev_ids
1846 = map mk ev_ids
1847 where
1848 mk ev_id = mkNonCanonical (CtGiven { ctev_evar = ev_id
1849 , ctev_pred = evVarPred ev_id
1850 , ctev_loc = loc })
1851
1852 ctEvidence :: Ct -> CtEvidence
1853 ctEvidence (CQuantCan (QCI { qci_ev = ev })) = ev
1854 ctEvidence ct = cc_ev ct
1855
1856 ctLoc :: Ct -> CtLoc
1857 ctLoc = ctEvLoc . ctEvidence
1858
1859 setCtLoc :: Ct -> CtLoc -> Ct
1860 setCtLoc ct loc = ct { cc_ev = (cc_ev ct) { ctev_loc = loc } }
1861
1862 ctOrigin :: Ct -> CtOrigin
1863 ctOrigin = ctLocOrigin . ctLoc
1864
1865 ctPred :: Ct -> PredType
1866 -- See Note [Ct/evidence invariant]
1867 ctPred ct = ctEvPred (ctEvidence ct)
1868
1869 ctEvId :: Ct -> EvVar
1870 -- The evidence Id for this Ct
1871 ctEvId ct = ctEvEvId (ctEvidence ct)
1872
1873 -- | Makes a new equality predicate with the same role as the given
1874 -- evidence.
1875 mkTcEqPredLikeEv :: CtEvidence -> TcType -> TcType -> TcType
1876 mkTcEqPredLikeEv ev
1877 = case predTypeEqRel pred of
1878 NomEq -> mkPrimEqPred
1879 ReprEq -> mkReprPrimEqPred
1880 where
1881 pred = ctEvPred ev
1882
1883 -- | Get the flavour of the given 'Ct'
1884 ctFlavour :: Ct -> CtFlavour
1885 ctFlavour = ctEvFlavour . ctEvidence
1886
1887 -- | Get the equality relation for the given 'Ct'
1888 ctEqRel :: Ct -> EqRel
1889 ctEqRel = ctEvEqRel . ctEvidence
1890
1891 instance Outputable Ct where
1892 ppr ct = ppr (ctEvidence ct) <+> parens pp_sort
1893 where
1894 pp_sort = case ct of
1895 CTyEqCan {} -> text "CTyEqCan"
1896 CFunEqCan {} -> text "CFunEqCan"
1897 CNonCanonical {} -> text "CNonCanonical"
1898 CDictCan { cc_pend_sc = pend_sc }
1899 | pend_sc -> text "CDictCan(psc)"
1900 | otherwise -> text "CDictCan"
1901 CIrredCan { cc_insol = insol }
1902 | insol -> text "CIrredCan(insol)"
1903 | otherwise -> text "CIrredCan(sol)"
1904 CHoleCan { cc_hole = hole } -> text "CHoleCan:" <+> ppr hole
1905 CQuantCan (QCI { qci_pend_sc = pend_sc })
1906 | pend_sc -> text "CQuantCan(psc)"
1907 | otherwise -> text "CQuantCan"
1908
1909 {-
1910 ************************************************************************
1911 * *
1912 Simple functions over evidence variables
1913 * *
1914 ************************************************************************
1915 -}
1916
1917 ---------------- Getting free tyvars -------------------------
1918
1919 -- | Returns free variables of constraints as a non-deterministic set
1920 tyCoVarsOfCt :: Ct -> TcTyCoVarSet
1921 tyCoVarsOfCt = fvVarSet . tyCoFVsOfCt
1922
1923 -- | Returns free variables of constraints as a deterministically ordered.
1924 -- list. See Note [Deterministic FV] in FV.
1925 tyCoVarsOfCtList :: Ct -> [TcTyCoVar]
1926 tyCoVarsOfCtList = fvVarList . tyCoFVsOfCt
1927
1928 -- | Returns free variables of constraints as a composable FV computation.
1929 -- See Note [Deterministic FV] in FV.
1930 tyCoFVsOfCt :: Ct -> FV
1931 tyCoFVsOfCt (CTyEqCan { cc_tyvar = tv, cc_rhs = xi })
1932 = tyCoFVsOfType xi `unionFV` FV.unitFV tv
1933 `unionFV` tyCoFVsOfType (tyVarKind tv)
1934 tyCoFVsOfCt (CFunEqCan { cc_tyargs = tys, cc_fsk = fsk })
1935 = tyCoFVsOfTypes tys `unionFV` FV.unitFV fsk
1936 `unionFV` tyCoFVsOfType (tyVarKind fsk)
1937 tyCoFVsOfCt (CDictCan { cc_tyargs = tys }) = tyCoFVsOfTypes tys
1938 tyCoFVsOfCt ct = tyCoFVsOfType (ctPred ct)
1939
1940 -- | Returns free variables of a bag of constraints as a non-deterministic
1941 -- set. See Note [Deterministic FV] in FV.
1942 tyCoVarsOfCts :: Cts -> TcTyCoVarSet
1943 tyCoVarsOfCts = fvVarSet . tyCoFVsOfCts
1944
1945 -- | Returns free variables of a bag of constraints as a deterministically
1946 -- odered list. See Note [Deterministic FV] in FV.
1947 tyCoVarsOfCtsList :: Cts -> [TcTyCoVar]
1948 tyCoVarsOfCtsList = fvVarList . tyCoFVsOfCts
1949
1950 -- | Returns free variables of a bag of constraints as a composable FV
1951 -- computation. See Note [Deterministic FV] in FV.
1952 tyCoFVsOfCts :: Cts -> FV
1953 tyCoFVsOfCts = foldrBag (unionFV . tyCoFVsOfCt) emptyFV
1954
1955 -- | Returns free variables of WantedConstraints as a non-deterministic
1956 -- set. See Note [Deterministic FV] in FV.
1957 tyCoVarsOfWC :: WantedConstraints -> TyCoVarSet
1958 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1959 tyCoVarsOfWC = fvVarSet . tyCoFVsOfWC
1960
1961 -- | Returns free variables of WantedConstraints as a deterministically
1962 -- ordered list. See Note [Deterministic FV] in FV.
1963 tyCoVarsOfWCList :: WantedConstraints -> [TyCoVar]
1964 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1965 tyCoVarsOfWCList = fvVarList . tyCoFVsOfWC
1966
1967 -- | Returns free variables of WantedConstraints as a composable FV
1968 -- computation. See Note [Deterministic FV] in FV.
1969 tyCoFVsOfWC :: WantedConstraints -> FV
1970 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1971 tyCoFVsOfWC (WC { wc_simple = simple, wc_impl = implic })
1972 = tyCoFVsOfCts simple `unionFV`
1973 tyCoFVsOfBag tyCoFVsOfImplic implic
1974
1975 -- | Returns free variables of Implication as a composable FV computation.
1976 -- See Note [Deterministic FV] in FV.
1977 tyCoFVsOfImplic :: Implication -> FV
1978 -- Only called on *zonked* things, hence no need to worry about flatten-skolems
1979 tyCoFVsOfImplic (Implic { ic_skols = skols
1980 , ic_given = givens
1981 , ic_wanted = wanted })
1982 | isEmptyWC wanted
1983 = emptyFV
1984 | otherwise
1985 = tyCoFVsVarBndrs skols $
1986 tyCoFVsVarBndrs givens $
1987 tyCoFVsOfWC wanted
1988
1989 tyCoFVsOfBag :: (a -> FV) -> Bag a -> FV
1990 tyCoFVsOfBag tvs_of = foldrBag (unionFV . tvs_of) emptyFV
1991
1992 ---------------------------
1993 dropDerivedWC :: WantedConstraints -> WantedConstraints
1994 -- See Note [Dropping derived constraints]
1995 dropDerivedWC wc@(WC { wc_simple = simples })
1996 = wc { wc_simple = dropDerivedSimples simples }
1997 -- The wc_impl implications are already (recursively) filtered
1998
1999 --------------------------
2000 dropDerivedSimples :: Cts -> Cts
2001 -- Drop all Derived constraints, but make [W] back into [WD],
2002 -- so that if we re-simplify these constraints we will get all
2003 -- the right derived constraints re-generated. Forgetting this
2004 -- step led to #12936
2005 dropDerivedSimples simples = mapMaybeBag dropDerivedCt simples
2006
2007 dropDerivedCt :: Ct -> Maybe Ct
2008 dropDerivedCt ct
2009 = case ctEvFlavour ev of
2010 Wanted WOnly -> Just (ct' { cc_ev = ev_wd })
2011 Wanted _ -> Just ct'
2012 _ | isDroppableCt ct -> Nothing
2013 | otherwise -> Just ct
2014 where
2015 ev = ctEvidence ct
2016 ev_wd = ev { ctev_nosh = WDeriv }
2017 ct' = setPendingScDict ct -- See Note [Resetting cc_pend_sc]
2018
2019 {- Note [Resetting cc_pend_sc]
2020 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
2021 When we discard Derived constraints, in dropDerivedSimples, we must
2022 set the cc_pend_sc flag to True, so that if we re-process this
2023 CDictCan we will re-generate its derived superclasses. Otherwise
2024 we might miss some fundeps. #13662 showed this up.
2025
2026 See Note [The superclass story] in TcCanonical.
2027 -}
2028
2029 isDroppableCt :: Ct -> Bool
2030 isDroppableCt ct
2031 = isDerived ev && not keep_deriv
2032 -- Drop only derived constraints, and then only if they
2033 -- obey Note [Dropping derived constraints]
2034 where
2035 ev = ctEvidence ct
2036 loc = ctEvLoc ev
2037 orig = ctLocOrigin loc
2038
2039 keep_deriv
2040 = case ct of
2041 CHoleCan {} -> True
2042 CIrredCan { cc_insol = insoluble }
2043 -> keep_eq insoluble
2044 _ -> keep_eq False
2045
2046 keep_eq definitely_insoluble
2047 | isGivenOrigin orig -- Arising only from givens
2048 = definitely_insoluble -- Keep only definitely insoluble
2049 | otherwise
2050 = case orig of
2051 KindEqOrigin {} -> True -- See Note [Dropping derived constraints]
2052
2053 -- See Note [Dropping derived constraints]
2054 -- For fundeps, drop wanted/wanted interactions
2055 FunDepOrigin2 {} -> True -- Top-level/Wanted
2056 FunDepOrigin1 _ loc1 _ loc2
2057 | g1 || g2 -> True -- Given/Wanted errors: keep all
2058 | otherwise -> False -- Wanted/Wanted errors: discard
2059 where
2060 g1 = isGivenLoc loc1
2061 g2 = isGivenLoc loc2
2062
2063 _ -> False
2064
2065 arisesFromGivens :: Ct -> Bool
2066 arisesFromGivens ct
2067 = case ctEvidence ct of
2068 CtGiven {} -> True
2069 CtWanted {} -> False
2070 CtDerived { ctev_loc = loc } -> isGivenLoc loc
2071
2072 isGivenLoc :: CtLoc -> Bool
2073 isGivenLoc loc = isGivenOrigin (ctLocOrigin loc)
2074
2075 isGivenOrigin :: CtOrigin -> Bool
2076 isGivenOrigin (GivenOrigin {}) = True
2077 isGivenOrigin (FunDepOrigin1 _ l1 _ l2) = isGivenLoc l1 && isGivenLoc l2
2078 isGivenOrigin (FunDepOrigin2 _ o1 _ _) = isGivenOrigin o1
2079 isGivenOrigin _ = False
2080
2081 {- Note [Dropping derived constraints]
2082 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2083 In general we discard derived constraints at the end of constraint solving;
2084 see dropDerivedWC. For example
2085
2086 * Superclasses: if we have an unsolved [W] (Ord a), we don't want to
2087 complain about an unsolved [D] (Eq a) as well.
2088
2089 * If we have [W] a ~ Int, [W] a ~ Bool, improvement will generate
2090 [D] Int ~ Bool, and we don't want to report that because it's
2091 incomprehensible. That is why we don't rewrite wanteds with wanteds!
2092
2093 But (tiresomely) we do keep *some* Derived constraints:
2094
2095 * Type holes are derived constraints, because they have no evidence
2096 and we want to keep them, so we get the error report
2097
2098 * Insoluble kind equalities (e.g. [D] * ~ (* -> *)), with
2099 KindEqOrigin, may arise from a type equality a ~ Int#, say. See
2100 Note [Equalities with incompatible kinds] in TcCanonical.
2101 These need to be kept because the kind equalities might have different
2102 source locations and hence different error messages.
2103 E.g., test case dependent/should_fail/T11471
2104
2105 * We keep most derived equalities arising from functional dependencies
2106 - Given/Given interactions (subset of FunDepOrigin1):
2107 The definitely-insoluble ones reflect unreachable code.
2108
2109 Others not-definitely-insoluble ones like [D] a ~ Int do not
2110 reflect unreachable code; indeed if fundeps generated proofs, it'd
2111 be a useful equality. See #14763. So we discard them.
2112
2113 - Given/Wanted interacGiven or Wanted interacting with an
2114 instance declaration (FunDepOrigin2)
2115
2116 - Given/Wanted interactions (FunDepOrigin1); see #9612
2117
2118 - But for Wanted/Wanted interactions we do /not/ want to report an
2119 error (#13506). Consider [W] C Int Int, [W] C Int Bool, with
2120 a fundep on class C. We don't want to report an insoluble Int~Bool;
2121 c.f. "wanteds do not rewrite wanteds".
2122
2123 To distinguish these cases we use the CtOrigin.
2124
2125 NB: we keep *all* derived insolubles under some circumstances:
2126
2127 * They are looked at by simplifyInfer, to decide whether to
2128 generalise. Example: [W] a ~ Int, [W] a ~ Bool
2129 We get [D] Int ~ Bool, and indeed the constraints are insoluble,
2130 and we want simplifyInfer to see that, even though we don't
2131 ultimately want to generate an (inexplicable) error message from it
2132
2133
2134 ************************************************************************
2135 * *
2136 CtEvidence
2137 The "flavor" of a canonical constraint
2138 * *
2139 ************************************************************************
2140 -}
2141
2142 isWantedCt :: Ct -> Bool
2143 isWantedCt = isWanted . ctEvidence
2144
2145 isGivenCt :: Ct -> Bool
2146 isGivenCt = isGiven . ctEvidence
2147
2148 isDerivedCt :: Ct -> Bool
2149 isDerivedCt = isDerived . ctEvidence
2150
2151 isCTyEqCan :: Ct -> Bool
2152 isCTyEqCan (CTyEqCan {}) = True
2153 isCTyEqCan (CFunEqCan {}) = False
2154 isCTyEqCan _ = False
2155
2156 isCDictCan_Maybe :: Ct -> Maybe Class
2157 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
2158 isCDictCan_Maybe _ = Nothing
2159
2160 isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
2161 isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
2162 isCFunEqCan_maybe _ = Nothing
2163
2164 isCFunEqCan :: Ct -> Bool
2165 isCFunEqCan (CFunEqCan {}) = True
2166 isCFunEqCan _ = False
2167
2168 isCNonCanonical :: Ct -> Bool
2169 isCNonCanonical (CNonCanonical {}) = True
2170 isCNonCanonical _ = False
2171
2172 isHoleCt:: Ct -> Bool
2173 isHoleCt (CHoleCan {}) = True
2174 isHoleCt _ = False
2175
2176 isOutOfScopeCt :: Ct -> Bool
2177 -- We treat expression holes representing out-of-scope variables a bit
2178 -- differently when it comes to error reporting
2179 isOutOfScopeCt (CHoleCan { cc_hole = ExprHole (OutOfScope {}) }) = True
2180 isOutOfScopeCt _ = False
2181
2182 isExprHoleCt :: Ct -> Bool
2183 isExprHoleCt (CHoleCan { cc_hole = ExprHole {} }) = True
2184 isExprHoleCt _ = False
2185
2186 isTypeHoleCt :: Ct -> Bool
2187 isTypeHoleCt (CHoleCan { cc_hole = TypeHole {} }) = True
2188 isTypeHoleCt _ = False
2189
2190
2191 {- Note [Custom type errors in constraints]
2192 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2193
2194 When GHC reports a type-error about an unsolved-constraint, we check
2195 to see if the constraint contains any custom-type errors, and if so
2196 we report them. Here are some examples of constraints containing type
2197 errors:
2198
2199 TypeError msg -- The actual constraint is a type error
2200
2201 TypError msg ~ Int -- Some type was supposed to be Int, but ended up
2202 -- being a type error instead
2203
2204 Eq (TypeError msg) -- A class constraint is stuck due to a type error
2205
2206 F (TypeError msg) ~ a -- A type function failed to evaluate due to a type err
2207
2208 It is also possible to have constraints where the type error is nested deeper,
2209 for example see #11990, and also:
2210
2211 Eq (F (TypeError msg)) -- Here the type error is nested under a type-function
2212 -- call, which failed to evaluate because of it,
2213 -- and so the `Eq` constraint was unsolved.
2214 -- This may happen when one function calls another
2215 -- and the called function produced a custom type error.
2216 -}
2217
2218 -- | A constraint is considered to be a custom type error, if it contains
2219 -- custom type errors anywhere in it.
2220 -- See Note [Custom type errors in constraints]
2221 getUserTypeErrorMsg :: Ct -> Maybe Type
2222 getUserTypeErrorMsg ct = findUserTypeError (ctPred ct)
2223 where
2224 findUserTypeError t = msum ( userTypeError_maybe t
2225 : map findUserTypeError (subTys t)
2226 )
2227
2228 subTys t = case splitAppTys t of
2229 (t,[]) ->
2230 case splitTyConApp_maybe t of
2231 Nothing -> []
2232 Just (_,ts) -> ts
2233 (t,ts) -> t : ts
2234
2235
2236
2237
2238 isUserTypeErrorCt :: Ct -> Bool
2239 isUserTypeErrorCt ct = case getUserTypeErrorMsg ct of
2240 Just _ -> True
2241 _ -> False
2242
2243 isPendingScDict :: Ct -> Maybe Ct
2244 -- Says whether this is a CDictCan with cc_pend_sc is True,
2245 -- AND if so flips the flag
2246 isPendingScDict ct@(CDictCan { cc_pend_sc = True })
2247 = Just (ct { cc_pend_sc = False })
2248 isPendingScDict _ = Nothing
2249
2250 isPendingScInst :: QCInst -> Maybe QCInst
2251 -- Same as isPrendinScDict, but for QCInsts
2252 isPendingScInst qci@(QCI { qci_pend_sc = True })
2253 = Just (qci { qci_pend_sc = False })
2254 isPendingScInst _ = Nothing
2255
2256 setPendingScDict :: Ct -> Ct
2257 -- Set the cc_pend_sc flag to True
2258 setPendingScDict ct@(CDictCan { cc_pend_sc = False })
2259 = ct { cc_pend_sc = True }
2260 setPendingScDict ct = ct
2261
2262 superClassesMightHelp :: WantedConstraints -> Bool
2263 -- ^ True if taking superclasses of givens, or of wanteds (to perhaps
2264 -- expose more equalities or functional dependencies) might help to
2265 -- solve this constraint. See Note [When superclasses help]
2266 superClassesMightHelp (WC { wc_simple = simples, wc_impl = implics })
2267 = anyBag might_help_ct simples || anyBag might_help_implic implics
2268 where
2269 might_help_implic ic
2270 | IC_Unsolved <- ic_status ic = superClassesMightHelp (ic_wanted ic)
2271 | otherwise = False
2272
2273 might_help_ct ct = isWantedCt ct && not (is_ip ct)
2274
2275 is_ip (CDictCan { cc_class = cls }) = isIPClass cls
2276 is_ip _ = False
2277
2278 getPendingWantedScs :: Cts -> ([Ct], Cts)
2279 getPendingWantedScs simples
2280 = mapAccumBagL get [] simples
2281 where
2282 get acc ct | Just ct' <- isPendingScDict ct
2283 = (ct':acc, ct')
2284 | otherwise
2285 = (acc, ct)
2286
2287 {- Note [When superclasses help]
2288 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2289 First read Note [The superclass story] in TcCanonical.
2290
2291 We expand superclasses and iterate only if there is at unsolved wanted
2292 for which expansion of superclasses (e.g. from given constraints)
2293 might actually help. The function superClassesMightHelp tells if
2294 doing this superclass expansion might help solve this constraint.
2295 Note that
2296
2297 * We look inside implications; maybe it'll help to expand the Givens
2298 at level 2 to help solve an unsolved Wanted buried inside an
2299 implication. E.g.
2300 forall a. Ord a => forall b. [W] Eq a
2301
2302 * Superclasses help only for Wanted constraints. Derived constraints
2303 are not really "unsolved" and we certainly don't want them to
2304 trigger superclass expansion. This was a good part of the loop
2305 in #11523
2306
2307 * Even for Wanted constraints, we say "no" for implicit parameters.
2308 we have [W] ?x::ty, expanding superclasses won't help:
2309 - Superclasses can't be implicit parameters
2310 - If we have a [G] ?x:ty2, then we'll have another unsolved
2311 [D] ty ~ ty2 (from the functional dependency)
2312 which will trigger superclass expansion.
2313
2314 It's a bit of a special case, but it's easy to do. The runtime cost
2315 is low because the unsolved set is usually empty anyway (errors
2316 aside), and the first non-imlicit-parameter will terminate the search.
2317
2318 The special case is worth it (#11480, comment:2) because it
2319 applies to CallStack constraints, which aren't type errors. If we have
2320 f :: (C a) => blah
2321 f x = ...undefined...
2322 we'll get a CallStack constraint. If that's the only unsolved
2323 constraint it'll eventually be solved by defaulting. So we don't
2324 want to emit warnings about hitting the simplifier's iteration
2325 limit. A CallStack constraint really isn't an unsolved
2326 constraint; it can always be solved by defaulting.
2327 -}
2328
2329 singleCt :: Ct -> Cts
2330 singleCt = unitBag
2331
2332 andCts :: Cts -> Cts -> Cts
2333 andCts = unionBags
2334
2335 listToCts :: [Ct] -> Cts
2336 listToCts = listToBag
2337
2338 ctsElts :: Cts -> [Ct]
2339 ctsElts = bagToList
2340
2341 consCts :: Ct -> Cts -> Cts
2342 consCts = consBag
2343
2344 snocCts :: Cts -> Ct -> Cts
2345 snocCts = snocBag
2346
2347 extendCtsList :: Cts -> [Ct] -> Cts
2348 extendCtsList cts xs | null xs = cts
2349 | otherwise = cts `unionBags` listToBag xs
2350
2351 andManyCts :: [Cts] -> Cts
2352 andManyCts = unionManyBags
2353
2354 emptyCts :: Cts
2355 emptyCts = emptyBag
2356
2357 isEmptyCts :: Cts -> Bool
2358 isEmptyCts = isEmptyBag
2359
2360 pprCts :: Cts -> SDoc
2361 pprCts cts = vcat (map ppr (bagToList cts))
2362
2363 {-
2364 ************************************************************************
2365 * *
2366 Wanted constraints
2367 These are forced to be in TcRnTypes because
2368 TcLclEnv mentions WantedConstraints
2369 WantedConstraint mentions CtLoc
2370 CtLoc mentions ErrCtxt
2371 ErrCtxt mentions TcM
2372 * *
2373 v%************************************************************************
2374 -}
2375
2376 data WantedConstraints
2377 = WC { wc_simple :: Cts -- Unsolved constraints, all wanted
2378 , wc_impl :: Bag Implication
2379 }
2380
2381 emptyWC :: WantedConstraints
2382 emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag }
2383
2384 mkSimpleWC :: [CtEvidence] -> WantedConstraints
2385 mkSimpleWC cts
2386 = WC { wc_simple = listToBag (map mkNonCanonical cts)
2387 , wc_impl = emptyBag }
2388
2389 mkImplicWC :: Bag Implication -> WantedConstraints
2390 mkImplicWC implic
2391 = WC { wc_simple = emptyBag, wc_impl = implic }
2392
2393 isEmptyWC :: WantedConstraints -> Bool
2394 isEmptyWC (WC { wc_simple = f, wc_impl = i })
2395 = isEmptyBag f && isEmptyBag i
2396
2397
2398 -- | Checks whether a the given wanted constraints are solved, i.e.
2399 -- that there are no simple constraints left and all the implications
2400 -- are solved.
2401 isSolvedWC :: WantedConstraints -> Bool
2402 isSolvedWC WC {wc_simple = wc_simple, wc_impl = wc_impl} =
2403 isEmptyBag wc_simple && allBag (isSolvedStatus . ic_status) wc_impl
2404
2405 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
2406 andWC (WC { wc_simple = f1, wc_impl = i1 })
2407 (WC { wc_simple = f2, wc_impl = i2 })
2408 = WC { wc_simple = f1 `unionBags` f2
2409 , wc_impl = i1 `unionBags` i2 }
2410
2411 unionsWC :: [WantedConstraints] -> WantedConstraints
2412 unionsWC = foldr andWC emptyWC
2413
2414 addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
2415 addSimples wc cts
2416 = wc { wc_simple = wc_simple wc `unionBags` cts }
2417 -- Consider: Put the new constraints at the front, so they get solved first
2418
2419 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
2420 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
2421
2422 addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
2423 addInsols wc cts
2424 = wc { wc_simple = wc_simple wc `unionBags` cts }
2425
2426 insolublesOnly :: WantedConstraints -> WantedConstraints
2427 -- Keep only the definitely-insoluble constraints
2428 insolublesOnly (WC { wc_simple = simples, wc_impl = implics })
2429 = WC { wc_simple = filterBag insolubleCt simples
2430 , wc_impl = mapBag implic_insols_only implics }
2431 where
2432 implic_insols_only implic
2433 = implic { ic_wanted = insolublesOnly (ic_wanted implic) }
2434
2435 isSolvedStatus :: ImplicStatus -> Bool
2436 isSolvedStatus (IC_Solved {}) = True
2437 isSolvedStatus _ = False
2438
2439 isInsolubleStatus :: ImplicStatus -> Bool
2440 isInsolubleStatus IC_Insoluble = True
2441 isInsolubleStatus IC_BadTelescope = True
2442 isInsolubleStatus _ = False
2443
2444 insolubleImplic :: Implication -> Bool
2445 insolubleImplic ic = isInsolubleStatus (ic_status ic)
2446
2447 insolubleWC :: WantedConstraints -> Bool
2448 insolubleWC (WC { wc_impl = implics, wc_simple = simples })
2449 = anyBag insolubleCt simples
2450 || anyBag insolubleImplic implics
2451
2452 insolubleCt :: Ct -> Bool
2453 -- Definitely insoluble, in particular /excluding/ type-hole constraints
2454 -- Namely: a) an equality constraint
2455 -- b) that is insoluble
2456 -- c) and does not arise from a Given
2457 insolubleCt ct
2458 | isHoleCt ct = isOutOfScopeCt ct -- See Note [Insoluble holes]
2459 | not (insolubleEqCt ct) = False
2460 | arisesFromGivens ct = False -- See Note [Given insolubles]
2461 | otherwise = True
2462
2463 insolubleEqCt :: Ct -> Bool
2464 -- Returns True of /equality/ constraints
2465 -- that are /definitely/ insoluble
2466 -- It won't detect some definite errors like
2467 -- F a ~ T (F a)
2468 -- where F is a type family, which actually has an occurs check
2469 --
2470 -- The function is tuned for application /after/ constraint solving
2471 -- i.e. assuming canonicalisation has been done
2472 -- E.g. It'll reply True for a ~ [a]
2473 -- but False for [a] ~ a
2474 -- and
2475 -- True for Int ~ F a Int
2476 -- but False for Maybe Int ~ F a Int Int
2477 -- (where F is an arity-1 type function)
2478 insolubleEqCt (CIrredCan { cc_insol = insol }) = insol
2479 insolubleEqCt _ = False
2480
2481 instance Outputable WantedConstraints where
2482 ppr (WC {wc_simple = s, wc_impl = i})
2483 = text "WC" <+> braces (vcat
2484 [ ppr_bag (text "wc_simple") s
2485 , ppr_bag (text "wc_impl") i ])
2486
2487 ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
2488 ppr_bag doc bag
2489 | isEmptyBag bag = empty
2490 | otherwise = hang (doc <+> equals)
2491 2 (foldrBag (($$) . ppr) empty bag)
2492
2493 {- Note [Given insolubles]
2494 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2495 Consider (#14325, comment:)
2496 class (a~b) => C a b
2497
2498 foo :: C a c => a -> c
2499 foo x = x
2500
2501 hm3 :: C (f b) b => b -> f b
2502 hm3 x = foo x
2503
2504 In the RHS of hm3, from the [G] C (f b) b we get the insoluble
2505 [G] f b ~# b. Then we also get an unsolved [W] C b (f b).
2506 Residual implication looks like
2507 forall b. C (f b) b => [G] f b ~# b
2508 [W] C f (f b)
2509
2510 We do /not/ want to set the implication status to IC_Insoluble,
2511 because that'll suppress reports of [W] C b (f b). But we
2512 may not report the insoluble [G] f b ~# b either (see Note [Given errors]
2513 in TcErrors), so we may fail to report anything at all! Yikes.
2514
2515 The same applies to Derived constraints that /arise from/ Givens.
2516 E.g. f :: (C Int [a]) => blah
2517 where a fundep means we get
2518 [D] Int ~ [a]
2519 By the same reasoning we must not suppress other errors (#15767)
2520
2521 Bottom line: insolubleWC (called in TcSimplify.setImplicationStatus)
2522 should ignore givens even if they are insoluble.
2523
2524 Note [Insoluble holes]
2525 ~~~~~~~~~~~~~~~~~~~~~~
2526 Hole constraints that ARE NOT treated as truly insoluble:
2527 a) type holes, arising from PartialTypeSignatures,
2528 b) "true" expression holes arising from TypedHoles
2529
2530 An "expression hole" or "type hole" constraint isn't really an error
2531 at all; it's a report saying "_ :: Int" here. But an out-of-scope
2532 variable masquerading as expression holes IS treated as truly
2533 insoluble, so that it trumps other errors during error reporting.
2534 Yuk!
2535
2536 ************************************************************************
2537 * *
2538 Implication constraints
2539 * *
2540 ************************************************************************
2541 -}
2542
2543 data Implication
2544 = Implic { -- Invariants for a tree of implications:
2545 -- see TcType Note [TcLevel and untouchable type variables]
2546
2547 ic_tclvl :: TcLevel, -- TcLevel of unification variables
2548 -- allocated /inside/ this implication
2549
2550 ic_skols :: [TcTyVar], -- Introduced skolems
2551 ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
2552 -- See Note [Shadowing in a constraint]
2553 ic_telescope :: Maybe SDoc, -- User-written telescope, if there is one
2554 -- The list of skolems is order-checked
2555 -- if and only if this is a Just.
2556 -- See Note [Keeping scoped variables in order: Explicit]
2557 -- in TcHsType
2558
2559 ic_given :: [EvVar], -- Given evidence variables
2560 -- (order does not matter)
2561 -- See Invariant (GivenInv) in TcType
2562
2563 ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
2564 -- False <=> ic_givens might have equalities
2565
2566 ic_env :: Env TcGblEnv TcLclEnv,
2567 -- Records the Env at the time of creation.
2568 --
2569 -- This is primarly needed for the enclosed
2570 -- TcLclEnv, which gives the source location
2571 -- and error context for the implication, and
2572 -- hence for all the given evidence variables.
2573 --
2574 -- The enclosed DynFlags also influences error
2575 -- reporting. See Note [Avoid
2576 -- -Winaccessible-code when deriving] in
2577 -- TcInstDcls.
2578
2579 ic_wanted :: WantedConstraints, -- The wanteds
2580 -- See Invariang (WantedInf) in TcType
2581
2582 ic_binds :: EvBindsVar, -- Points to the place to fill in the
2583 -- abstraction and bindings.
2584
2585 -- The ic_need fields keep track of which Given evidence
2586 -- is used by this implication or its children
2587 -- NB: including stuff used by nested implications that have since
2588 -- been discarded
2589 ic_need_inner :: VarSet, -- Includes all used Given evidence
2590 ic_need_outer :: VarSet, -- Includes only the free Given evidence
2591 -- i.e. ic_need_inner after deleting
2592 -- (a) givens (b) binders of ic_binds
2593
2594 ic_status :: ImplicStatus
2595 }
2596
2597 -- | Create a new 'Implication' with as many sensible defaults for its fields
2598 -- as possible. Note that the 'ic_tclvl', 'ic_binds', and 'ic_info' fields do
2599 -- /not/ have sensible defaults, so they are initialized with lazy thunks that
2600 -- will 'panic' if forced, so one should take care to initialize these fields
2601 -- after creation.
2602 --
2603 -- This is monadic purely to look up the 'Env', which is used to initialize
2604 -- 'ic_env'.
2605 newImplication :: TcM Implication
2606 newImplication
2607 = do env <- getEnv
2608 return (implicationPrototype { ic_env = env })
2609
2610 implicationPrototype :: Implication
2611 implicationPrototype
2612 = Implic { -- These fields must be initialised
2613 ic_tclvl = panic "newImplic:tclvl"
2614 , ic_binds = panic "newImplic:binds"
2615 , ic_info = panic "newImplic:info"
2616 , ic_env = panic "newImplic:env"
2617
2618 -- The rest have sensible default values
2619 , ic_skols = []
2620 , ic_telescope = Nothing
2621 , ic_given = []
2622 , ic_wanted = emptyWC
2623 , ic_no_eqs = False
2624 , ic_status = IC_Unsolved
2625 , ic_need_inner = emptyVarSet
2626 , ic_need_outer = emptyVarSet }
2627
2628 -- | Retrieve the enclosed 'TcLclEnv' from an 'Implication'.
2629 implicLclEnv :: Implication -> TcLclEnv
2630 implicLclEnv = env_lcl . ic_env
2631
2632 -- | Retrieve the enclosed 'DynFlags' from an 'Implication'.
2633 implicDynFlags :: Implication -> DynFlags
2634 implicDynFlags = hsc_dflags . env_top . ic_env
2635
2636 data ImplicStatus
2637 = IC_Solved -- All wanteds in the tree are solved, all the way down
2638 { ics_dead :: [EvVar] } -- Subset of ic_given that are not needed
2639 -- See Note [Tracking redundant constraints] in TcSimplify
2640
2641 | IC_Insoluble -- At least one insoluble constraint in the tree
2642
2643 | IC_BadTelescope -- solved, but the skolems in the telescope are out of
2644 -- dependency order
2645
2646 | IC_Unsolved -- Neither of the above; might go either way
2647
2648 instance Outputable Implication where
2649 ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
2650 , ic_given = given, ic_no_eqs = no_eqs
2651 , ic_wanted = wanted, ic_status = status
2652 , ic_binds = binds
2653 , ic_need_inner = need_in, ic_need_outer = need_out
2654 , ic_info = info })
2655 = hang (text "Implic" <+> lbrace)
2656 2 (sep [ text "TcLevel =" <+> ppr tclvl
2657 , text "Skolems =" <+> pprTyVars skols
2658 , text "No-eqs =" <+> ppr no_eqs
2659 , text "Status =" <+> ppr status
2660 , hang (text "Given =") 2 (pprEvVars given)
2661 , hang (text "Wanted =") 2 (ppr wanted)
2662 , text "Binds =" <+> ppr binds
2663 , whenPprDebug (text "Needed inner =" <+> ppr need_in)
2664 , whenPprDebug (text "Needed outer =" <+> ppr need_out)
2665 , pprSkolInfo info ] <+> rbrace)
2666
2667 instance Outputable ImplicStatus where
2668 ppr IC_Insoluble = text "Insoluble"
2669 ppr IC_BadTelescope = text "Bad telescope"
2670 ppr IC_Unsolved = text "Unsolved"
2671 ppr (IC_Solved { ics_dead = dead })
2672 = text "Solved" <+> (braces (text "Dead givens =" <+> ppr dead))
2673
2674 {-
2675 Note [Needed evidence variables]
2676 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2677 Th ic_need_evs field holds the free vars of ic_binds, and all the
2678 ic_binds in nested implications.
2679
2680 * Main purpose: if one of the ic_givens is not mentioned in here, it
2681 is redundant.
2682
2683 * solveImplication may drop an implication altogether if it has no
2684 remaining 'wanteds'. But we still track the free vars of its
2685 evidence binds, even though it has now disappeared.
2686
2687 Note [Shadowing in a constraint]
2688 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2689 We assume NO SHADOWING in a constraint. Specifically
2690 * The unification variables are all implicitly quantified at top
2691 level, and are all unique
2692 * The skolem variables bound in ic_skols are all freah when the
2693 implication is created.
2694 So we can safely substitute. For example, if we have
2695 forall a. a~Int => ...(forall b. ...a...)...
2696 we can push the (a~Int) constraint inwards in the "givens" without
2697 worrying that 'b' might clash.
2698
2699 Note [Skolems in an implication]
2700 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2701 The skolems in an implication are not there to perform a skolem escape
2702 check. That happens because all the environment variables are in the
2703 untouchables, and therefore cannot be unified with anything at all,
2704 let alone the skolems.
2705
2706 Instead, ic_skols is used only when considering floating a constraint
2707 outside the implication in TcSimplify.floatEqualities or
2708 TcSimplify.approximateImplications
2709
2710 Note [Insoluble constraints]
2711 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2712 Some of the errors that we get during canonicalization are best
2713 reported when all constraints have been simplified as much as
2714 possible. For instance, assume that during simplification the
2715 following constraints arise:
2716
2717 [Wanted] F alpha ~ uf1
2718 [Wanted] beta ~ uf1 beta
2719
2720 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
2721 we will simply see a message:
2722 'Can't construct the infinite type beta ~ uf1 beta'
2723 and the user has no idea what the uf1 variable is.
2724
2725 Instead our plan is that we will NOT fail immediately, but:
2726 (1) Record the "frozen" error in the ic_insols field
2727 (2) Isolate the offending constraint from the rest of the inerts
2728 (3) Keep on simplifying/canonicalizing
2729
2730 At the end, we will hopefully have substituted uf1 := F alpha, and we
2731 will be able to report a more informative error:
2732 'Can't construct the infinite type beta ~ F alpha beta'
2733
2734 Insoluble constraints *do* include Derived constraints. For example,
2735 a functional dependency might give rise to [D] Int ~ Bool, and we must
2736 report that. If insolubles did not contain Deriveds, reportErrors would
2737 never see it.
2738
2739
2740 ************************************************************************
2741 * *
2742 Pretty printing
2743 * *
2744 ************************************************************************
2745 -}
2746
2747 pprEvVars :: [EvVar] -> SDoc -- Print with their types
2748 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
2749
2750 pprEvVarTheta :: [EvVar] -> SDoc
2751 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
2752
2753 pprEvVarWithType :: EvVar -> SDoc
2754 pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
2755
2756
2757
2758 -- | Wraps the given type with the constraints (via ic_given) in the given
2759 -- implication, according to the variables mentioned (via ic_skols)
2760 -- in the implication, but taking care to only wrap those variables
2761 -- that are mentioned in the type or the implication.
2762 wrapTypeWithImplication :: Type -> Implication -> Type
2763 wrapTypeWithImplication ty impl = wrapType ty mentioned_skols givens
2764 where givens = map idType $ ic_given impl
2765 skols = ic_skols impl
2766 freeVars = fvVarSet $ tyCoFVsOfTypes (ty:givens)
2767 mentioned_skols = filter (`elemVarSet` freeVars) skols
2768
2769 wrapType :: Type -> [TyVar] -> [PredType] -> Type
2770 wrapType ty skols givens = mkSpecForAllTys skols $ mkPhiTy givens ty
2771
2772
2773 {-
2774 ************************************************************************
2775 * *
2776 CtEvidence
2777 * *
2778 ************************************************************************
2779
2780 Note [Evidence field of CtEvidence]
2781 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2782 During constraint solving we never look at the type of ctev_evar/ctev_dest;
2783 instead we look at the ctev_pred field. The evtm/evar field
2784 may be un-zonked.
2785
2786 Note [Bind new Givens immediately]
2787 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2788 For Givens we make new EvVars and bind them immediately. Two main reasons:
2789 * Gain sharing. E.g. suppose we start with g :: C a b, where
2790 class D a => C a b
2791 class (E a, F a) => D a
2792 If we generate all g's superclasses as separate EvTerms we might
2793 get selD1 (selC1 g) :: E a
2794 selD2 (selC1 g) :: F a
2795 selC1 g :: D a
2796 which we could do more economically as:
2797 g1 :: D a = selC1 g
2798 g2 :: E a = selD1 g1
2799 g3 :: F a = selD2 g1
2800
2801 * For *coercion* evidence we *must* bind each given:
2802 class (a~b) => C a b where ....
2803 f :: C a b => ....
2804 Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
2805 But that superclass selector can't (yet) appear in a coercion
2806 (see evTermCoercion), so the easy thing is to bind it to an Id.
2807
2808 So a Given has EvVar inside it rather than (as previously) an EvTerm.
2809
2810 -}
2811
2812 -- | A place for type-checking evidence to go after it is generated.
2813 -- Wanted equalities are always HoleDest; other wanteds are always
2814 -- EvVarDest.
2815 data TcEvDest
2816 = EvVarDest EvVar -- ^ bind this var to the evidence
2817 -- EvVarDest is always used for non-type-equalities
2818 -- e.g. class constraints
2819
2820 | HoleDest CoercionHole -- ^ fill in this hole with the evidence
2821 -- HoleDest is always used for type-equalities
2822 -- See Note [Coercion holes] in TyCoRep
2823
2824 data CtEvidence
2825 = CtGiven -- Truly given, not depending on subgoals
2826 { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
2827 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
2828 , ctev_loc :: CtLoc }
2829
2830
2831 | CtWanted -- Wanted goal
2832 { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
2833 , ctev_dest :: TcEvDest
2834 , ctev_nosh :: ShadowInfo -- See Note [Constraint flavours]
2835 , ctev_loc :: CtLoc }
2836
2837 | CtDerived -- A goal that we don't really have to solve and can't
2838 -- immediately rewrite anything other than a derived
2839 -- (there's no evidence!) but if we do manage to solve
2840 -- it may help in solving other goals.
2841 { ctev_pred :: TcPredType
2842 , ctev_loc :: CtLoc }
2843
2844 ctEvPred :: CtEvidence -> TcPredType
2845 -- The predicate of a flavor
2846 ctEvPred = ctev_pred
2847
2848 ctEvLoc :: CtEvidence -> CtLoc
2849 ctEvLoc = ctev_loc
2850
2851 ctEvOrigin :: CtEvidence -> CtOrigin
2852 ctEvOrigin = ctLocOrigin . ctEvLoc
2853
2854 -- | Get the equality relation relevant for a 'CtEvidence'
2855 ctEvEqRel :: CtEvidence -> EqRel
2856 ctEvEqRel = predTypeEqRel . ctEvPred
2857
2858 -- | Get the role relevant for a 'CtEvidence'
2859 ctEvRole :: CtEvidence -> Role
2860 ctEvRole = eqRelRole . ctEvEqRel
2861
2862 ctEvTerm :: CtEvidence -> EvTerm
2863 ctEvTerm ev = EvExpr (ctEvExpr ev)
2864
2865 ctEvExpr :: CtEvidence -> EvExpr
2866 ctEvExpr ev@(CtWanted { ctev_dest = HoleDest _ })
2867 = Coercion $ ctEvCoercion ev
2868 ctEvExpr ev = evId (ctEvEvId ev)
2869
2870 ctEvCoercion :: HasDebugCallStack => CtEvidence -> Coercion
2871 ctEvCoercion (CtGiven { ctev_evar = ev_id })
2872 = mkTcCoVarCo ev_id
2873 ctEvCoercion (CtWanted { ctev_dest = dest })
2874 | HoleDest hole <- dest
2875 = -- ctEvCoercion is only called on type equalities
2876 -- and they always have HoleDests
2877 mkHoleCo hole
2878 ctEvCoercion ev
2879 = pprPanic "ctEvCoercion" (ppr ev)
2880
2881 ctEvEvId :: CtEvidence -> EvVar
2882 ctEvEvId (CtWanted { ctev_dest = EvVarDest ev }) = ev
2883 ctEvEvId (CtWanted { ctev_dest = HoleDest h }) = coHoleCoVar h
2884 ctEvEvId (CtGiven { ctev_evar = ev }) = ev
2885 ctEvEvId ctev@(CtDerived {}) = pprPanic "ctEvId:" (ppr ctev)
2886
2887 instance Outputable TcEvDest where
2888 ppr (HoleDest h) = text "hole" <> ppr h
2889 ppr (EvVarDest ev) = ppr ev
2890
2891 instance Outputable CtEvidence where
2892 ppr ev = ppr (ctEvFlavour ev)
2893 <+> pp_ev
2894 <+> braces (ppr (ctl_depth (ctEvLoc ev))) <> dcolon
2895 -- Show the sub-goal depth too
2896 <+> ppr (ctEvPred ev)
2897 where
2898 pp_ev = case ev of
2899 CtGiven { ctev_evar = v } -> ppr v
2900 CtWanted {ctev_dest = d } -> ppr d
2901 CtDerived {} -> text "_"
2902
2903 isWanted :: CtEvidence -> Bool
2904 isWanted (CtWanted {}) = True
2905 isWanted _ = False
2906
2907 isGiven :: CtEvidence -> Bool
2908 isGiven (CtGiven {}) = True
2909 isGiven _ = False
2910
2911 isDerived :: CtEvidence -> Bool
2912 isDerived (CtDerived {}) = True
2913 isDerived _ = False
2914
2915 {-
2916 %************************************************************************
2917 %* *
2918 CtFlavour
2919 %* *
2920 %************************************************************************
2921
2922 Note [Constraint flavours]
2923 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2924 Constraints come in four flavours:
2925
2926 * [G] Given: we have evidence
2927
2928 * [W] Wanted WOnly: we want evidence
2929
2930 * [D] Derived: any solution must satisfy this constraint, but
2931 we don't need evidence for it. Examples include:
2932 - superclasses of [W] class constraints
2933 - equalities arising from functional dependencies
2934 or injectivity
2935
2936 * [WD] Wanted WDeriv: a single constraint that represents
2937 both [W] and [D]
2938 We keep them paired as one both for efficiency, and because
2939 when we have a finite map F tys -> CFunEqCan, it's inconvenient
2940 to have two CFunEqCans in the range
2941
2942 The ctev_nosh field of a Wanted distinguishes between [W] and [WD]
2943
2944 Wanted constraints are born as [WD], but are split into [W] and its
2945 "shadow" [D] in TcSMonad.maybeEmitShadow.
2946
2947 See Note [The improvement story and derived shadows] in TcSMonad
2948 -}
2949
2950 data CtFlavour -- See Note [Constraint flavours]
2951 = Given
2952 | Wanted ShadowInfo
2953 | Derived
2954 deriving Eq
2955
2956 data ShadowInfo
2957 = WDeriv -- [WD] This Wanted constraint has no Derived shadow,
2958 -- so it behaves like a pair of a Wanted and a Derived
2959 | WOnly -- [W] It has a separate derived shadow
2960 -- See Note [Derived shadows]
2961 deriving( Eq )
2962
2963 isGivenOrWDeriv :: CtFlavour -> Bool
2964 isGivenOrWDeriv Given = True
2965 isGivenOrWDeriv (Wanted WDeriv) = True
2966 isGivenOrWDeriv _ = False
2967
2968 instance Outputable CtFlavour where
2969 ppr Given = text "[G]"
2970 ppr (Wanted WDeriv) = text "[WD]"
2971 ppr (Wanted WOnly) = text "[W]"
2972 ppr Derived = text "[D]"
2973
2974 ctEvFlavour :: CtEvidence -> CtFlavour
2975 ctEvFlavour (CtWanted { ctev_nosh = nosh }) = Wanted nosh
2976 ctEvFlavour (CtGiven {}) = Given
2977 ctEvFlavour (CtDerived {}) = Derived
2978
2979 -- | Whether or not one 'Ct' can rewrite another is determined by its
2980 -- flavour and its equality relation. See also
2981 -- Note [Flavours with roles] in TcSMonad
2982 type CtFlavourRole = (CtFlavour, EqRel)
2983
2984 -- | Extract the flavour, role, and boxity from a 'CtEvidence'
2985 ctEvFlavourRole :: CtEvidence -> CtFlavourRole
2986 ctEvFlavourRole ev = (ctEvFlavour ev, ctEvEqRel ev)
2987
2988 -- | Extract the flavour and role from a 'Ct'
2989 ctFlavourRole :: Ct -> CtFlavourRole
2990 -- Uses short-cuts to role for special cases
2991 ctFlavourRole (CDictCan { cc_ev = ev })
2992 = (ctEvFlavour ev, NomEq)
2993 ctFlavourRole (CTyEqCan { cc_ev = ev, cc_eq_rel = eq_rel })
2994 = (ctEvFlavour ev, eq_rel)
2995 ctFlavourRole (CFunEqCan { cc_ev = ev })
2996 = (ctEvFlavour ev, NomEq)
2997 ctFlavourRole (CHoleCan { cc_ev = ev })
2998 = (ctEvFlavour ev, NomEq) -- NomEq: CHoleCans can be rewritten by
2999 -- by nominal equalities but empahatically
3000 -- not by representational equalities
3001 ctFlavourRole ct
3002 = ctEvFlavourRole (ctEvidence ct)
3003
3004 {- Note [eqCanRewrite]
3005 ~~~~~~~~~~~~~~~~~~~~~~
3006 (eqCanRewrite ct1 ct2) holds if the constraint ct1 (a CTyEqCan of form
3007 tv ~ ty) can be used to rewrite ct2. It must satisfy the properties of
3008 a can-rewrite relation, see Definition [Can-rewrite relation] in
3009 TcSMonad.
3010
3011 With the solver handling Coercible constraints like equality constraints,
3012 the rewrite conditions must take role into account, never allowing
3013 a representational equality to rewrite a nominal one.
3014
3015 Note [Wanteds do not rewrite Wanteds]
3016 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3017 We don't allow Wanteds to rewrite Wanteds, because that can give rise
3018 to very confusing type error messages. A good example is #8450.
3019 Here's another
3020 f :: a -> Bool
3021 f x = ( [x,'c'], [x,True] ) `seq` True
3022 Here we get
3023 [W] a ~ Char
3024 [W] a ~ Bool
3025 but we do not want to complain about Bool ~ Char!
3026
3027 Note [Deriveds do rewrite Deriveds]
3028 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3029 However we DO allow Deriveds to rewrite Deriveds, because that's how
3030 improvement works; see Note [The improvement story] in TcInteract.
3031
3032 However, for now at least I'm only letting (Derived,NomEq) rewrite
3033 (Derived,NomEq) and not doing anything for ReprEq. If we have
3034 eqCanRewriteFR (Derived, NomEq) (Derived, _) = True
3035 then we lose property R2 of Definition [Can-rewrite relation]
3036 in TcSMonad
3037 R2. If f1 >= f, and f2 >= f,
3038 then either f1 >= f2 or f2 >= f1
3039 Consider f1 = (Given, ReprEq)
3040 f2 = (Derived, NomEq)
3041 f = (Derived, ReprEq)
3042
3043 I thought maybe we could never get Derived ReprEq constraints, but
3044 we can; straight from the Wanteds during improvement. And from a Derived
3045 ReprEq we could conceivably get a Derived NomEq improvement (by decomposing
3046 a type constructor with Nomninal role), and hence unify.
3047 -}
3048
3049 eqCanRewrite :: EqRel -> EqRel -> Bool
3050 eqCanRewrite NomEq _ = True
3051 eqCanRewrite ReprEq ReprEq = True
3052 eqCanRewrite ReprEq NomEq = False
3053
3054 eqCanRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
3055 -- Can fr1 actually rewrite fr2?
3056 -- Very important function!
3057 -- See Note [eqCanRewrite]
3058 -- See Note [Wanteds do not rewrite Wanteds]
3059 -- See Note [Deriveds do rewrite Deriveds]
3060 eqCanRewriteFR (Given, r1) (_, r2) = eqCanRewrite r1 r2
3061 eqCanRewriteFR (Wanted WDeriv, NomEq) (Derived, NomEq) = True
3062 eqCanRewriteFR (Derived, NomEq) (Derived, NomEq) = True
3063 eqCanRewriteFR _ _ = False
3064
3065 eqMayRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
3066 -- Is it /possible/ that fr1 can rewrite fr2?
3067 -- This is used when deciding which inerts to kick out,
3068 -- at which time a [WD] inert may be split into [W] and [D]
3069 eqMayRewriteFR (Wanted WDeriv, NomEq) (Wanted WDeriv, NomEq) = True
3070 eqMayRewriteFR (Derived, NomEq) (Wanted WDeriv, NomEq) = True
3071 eqMayRewriteFR fr1 fr2 = eqCanRewriteFR fr1 fr2
3072
3073 -----------------
3074 {- Note [funEqCanDischarge]
3075 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
3076 Suppose we have two CFunEqCans with the same LHS:
3077 (x1:F ts ~ f1) `funEqCanDischarge` (x2:F ts ~ f2)
3078 Can we drop x2 in favour of x1, either unifying
3079 f2 (if it's a flatten meta-var) or adding a new Given
3080 (f1 ~ f2), if x2 is a Given?
3081
3082 Answer: yes if funEqCanDischarge is true.
3083 -}
3084
3085 funEqCanDischarge
3086 :: CtEvidence -> CtEvidence
3087 -> ( SwapFlag -- NotSwapped => lhs can discharge rhs
3088 -- Swapped => rhs can discharge lhs
3089 , Bool) -- True <=> upgrade non-discharded one
3090 -- from [W] to [WD]
3091 -- See Note [funEqCanDischarge]
3092 funEqCanDischarge ev1 ev2
3093 = ASSERT2( ctEvEqRel ev1 == NomEq, ppr ev1 )
3094 ASSERT2( ctEvEqRel ev2 == NomEq, ppr ev2 )
3095 -- CFunEqCans are all Nominal, hence asserts
3096 funEqCanDischargeF (ctEvFlavour ev1) (ctEvFlavour ev2)
3097
3098 funEqCanDischargeF :: CtFlavour -> CtFlavour -> (SwapFlag, Bool)
3099 funEqCanDischargeF Given _ = (NotSwapped, False)
3100 funEqCanDischargeF _ Given = (IsSwapped, False)
3101 funEqCanDischargeF (Wanted WDeriv) _ = (NotSwapped, False)
3102 funEqCanDischargeF _ (Wanted WDeriv) = (IsSwapped, True)
3103 funEqCanDischargeF (Wanted WOnly) (Wanted WOnly) = (NotSwapped, False)
3104 funEqCanDischargeF (Wanted WOnly) Derived = (NotSwapped, True)
3105 funEqCanDischargeF Derived (Wanted WOnly) = (IsSwapped, True)
3106 funEqCanDischargeF Derived Derived = (NotSwapped, False)
3107
3108
3109 {- Note [eqCanDischarge]
3110 ~~~~~~~~~~~~~~~~~~~~~~~~
3111 Suppose we have two identical CTyEqCan equality constraints
3112 (i.e. both LHS and RHS are the same)
3113 (x1:a~t) `eqCanDischarge` (xs:a~t)
3114 Can we just drop x2 in favour of x1?
3115
3116 Answer: yes if eqCanDischarge is true.
3117
3118 Note that we do /not/ allow Wanted to discharge Derived.
3119 We must keep both. Why? Because the Derived may rewrite
3120 other Deriveds in the model whereas the Wanted cannot.
3121
3122 However a Wanted can certainly discharge an identical Wanted. So
3123 eqCanDischarge does /not/ define a can-rewrite relation in the
3124 sense of Definition [Can-rewrite relation] in TcSMonad.
3125
3126 We /do/ say that a [W] can discharge a [WD]. In evidence terms it
3127 certainly can, and the /caller/ arranges that the otherwise-lost [D]
3128 is spat out as a new Derived. -}
3129
3130 eqCanDischargeFR :: CtFlavourRole -> CtFlavourRole -> Bool
3131 -- See Note [eqCanDischarge]
3132 eqCanDischargeFR (f1,r1) (f2, r2) = eqCanRewrite r1 r2
3133 && eqCanDischargeF f1 f2
3134
3135 eqCanDischargeF :: CtFlavour -> CtFlavour -> Bool
3136 eqCanDischargeF Given _ = True
3137 eqCanDischargeF (Wanted _) (Wanted _) = True
3138 eqCanDischargeF (Wanted WDeriv) Derived = True
3139 eqCanDischargeF Derived Derived = True
3140 eqCanDischargeF _ _ = False
3141
3142
3143 {-
3144 ************************************************************************
3145 * *
3146 SubGoalDepth
3147 * *
3148 ************************************************************************
3149
3150 Note [SubGoalDepth]
3151 ~~~~~~~~~~~~~~~~~~~
3152 The 'SubGoalDepth' takes care of stopping the constraint solver from looping.
3153
3154 The counter starts at zero and increases. It includes dictionary constraints,
3155 equality simplification, and type family reduction. (Why combine these? Because
3156 it's actually quite easy to mistake one for another, in sufficiently involved
3157 scenarios, like ConstraintKinds.)
3158
3159 The flag -fcontext-stack=n (not very well named!) fixes the maximium
3160 level.
3161
3162 * The counter includes the depth of type class instance declarations. Example:
3163 [W] d{7} : Eq [Int]
3164 That is d's dictionary-constraint depth is 7. If we use the instance
3165 $dfEqList :: Eq a => Eq [a]
3166 to simplify it, we get
3167 d{7} = $dfEqList d'{8}
3168 where d'{8} : Eq Int, and d' has depth 8.
3169
3170 For civilised (decidable) instance declarations, each increase of
3171 depth removes a type constructor from the type, so the depth never
3172 gets big; i.e. is bounded by the structural depth of the type.
3173
3174 * The counter also increments when resolving
3175 equalities involving type functions. Example:
3176 Assume we have a wanted at depth 7:
3177 [W] d{7} : F () ~ a
3178 If there is a type function equation "F () = Int", this would be rewritten to
3179 [W] d{8} : Int ~ a
3180 and remembered as having depth 8.
3181
3182 Again, without UndecidableInstances, this counter is bounded, but without it
3183 can resolve things ad infinitum. Hence there is a maximum level.
3184
3185 * Lastly, every time an equality is rewritten, the counter increases. Again,
3186 rewriting an equality constraint normally makes progress, but it's possible
3187 the "progress" is just the reduction of an infinitely-reducing type family.
3188 Hence we need to track the rewrites.
3189
3190 When compiling a program requires a greater depth, then GHC recommends turning
3191 off this check entirely by setting -freduction-depth=0. This is because the
3192 exact number that works is highly variable, and is likely to change even between
3193 minor releases. Because this check is solely to prevent infinite compilation
3194 times, it seems safe to disable it when a user has ascertained that their program
3195 doesn't loop at the type level.
3196
3197 -}
3198
3199 -- | See Note [SubGoalDepth]
3200 newtype SubGoalDepth = SubGoalDepth Int
3201 deriving (Eq, Ord, Outputable)
3202
3203 initialSubGoalDepth :: SubGoalDepth
3204 initialSubGoalDepth = SubGoalDepth 0
3205
3206 bumpSubGoalDepth :: SubGoalDepth -> SubGoalDepth
3207 bumpSubGoalDepth (SubGoalDepth n) = SubGoalDepth (n + 1)
3208
3209 maxSubGoalDepth :: SubGoalDepth -> SubGoalDepth -> SubGoalDepth
3210 maxSubGoalDepth (SubGoalDepth n) (SubGoalDepth m) = SubGoalDepth (n `max` m)
3211
3212 subGoalDepthExceeded :: DynFlags -> SubGoalDepth -> Bool
3213 subGoalDepthExceeded dflags (SubGoalDepth d)
3214 = mkIntWithInf d > reductionDepth dflags
3215
3216 {-
3217 ************************************************************************
3218 * *
3219 CtLoc
3220 * *
3221 ************************************************************************
3222
3223 The 'CtLoc' gives information about where a constraint came from.
3224 This is important for decent error message reporting because
3225 dictionaries don't appear in the original source code.
3226 type will evolve...
3227
3228 -}
3229
3230 data CtLoc = CtLoc { ctl_origin :: CtOrigin
3231 , ctl_env :: TcLclEnv
3232 , ctl_t_or_k :: Maybe TypeOrKind -- OK if we're not sure
3233 , ctl_depth :: !SubGoalDepth }
3234
3235 -- The TcLclEnv includes particularly
3236 -- source location: tcl_loc :: RealSrcSpan
3237 -- context: tcl_ctxt :: [ErrCtxt]
3238 -- binder stack: tcl_bndrs :: TcBinderStack
3239 -- level: tcl_tclvl :: TcLevel
3240
3241 mkKindLoc :: TcType -> TcType -- original *types* being compared
3242 -> CtLoc -> CtLoc
3243 mkKindLoc s1 s2 loc = setCtLocOrigin (toKindLoc loc)
3244 (KindEqOrigin s1 (Just s2) (ctLocOrigin loc)
3245 (ctLocTypeOrKind_maybe loc))
3246
3247 -- | Take a CtLoc and moves it to the kind level
3248 toKindLoc :: CtLoc -> CtLoc
3249 toKindLoc loc = loc { ctl_t_or_k = Just KindLevel }
3250
3251 mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
3252 mkGivenLoc tclvl skol_info env
3253 = CtLoc { ctl_origin = GivenOrigin skol_info
3254 , ctl_env = env { tcl_tclvl = tclvl }
3255 , ctl_t_or_k = Nothing -- this only matters for error msgs
3256 , ctl_depth = initialSubGoalDepth }
3257
3258 ctLocEnv :: CtLoc -> TcLclEnv
3259 ctLocEnv = ctl_env
3260
3261 ctLocLevel :: CtLoc -> TcLevel
3262 ctLocLevel loc = tcl_tclvl (ctLocEnv loc)
3263
3264 ctLocDepth :: CtLoc -> SubGoalDepth
3265 ctLocDepth = ctl_depth
3266
3267 ctLocOrigin :: CtLoc -> CtOrigin
3268 ctLocOrigin = ctl_origin
3269
3270 ctLocSpan :: CtLoc -> RealSrcSpan
3271 ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
3272
3273 ctLocTypeOrKind_maybe :: CtLoc -> Maybe TypeOrKind
3274 ctLocTypeOrKind_maybe = ctl_t_or_k
3275
3276 setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
3277 setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
3278
3279 bumpCtLocDepth :: CtLoc -> CtLoc
3280 bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth d }
3281
3282 setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
3283 setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
3284
3285 updateCtLocOrigin :: CtLoc -> (CtOrigin -> CtOrigin) -> CtLoc
3286 updateCtLocOrigin ctl@(CtLoc { ctl_origin = orig }) upd
3287 = ctl { ctl_origin = upd orig }
3288
3289 setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
3290 setCtLocEnv ctl env = ctl { ctl_env = env }
3291
3292 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
3293 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
3294 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
3295
3296 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
3297 -- Just add information w/o updating the origin!
3298 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
3299 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
3300
3301 {-
3302 ************************************************************************
3303 * *
3304 SkolemInfo
3305 * *
3306 ************************************************************************
3307 -}
3308
3309 -- SkolemInfo gives the origin of *given* constraints
3310 -- a) type variables are skolemised
3311 -- b) an implication constraint is generated
3312 data SkolemInfo
3313 = SigSkol -- A skolem that is created by instantiating
3314 -- a programmer-supplied type signature
3315 -- Location of the binding site is on the TyVar
3316 -- See Note [SigSkol SkolemInfo]
3317 UserTypeCtxt -- What sort of signature
3318 TcType -- Original type signature (before skolemisation)
3319 [(Name,TcTyVar)] -- Maps the original name of the skolemised tyvar
3320 -- to its instantiated version
3321
3322 | SigTypeSkol UserTypeCtxt
3323 -- like SigSkol, but when we're kind-checking the *type*
3324 -- hence, we have less info
3325
3326 | ForAllSkol SDoc -- Bound by a user-written "forall".
3327
3328 | DerivSkol Type -- Bound by a 'deriving' clause;
3329 -- the type is the instance we are trying to derive
3330
3331 | InstSkol -- Bound at an instance decl
3332 | InstSC TypeSize -- A "given" constraint obtained by superclass selection.
3333 -- If (C ty1 .. tyn) is the largest class from
3334 -- which we made a superclass selection in the chain,
3335 -- then TypeSize = sizeTypes [ty1, .., tyn]
3336 -- See Note [Solving superclass constraints] in TcInstDcls
3337
3338 | FamInstSkol -- Bound at a family instance decl
3339 | PatSkol -- An existential type variable bound by a pattern for
3340 ConLike -- a data constructor with an existential type.
3341 (HsMatchContext Name)
3342 -- e.g. data T = forall a. Eq a => MkT a
3343 -- f (MkT x) = ...
3344 -- The pattern MkT x will allocate an existential type
3345 -- variable for 'a'.
3346
3347 | ArrowSkol -- An arrow form (see TcArrows)
3348
3349 | IPSkol [HsIPName] -- Binding site of an implicit parameter
3350
3351 | RuleSkol RuleName -- The LHS of a RULE
3352
3353 | InferSkol [(Name,TcType)]
3354 -- We have inferred a type for these (mutually-recursivive)
3355 -- polymorphic Ids, and are now checking that their RHS
3356 -- constraints are satisfied.
3357
3358 | BracketSkol -- Template Haskell bracket
3359
3360 | UnifyForAllSkol -- We are unifying two for-all types
3361 TcType -- The instantiated type *inside* the forall
3362
3363 | TyConSkol TyConFlavour Name -- bound in a type declaration of the given flavour
3364
3365 | DataConSkol Name -- bound as an existential in a Haskell98 datacon decl or
3366 -- as any variable in a GADT datacon decl
3367
3368 | ReifySkol -- Bound during Template Haskell reification
3369
3370 | QuantCtxtSkol -- Quantified context, e.g.
3371 -- f :: forall c. (forall a. c a => c [a]) => blah
3372
3373 | UnkSkol -- Unhelpful info (until I improve it)
3374
3375 instance Outputable SkolemInfo where
3376 ppr = pprSkolInfo
3377
3378 pprSkolInfo :: SkolemInfo -> SDoc
3379 -- Complete the sentence "is a rigid type variable bound by..."
3380 pprSkolInfo (SigSkol cx ty _) = pprSigSkolInfo cx ty
3381 pprSkolInfo (SigTypeSkol cx) = pprUserTypeCtxt cx
3382 pprSkolInfo (ForAllSkol doc) = quotes doc
3383 pprSkolInfo (IPSkol ips) = text "the implicit-parameter binding" <> plural ips <+> text "for"
3384 <+> pprWithCommas ppr ips
3385 pprSkolInfo (DerivSkol pred) = text "the deriving clause for" <+> quotes (ppr pred)
3386 pprSkolInfo InstSkol = text "the instance declaration"
3387 pprSkolInfo (InstSC n) = text "the instance declaration" <> whenPprDebug (parens (ppr n))
3388 pprSkolInfo FamInstSkol = text "a family instance declaration"
3389 pprSkolInfo BracketSkol = text "a Template Haskell bracket"
3390 pprSkolInfo (RuleSkol name) = text "the RULE" <+> pprRuleName name
3391 pprSkolInfo ArrowSkol = text "an arrow form"
3392 pprSkolInfo (PatSkol cl mc) = sep [ pprPatSkolInfo cl
3393 , text "in" <+> pprMatchContext mc ]
3394 pprSkolInfo (InferSkol ids) = hang (text "the inferred type" <> plural ids <+> text "of")
3395 2 (vcat [ ppr name <+> dcolon <+> ppr ty
3396 | (name,ty) <- ids ])
3397 pprSkolInfo (UnifyForAllSkol ty) = text "the type" <+> ppr ty
3398 pprSkolInfo (TyConSkol flav name) = text "the" <+> ppr flav <+> text "declaration for" <+> quotes (ppr name)
3399 pprSkolInfo (DataConSkol name)= text "the data constructor" <+> quotes (ppr name)
3400 pprSkolInfo ReifySkol = text "the type being reified"
3401
3402 pprSkolInfo (QuantCtxtSkol {}) = text "a quantified context"
3403
3404 -- UnkSkol
3405 -- For type variables the others are dealt with by pprSkolTvBinding.
3406 -- For Insts, these cases should not happen
3407 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) text "UnkSkol"
3408
3409 pprSigSkolInfo :: UserTypeCtxt -> TcType -> SDoc
3410 -- The type is already tidied
3411 pprSigSkolInfo ctxt ty
3412 = case ctxt of
3413 FunSigCtxt f _ -> vcat [ text "the type signature for:"
3414 , nest 2 (pprPrefixOcc f <+> dcolon <+> ppr ty) ]
3415 PatSynCtxt {} -> pprUserTypeCtxt ctxt -- See Note [Skolem info for pattern synonyms]
3416 _ -> vcat [ pprUserTypeCtxt ctxt <> colon
3417 , nest 2 (ppr ty) ]
3418
3419 pprPatSkolInfo :: ConLike -> SDoc
3420 pprPatSkolInfo (RealDataCon dc)
3421 = sep [ text "a pattern with constructor:"
3422 , nest 2 $ ppr dc <+> dcolon
3423 <+> pprType (dataConUserType dc) <> comma ]
3424 -- pprType prints forall's regardless of -fprint-explicit-foralls
3425 -- which is what we want here, since we might be saying
3426 -- type variable 't' is bound by ...
3427
3428 pprPatSkolInfo (PatSynCon ps)
3429 = sep [ text "a pattern with pattern synonym:"
3430 , nest 2 $ ppr ps <+> dcolon
3431 <+> pprPatSynType ps <> comma ]
3432
3433 {- Note [Skolem info for pattern synonyms]
3434 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3435 For pattern synonym SkolemInfo we have
3436 SigSkol (PatSynCtxt p) ty _
3437 but the type 'ty' is not very helpful. The full pattern-synonym type
3438 has the provided and required pieces, which it is inconvenient to
3439 record and display here. So we simply don't display the type at all,
3440 contenting outselves with just the name of the pattern synonym, which
3441 is fine. We could do more, but it doesn't seem worth it.
3442
3443 Note [SigSkol SkolemInfo]
3444 ~~~~~~~~~~~~~~~~~~~~~~~~~
3445 Suppose we (deeply) skolemise a type
3446 f :: forall a. a -> forall b. b -> a
3447 Then we'll instantiate [a :-> a', b :-> b'], and with the instantiated
3448 a' -> b' -> a.
3449 But when, in an error message, we report that "b is a rigid type
3450 variable bound by the type signature for f", we want to show the foralls
3451 in the right place. So we proceed as follows:
3452
3453 * In SigSkol we record
3454 - the original signature forall a. a -> forall b. b -> a
3455 - the instantiation mapping [a :-> a', b :-> b']
3456
3457 * Then when tidying in TcMType.tidySkolemInfo, we first tidy a' to
3458 whatever it tidies to, say a''; and then we walk over the type
3459 replacing the binder a by the tidied version a'', to give
3460 forall a''. a'' -> forall b''. b'' -> a''
3461 We need to do this under function arrows, to match what deeplySkolemise
3462 does.
3463
3464 * Typically a'' will have a nice pretty name like "a", but the point is
3465 that the foral-bound variables of the signature we report line up with
3466 the instantiated skolems lying around in other types.
3467
3468
3469 ************************************************************************
3470 * *
3471 CtOrigin
3472 * *
3473 ************************************************************************
3474 -}
3475
3476 data CtOrigin
3477 = GivenOrigin SkolemInfo
3478
3479 -- All the others are for *wanted* constraints
3480 | OccurrenceOf Name -- Occurrence of an overloaded identifier
3481 | OccurrenceOfRecSel RdrName -- Occurrence of a record selector
3482 | AppOrigin -- An application of some kind
3483
3484 | SpecPragOrigin UserTypeCtxt -- Specialisation pragma for
3485 -- function or instance
3486
3487 | TypeEqOrigin { uo_actual :: TcType
3488 , uo_expected :: TcType
3489 , uo_thing :: Maybe SDoc
3490 -- ^ The thing that has type "actual"
3491 , uo_visible :: Bool
3492 -- ^ Is at least one of the three elements above visible?
3493 -- (Errors from the polymorphic subsumption check are considered
3494 -- visible.) Only used for prioritizing error messages.
3495 }
3496
3497 | KindEqOrigin -- See Note [Equalities with incompatible kinds] in TcCanonical.
3498 TcType (Maybe TcType) -- A kind equality arising from unifying these two types
3499 CtOrigin -- originally arising from this
3500 (Maybe TypeOrKind) -- the level of the eq this arises from
3501
3502 | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
3503 | OverLabelOrigin FastString -- Occurrence of an overloaded label
3504
3505 | LiteralOrigin (HsOverLit GhcRn) -- Occurrence of a literal
3506 | NegateOrigin -- Occurrence of syntactic negation
3507
3508 | ArithSeqOrigin (ArithSeqInfo GhcRn) -- [x..], [x..y] etc
3509 | AssocFamPatOrigin -- When matching the patterns of an associated
3510 -- family instance with that of its parent class
3511 | SectionOrigin
3512 | TupleOrigin -- (..,..)
3513 | ExprSigOrigin -- e :: ty
3514 | PatSigOrigin -- p :: ty
3515 | PatOrigin -- Instantiating a polytyped pattern at a constructor
3516 | ProvCtxtOrigin -- The "provided" context of a pattern synonym signature
3517 (PatSynBind GhcRn GhcRn) -- Information about the pattern synonym, in
3518 -- particular the name and the right-hand side
3519 | RecordUpdOrigin
3520 | ViewPatOrigin
3521
3522 | ScOrigin TypeSize -- Typechecking superclasses of an instance declaration
3523 -- If the instance head is C ty1 .. tyn
3524 -- then TypeSize = sizeTypes [ty1, .., tyn]
3525 -- See Note [Solving superclass constraints] in TcInstDcls
3526
3527 | DerivClauseOrigin -- Typechecking a deriving clause (as opposed to
3528 -- standalone deriving).
3529 | DerivOriginDC DataCon Int Bool
3530 -- Checking constraints arising from this data con and field index. The
3531 -- Bool argument in DerivOriginDC and DerivOriginCoerce is True if
3532 -- standalong deriving (with a wildcard constraint) is being used. This
3533 -- is used to inform error messages on how to recommended fixes (e.g., if
3534 -- the argument is True, then don't recommend "use standalone deriving",
3535 -- but rather "fill in the wildcard constraint yourself").
3536 -- See Note [Inferring the instance context] in TcDerivInfer
3537 | DerivOriginCoerce Id Type Type Bool
3538 -- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
3539 -- `ty1` to `ty2`.
3540 | StandAloneDerivOrigin -- Typechecking stand-alone deriving. Useful for
3541 -- constraints coming from a wildcard constraint,
3542 -- e.g., deriving instance _ => Eq (Foo a)
3543 -- See Note [Inferring the instance context]
3544 -- in TcDerivInfer
3545 | DefaultOrigin -- Typechecking a default decl
3546 | DoOrigin -- Arising from a do expression
3547 | DoPatOrigin (LPat GhcRn) -- Arising from a failable pattern in
3548 -- a do expression
3549 | MCompOrigin -- Arising from a monad comprehension
3550 | MCompPatOrigin (LPat GhcRn) -- Arising from a failable pattern in a
3551 -- monad comprehension
3552 | IfOrigin -- Arising from an if statement
3553 | ProcOrigin -- Arising from a proc expression
3554 | AnnOrigin -- An annotation
3555
3556 | FunDepOrigin1 -- A functional dependency from combining
3557 PredType CtLoc -- This constraint arising from ...
3558 PredType CtLoc -- and this constraint arising from ...
3559
3560 | FunDepOrigin2 -- A functional dependency from combining
3561 PredType CtOrigin -- This constraint arising from ...
3562 PredType SrcSpan -- and this top-level instance
3563 -- We only need a CtOrigin on the first, because the location
3564 -- is pinned on the entire error message
3565
3566 | HoleOrigin
3567 | UnboundOccurrenceOf OccName
3568 | ListOrigin -- An overloaded list
3569 | StaticOrigin -- A static form
3570 | FailablePattern (LPat GhcTcId) -- A failable pattern in do-notation for the
3571 -- MonadFail Proposal (MFP). Obsolete when
3572 -- actual desugaring to MonadFail.fail is
3573 -- live.
3574 | Shouldn'tHappenOrigin String
3575 -- the user should never see this one,
3576 -- unless ImpredicativeTypes is on, where all
3577 -- bets are off
3578 | InstProvidedOrigin Module ClsInst
3579 -- Skolem variable arose when we were testing if an instance
3580 -- is solvable or not.
3581
3582 -- | Flag to see whether we're type-checking terms or kind-checking types
3583 data TypeOrKind = TypeLevel | KindLevel
3584 deriving Eq
3585
3586 instance Outputable TypeOrKind where
3587 ppr TypeLevel = text "TypeLevel"
3588 ppr KindLevel = text "KindLevel"
3589
3590 isTypeLevel :: TypeOrKind -> Bool
3591 isTypeLevel TypeLevel = True
3592 isTypeLevel KindLevel = False
3593
3594 isKindLevel :: TypeOrKind -> Bool
3595 isKindLevel TypeLevel = False
3596 isKindLevel KindLevel = True
3597
3598 -- An origin is visible if the place where the constraint arises is manifest
3599 -- in user code. Currently, all origins are visible except for invisible
3600 -- TypeEqOrigins. This is used when choosing which error of
3601 -- several to report
3602 isVisibleOrigin :: CtOrigin -> Bool
3603 isVisibleOrigin (TypeEqOrigin { uo_visible = vis }) = vis
3604 isVisibleOrigin (KindEqOrigin _ _ sub_orig _) = isVisibleOrigin sub_orig
3605 isVisibleOrigin _ = True
3606
3607 -- Converts a visible origin to an invisible one, if possible. Currently,
3608 -- this works only for TypeEqOrigin
3609 toInvisibleOrigin :: CtOrigin -> CtOrigin
3610 toInvisibleOrigin orig@(TypeEqOrigin {}) = orig { uo_visible = False }
3611 toInvisibleOrigin orig = orig
3612
3613 instance Outputable CtOrigin where
3614 ppr = pprCtOrigin
3615
3616 ctoHerald :: SDoc
3617 ctoHerald = text "arising from"
3618
3619 -- | Extract a suitable CtOrigin from a HsExpr
3620 lexprCtOrigin :: LHsExpr GhcRn -> CtOrigin
3621 lexprCtOrigin (L _ e) = exprCtOrigin e
3622
3623 exprCtOrigin :: HsExpr GhcRn -> CtOrigin
3624 exprCtOrigin (HsVar _ (L _ name)) = OccurrenceOf name
3625 exprCtOrigin (HsUnboundVar _ uv) = UnboundOccurrenceOf (unboundVarOcc uv)
3626 exprCtOrigin (HsConLikeOut {}) = panic "exprCtOrigin HsConLikeOut"
3627 exprCtOrigin (HsRecFld _ f) = OccurrenceOfRecSel (rdrNameAmbiguousFieldOcc f)
3628 exprCtOrigin (HsOverLabel _ _ l) = OverLabelOrigin l
3629 exprCtOrigin (HsIPVar _ ip) = IPOccOrigin ip
3630 exprCtOrigin (HsOverLit _ lit) = LiteralOrigin lit
3631 exprCtOrigin (HsLit {}) = Shouldn'tHappenOrigin "concrete literal"
3632 exprCtOrigin (HsLam _ matches) = matchesCtOrigin matches
3633 exprCtOrigin (HsLamCase _ ms) = matchesCtOrigin ms
3634 exprCtOrigin (HsApp _ e1 _) = lexprCtOrigin e1
3635 exprCtOrigin (HsAppType _ e1 _) = lexprCtOrigin e1
3636 exprCtOrigin (OpApp _ _ op _) = lexprCtOrigin op
3637 exprCtOrigin (NegApp _ e _) = lexprCtOrigin e
3638 exprCtOrigin (HsPar _ e) = lexprCtOrigin e
3639 exprCtOrigin (SectionL _ _ _) = SectionOrigin
3640 exprCtOrigin (SectionR _ _ _) = SectionOrigin
3641 exprCtOrigin (ExplicitTuple {}) = Shouldn'tHappenOrigin "explicit tuple"
3642 exprCtOrigin ExplicitSum{} = Shouldn'tHappenOrigin "explicit sum"
3643 exprCtOrigin (HsCase _ _ matches) = matchesCtOrigin matches
3644 exprCtOrigin (HsIf _ (Just syn) _ _ _) = exprCtOrigin (syn_expr syn)
3645 exprCtOrigin (HsIf {}) = Shouldn'tHappenOrigin "if expression"
3646 exprCtOrigin (HsMultiIf _ rhs) = lGRHSCtOrigin rhs
3647 exprCtOrigin (HsLet _ _ e) = lexprCtOrigin e
3648 exprCtOrigin (HsDo {}) = DoOrigin
3649 exprCtOrigin (ExplicitList {}) = Shouldn'tHappenOrigin "list"
3650 exprCtOrigin (RecordCon {}) = Shouldn'tHappenOrigin "record construction"
3651 exprCtOrigin (RecordUpd {}) = Shouldn'tHappenOrigin "record update"
3652 exprCtOrigin (ExprWithTySig {}) = ExprSigOrigin
3653 exprCtOrigin (ArithSeq {}) = Shouldn'tHappenOrigin "arithmetic sequence"
3654 exprCtOrigin (HsSCC _ _ _ e) = lexprCtOrigin e
3655 exprCtOrigin (HsCoreAnn _ _ _ e) = lexprCtOrigin e
3656 exprCtOrigin (HsBracket {}) = Shouldn'tHappenOrigin "TH bracket"
3657 exprCtOrigin (HsRnBracketOut {})= Shouldn'tHappenOrigin "HsRnBracketOut"
3658 exprCtOrigin (HsTcBracketOut {})= panic "exprCtOrigin HsTcBracketOut"
3659 exprCtOrigin (HsSpliceE {}) = Shouldn'tHappenOrigin "TH splice"
3660 exprCtOrigin (HsProc {}) = Shouldn'tHappenOrigin "proc"
3661 exprCtOrigin (HsStatic {}) = Shouldn'tHappenOrigin "static expression"
3662 exprCtOrigin (HsTick _ _ e) = lexprCtOrigin e
3663 exprCtOrigin (HsBinTick _ _ _ e) = lexprCtOrigin e
3664 exprCtOrigin (HsTickPragma _ _ _ _ e) = lexprCtOrigin e
3665 exprCtOrigin (EWildPat {}) = panic "exprCtOrigin EWildPat"
3666 exprCtOrigin (EAsPat {}) = panic "exprCtOrigin EAsPat"
3667 exprCtOrigin (EViewPat {}) = panic "exprCtOrigin EViewPat"
3668 exprCtOrigin (ELazyPat {}) = panic "exprCtOrigin ELazyPat"
3669 exprCtOrigin (HsWrap {}) = panic "exprCtOrigin HsWrap"
3670 exprCtOrigin (XExpr {}) = panic "exprCtOrigin XExpr"
3671
3672 -- | Extract a suitable CtOrigin from a MatchGroup
3673 matchesCtOrigin :: MatchGroup GhcRn (LHsExpr GhcRn) -> CtOrigin
3674 matchesCtOrigin (MG { mg_alts = alts })
3675 | L _ [L _ match] <- alts
3676 , Match { m_grhss = grhss } <- match
3677 = grhssCtOrigin grhss
3678
3679 | otherwise
3680 = Shouldn'tHappenOrigin "multi-way match"
3681 matchesCtOrigin (XMatchGroup{}) = panic "matchesCtOrigin"
3682
3683 -- | Extract a suitable CtOrigin from guarded RHSs
3684 grhssCtOrigin :: GRHSs GhcRn (LHsExpr GhcRn) -> CtOrigin
3685 grhssCtOrigin (GRHSs { grhssGRHSs = lgrhss }) = lGRHSCtOrigin lgrhss
3686 grhssCtOrigin (XGRHSs _) = panic "grhssCtOrigin"
3687
3688 -- | Extract a suitable CtOrigin from a list of guarded RHSs
3689 lGRHSCtOrigin :: [LGRHS GhcRn (LHsExpr GhcRn)] -> CtOrigin
3690 lGRHSCtOrigin [L _ (GRHS _ _ (L _ e))] = exprCtOrigin e
3691 lGRHSCtOrigin [L _ (XGRHS _)] = panic "lGRHSCtOrigin"
3692 lGRHSCtOrigin _ = Shouldn'tHappenOrigin "multi-way GRHS"
3693
3694 pprCtLoc :: CtLoc -> SDoc
3695 -- "arising from ... at ..."
3696 -- Not an instance of Outputable because of the "arising from" prefix
3697 pprCtLoc (CtLoc { ctl_origin = o, ctl_env = lcl})
3698 = sep [ pprCtOrigin o
3699 , text "at" <+> ppr (tcl_loc lcl)]
3700
3701 pprCtOrigin :: CtOrigin -> SDoc
3702 -- "arising from ..."
3703 -- Not an instance of Outputable because of the "arising from" prefix
3704 pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
3705
3706 pprCtOrigin (SpecPragOrigin ctxt)
3707 = case ctxt of
3708 FunSigCtxt n _ -> text "a SPECIALISE pragma for" <+> quotes (ppr n)
3709 SpecInstCtxt -> text "a SPECIALISE INSTANCE pragma"
3710 _ -> text "a SPECIALISE pragma" -- Never happens I think
3711
3712 pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
3713 = hang (ctoHerald <+> text "a functional dependency between constraints:")
3714 2 (vcat [ hang (quotes (ppr pred1)) 2 (pprCtLoc loc1)
3715 , hang (quotes (ppr pred2)) 2 (pprCtLoc loc2) ])
3716
3717 pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
3718 = hang (ctoHerald <+> text "a functional dependency between:")
3719 2 (vcat [ hang (text "constraint" <+> quotes (ppr pred1))
3720 2 (pprCtOrigin orig1 )
3721 , hang (text "instance" <+> quotes (ppr pred2))
3722 2 (text "at" <+> ppr loc2) ])
3723
3724 pprCtOrigin (KindEqOrigin t1 (Just t2) _ _)
3725 = hang (ctoHerald <+> text "a kind equality arising from")
3726 2 (sep [ppr t1, char '~', ppr t2])
3727
3728 pprCtOrigin AssocFamPatOrigin
3729 = text "when matching a family LHS with its class instance head"
3730
3731 pprCtOrigin (KindEqOrigin t1 Nothing _ _)
3732 = hang (ctoHerald <+> text "a kind equality when matching")
3733 2 (ppr t1)
3734
3735 pprCtOrigin (UnboundOccurrenceOf name)
3736 = ctoHerald <+> text "an undeclared identifier" <+> quotes (ppr name)
3737
3738 pprCtOrigin (DerivOriginDC dc n _)
3739 = hang (ctoHerald <+> text "the" <+> speakNth n
3740 <+> text "field of" <+> quotes (ppr dc))
3741 2 (parens (text "type" <+> quotes (ppr ty)))
3742 where
3743 ty = dataConOrigArgTys dc !! (n-1)
3744
3745 pprCtOrigin (DerivOriginCoerce meth ty1 ty2 _)
3746 = hang (ctoHerald <+> text "the coercion of the method" <+> quotes (ppr meth))
3747 2 (sep [ text "from type" <+> quotes (ppr ty1)
3748 , nest 2 $ text "to type" <+> quotes (ppr ty2) ])
3749
3750 pprCtOrigin (DoPatOrigin pat)
3751 = ctoHerald <+> text "a do statement"
3752 $$
3753 text "with the failable pattern" <+> quotes (ppr pat)
3754
3755 pprCtOrigin (MCompPatOrigin pat)
3756 = ctoHerald <+> hsep [ text "the failable pattern"
3757 , quotes (ppr pat)
3758 , text "in a statement in a monad comprehension" ]
3759 pprCtOrigin (FailablePattern pat)
3760 = ctoHerald <+> text "the failable pattern" <+> quotes (ppr pat)
3761 $$
3762 text "(this will become an error in a future GHC release)"
3763
3764 pprCtOrigin (Shouldn'tHappenOrigin note)
3765 = sdocWithDynFlags $ \dflags ->
3766 if xopt LangExt.ImpredicativeTypes dflags
3767 then text "a situation created by impredicative types"
3768 else
3769 vcat [ text "<< This should not appear in error messages. If you see this"
3770 , text "in an error message, please report a bug mentioning" <+> quotes (text note) <+> text "at"
3771 , text "https://gitlab.haskell.org/ghc/ghc/wikis/report-a-bug >>" ]
3772
3773 pprCtOrigin (ProvCtxtOrigin PSB{ psb_id = (L _ name) })
3774 = hang (ctoHerald <+> text "the \"provided\" constraints claimed by")
3775 2 (text "the signature of" <+> quotes (ppr name))
3776
3777 pprCtOrigin (InstProvidedOrigin mod cls_inst)
3778 = vcat [ text "arising when attempting to show that"
3779 , ppr cls_inst
3780 , text "is provided by" <+> quotes (ppr mod)]
3781
3782 pprCtOrigin simple_origin
3783 = ctoHerald <+> pprCtO simple_origin
3784
3785 -- | Short one-liners
3786 pprCtO :: CtOrigin -> SDoc
3787 pprCtO (OccurrenceOf name) = hsep [text "a use of", quotes (ppr name)]
3788 pprCtO (OccurrenceOfRecSel name) = hsep [text "a use of", quotes (ppr name)]
3789 pprCtO AppOrigin = text "an application"
3790 pprCtO (IPOccOrigin name) = hsep [text "a use of implicit parameter", quotes (ppr name)]
3791 pprCtO (OverLabelOrigin l) = hsep [text "the overloaded label"
3792 ,quotes (char '#' <> ppr l)]
3793 pprCtO RecordUpdOrigin = text "a record update"
3794 pprCtO ExprSigOrigin = text "an expression type signature"
3795 pprCtO PatSigOrigin = text "a pattern type signature"
3796 pprCtO PatOrigin = text "a pattern"
3797 pprCtO ViewPatOrigin = text "a view pattern"
3798 pprCtO IfOrigin = text "an if expression"
3799 pprCtO (LiteralOrigin lit) = hsep [text "the literal", quotes (ppr lit)]
3800 pprCtO (ArithSeqOrigin seq) = hsep [text "the arithmetic sequence", quotes (ppr seq)]
3801 pprCtO SectionOrigin = text "an operator section"
3802 pprCtO AssocFamPatOrigin = text "the LHS of a famly instance"
3803 pprCtO TupleOrigin = text "a tuple"
3804 pprCtO NegateOrigin = text "a use of syntactic negation"
3805 pprCtO (ScOrigin n) = text "the superclasses of an instance declaration"
3806 <> whenPprDebug (parens (ppr n))
3807 pprCtO DerivClauseOrigin = text "the 'deriving' clause of a data type declaration"
3808 pprCtO StandAloneDerivOrigin = text "a 'deriving' declaration"
3809 pprCtO DefaultOrigin = text "a 'default' declaration"
3810 pprCtO DoOrigin = text "a do statement"
3811 pprCtO MCompOrigin = text "a statement in a monad comprehension"
3812 pprCtO ProcOrigin = text "a proc expression"
3813 pprCtO (TypeEqOrigin t1 t2 _ _)= text "a type equality" <+> sep [ppr t1, char '~', ppr t2]
3814 pprCtO AnnOrigin = text "an annotation"
3815 pprCtO HoleOrigin = text "a use of" <+> quotes (text "_")
3816 pprCtO ListOrigin = text "an overloaded list"
3817 pprCtO StaticOrigin = text "a static form"
3818 pprCtO _ = panic "pprCtOrigin"
3819
3820 {-
3821 Constraint Solver Plugins
3822 -------------------------
3823 -}
3824
3825 type TcPluginSolver = [Ct] -- given
3826 -> [Ct] -- derived
3827 -> [Ct] -- wanted
3828 -> TcPluginM TcPluginResult
3829
3830 newtype TcPluginM a = TcPluginM (EvBindsVar -> TcM a)
3831
3832 instance Functor TcPluginM where
3833 fmap = liftM
3834
3835 instance Applicative TcPluginM where
3836 pure x = TcPluginM (const $ pure x)
3837 (<*>) = ap
3838
3839 instance Monad TcPluginM where
3840 #if !MIN_VERSION_base(4,13,0)
3841 fail = MonadFail.fail
3842 #endif
3843 TcPluginM m >>= k =
3844 TcPluginM (\ ev -> do a <- m ev
3845 runTcPluginM (k a) ev)
3846
3847 instance MonadFail.MonadFail TcPluginM where
3848 fail x = TcPluginM (const $ fail x)
3849
3850 runTcPluginM :: TcPluginM a -> EvBindsVar -> TcM a
3851 runTcPluginM (TcPluginM m) = m
3852
3853 -- | This function provides an escape for direct access to
3854 -- the 'TcM` monad. It should not be used lightly, and
3855 -- the provided 'TcPluginM' API should be favoured instead.
3856 unsafeTcPluginTcM :: TcM a -> TcPluginM a
3857 unsafeTcPluginTcM = TcPluginM . const
3858
3859 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
3860 -- constraint solving. Returns 'Nothing' if invoked during
3861 -- 'tcPluginInit' or 'tcPluginStop'.
3862 getEvBindsTcPluginM :: TcPluginM EvBindsVar
3863 getEvBindsTcPluginM = TcPluginM return
3864
3865
3866 data TcPlugin = forall s. TcPlugin
3867 { tcPluginInit :: TcPluginM s
3868 -- ^ Initialize plugin, when entering type-checker.
3869
3870 , tcPluginSolve :: s -> TcPluginSolver
3871 -- ^ Solve some constraints.
3872 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
3873
3874 , tcPluginStop :: s -> TcPluginM ()
3875 -- ^ Clean up after the plugin, when exiting the type-checker.
3876 }
3877
3878 data TcPluginResult
3879 = TcPluginContradiction [Ct]
3880 -- ^ The plugin found a contradiction.
3881 -- The returned constraints are removed from the inert set,
3882 -- and recorded as insoluble.
3883
3884 | TcPluginOk [(EvTerm,Ct)] [Ct]
3885 -- ^ The first field is for constraints that were solved.
3886 -- These are removed from the inert set,
3887 -- and the evidence for them is recorded.
3888 -- The second field contains new work, that should be processed by
3889 -- the constraint solver.
3890
3891 {- *********************************************************************
3892 * *
3893 Role annotations
3894 * *
3895 ********************************************************************* -}
3896
3897 type RoleAnnotEnv = NameEnv (LRoleAnnotDecl GhcRn)
3898
3899 mkRoleAnnotEnv :: [LRoleAnnotDecl GhcRn] -> RoleAnnotEnv
3900 mkRoleAnnotEnv role_annot_decls
3901 = mkNameEnv [ (name, ra_decl)
3902 | ra_decl <- role_annot_decls
3903 , let name = roleAnnotDeclName (unLoc ra_decl)
3904 , not (isUnboundName name) ]
3905 -- Some of the role annots will be unbound;
3906 -- we don't wish to include these
3907
3908 emptyRoleAnnotEnv :: RoleAnnotEnv
3909 emptyRoleAnnotEnv = emptyNameEnv
3910
3911 lookupRoleAnnot :: RoleAnnotEnv -> Name -> Maybe (LRoleAnnotDecl GhcRn)
3912 lookupRoleAnnot = lookupNameEnv
3913
3914 getRoleAnnots :: [Name] -> RoleAnnotEnv
3915 -> ([LRoleAnnotDecl GhcRn], RoleAnnotEnv)
3916 getRoleAnnots bndrs role_env
3917 = ( mapMaybe (lookupRoleAnnot role_env) bndrs
3918 , delListFromNameEnv role_env bndrs )