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