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