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