a70759fa7d5273c7525ef9961d9e6e0b75df4cc8
[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
21 module TcRnTypes(
22 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
23 TcRef,
24
25 -- The environment types
26 Env(..),
27 TcGblEnv(..), TcLclEnv(..),
28 IfGblEnv(..), IfLclEnv(..),
29
30 -- Renamer types
31 ErrCtxt, RecFieldEnv(..),
32 ImportAvails(..), emptyImportAvails, plusImportAvails,
33 WhereFrom(..), mkModDeps,
34
35 -- Typechecker types
36 TcTypeEnv, TcIdBinderStack, TcIdBinder(..),
37 TcTyThing(..), PromotionErr(..),
38 pprTcTyThingCategory, pprPECategory,
39
40 -- Desugaring types
41 DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
42 DsMetaEnv, DsMetaVal(..),
43
44 -- Template Haskell
45 ThStage(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage,
46 ThLevel, impLevel, outerLevel, thLevel,
47
48 -- Arrows
49 ArrowCtxt(..),
50
51 -- Canonical constraints
52 Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
53 singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
54 isEmptyCts, isCTyEqCan, isCFunEqCan,
55 isCDictCan_Maybe, isCFunEqCan_maybe,
56 isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
57 isGivenCt, isHoleCt, isExprHoleCt, isTypeHoleCt,
58 ctEvidence, ctLoc, ctPred, ctFlavour, ctEqRel,
59 mkNonCanonical, mkNonCanonicalCt,
60 ctEvPred, ctEvLoc, ctEvEqRel,
61 ctEvTerm, ctEvCoercion, ctEvId,
62
63 WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
64 andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
65 dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
66 insolubleImplic, trulyInsoluble,
67
68 Implication(..), ImplicStatus(..), isInsolubleStatus,
69 SubGoalDepth, initialSubGoalDepth,
70 bumpSubGoalDepth, subGoalDepthExceeded,
71 CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
72 ctLocDepth, bumpCtLocDepth,
73 setCtLocOrigin, setCtLocEnv, setCtLocSpan,
74 CtOrigin(..), pprCtOrigin,
75 pushErrCtxt, pushErrCtxtSameOrigin,
76
77 SkolemInfo(..),
78
79 CtEvidence(..),
80 mkGivenLoc,
81 isWanted, isGiven, isDerived,
82 ctEvRole,
83
84 -- Constraint solver plugins
85 TcPlugin(..), TcPluginResult(..), TcPluginSolver,
86 TcPluginM, runTcPluginM, unsafeTcPluginTcM,
87 getEvBindsTcPluginM_maybe,
88
89 CtFlavour(..), ctEvFlavour,
90
91 -- Pretty printing
92 pprEvVarTheta,
93 pprEvVars, pprEvVarWithType,
94 pprArising, pprArisingAt,
95
96 -- Misc other types
97 TcId, TcIdSet, HoleSort(..)
98
99 ) where
100
101 #include "HsVersions.h"
102
103 import HsSyn
104 import CoreSyn
105 import HscTypes
106 import TcEvidence
107 import Type
108 import CoAxiom ( Role )
109 import Class ( Class )
110 import TyCon ( TyCon )
111 import ConLike ( ConLike(..) )
112 import DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
113 import PatSyn ( PatSyn, patSynType )
114 import TcType
115 import Annotations
116 import InstEnv
117 import FamInstEnv
118 import IOEnv
119 import RdrName
120 import Name
121 import NameEnv
122 import NameSet
123 import Avail
124 import Var
125 import VarEnv
126 import Module
127 import SrcLoc
128 import VarSet
129 import ErrUtils
130 import UniqFM
131 import UniqSupply
132 import BasicTypes
133 import Bag
134 import DynFlags
135 import Outputable
136 import ListSetOps
137 import FastString
138 import GHC.Fingerprint
139
140 import Data.Set (Set)
141 import Control.Monad (ap, liftM)
142
143 #ifdef GHCI
144 import Data.Map ( Map )
145 import Data.Dynamic ( Dynamic )
146 import Data.Typeable ( TypeRep )
147
148 import qualified Language.Haskell.TH as TH
149 #endif
150
151 {-
152 ************************************************************************
153 * *
154 Standard monad definition for TcRn
155 All the combinators for the monad can be found in TcRnMonad
156 * *
157 ************************************************************************
158
159 The monad itself has to be defined here, because it is mentioned by ErrCtxt
160 -}
161
162 type TcRnIf a b = IOEnv (Env a b)
163 type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
164 type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
165 type IfG = IfM () -- Top level
166 type IfL = IfM IfLclEnv -- Nested
167 type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
168
169 -- TcRn is the type-checking and renaming monad: the main monad that
170 -- most type-checking takes place in. The global environment is
171 -- 'TcGblEnv', which tracks all of the top-level type-checking
172 -- information we've accumulated while checking a module, while the
173 -- local environment is 'TcLclEnv', which tracks local information as
174 -- we move inside expressions.
175
176 -- | Historical "renaming monad" (now it's just 'TcRn').
177 type RnM = TcRn
178
179 -- | Historical "type-checking monad" (now it's just 'TcRn').
180 type TcM = TcRn
181
182 -- We 'stack' these envs through the Reader like monad infastructure
183 -- as we move into an expression (although the change is focused in
184 -- the lcl type).
185 data Env gbl lcl
186 = Env {
187 env_top :: HscEnv, -- Top-level stuff that never changes
188 -- Includes all info about imported things
189
190 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
191 -- Unique supply for local varibles
192
193 env_gbl :: gbl, -- Info about things defined at the top level
194 -- of the module being compiled
195
196 env_lcl :: lcl -- Nested stuff; changes as we go into
197 }
198
199 instance ContainsDynFlags (Env gbl lcl) where
200 extractDynFlags env = hsc_dflags (env_top env)
201 replaceDynFlags env dflags
202 = env {env_top = replaceDynFlags (env_top env) dflags}
203
204 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
205 extractModule env = extractModule (env_gbl env)
206
207
208 {-
209 ************************************************************************
210 * *
211 The interface environments
212 Used when dealing with IfaceDecls
213 * *
214 ************************************************************************
215 -}
216
217 data IfGblEnv
218 = IfGblEnv {
219 -- The type environment for the module being compiled,
220 -- in case the interface refers back to it via a reference that
221 -- was originally a hi-boot file.
222 -- We need the module name so we can test when it's appropriate
223 -- to look in this env.
224 if_rec_types :: Maybe (Module, IfG TypeEnv)
225 -- Allows a read effect, so it can be in a mutable
226 -- variable; c.f. handling the external package type env
227 -- Nothing => interactive stuff, no loops possible
228 }
229
230 data IfLclEnv
231 = IfLclEnv {
232 -- The module for the current IfaceDecl
233 -- So if we see f = \x -> x
234 -- it means M.f = \x -> x, where M is the if_mod
235 if_mod :: Module,
236
237 -- The field is used only for error reporting
238 -- if (say) there's a Lint error in it
239 if_loc :: SDoc,
240 -- Where the interface came from:
241 -- .hi file, or GHCi state, or ext core
242 -- plus which bit is currently being examined
243
244 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
245 -- (and coercions)
246 if_id_env :: UniqFM Id -- Nested id binding
247 }
248
249 {-
250 ************************************************************************
251 * *
252 Desugarer monad
253 * *
254 ************************************************************************
255
256 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
257 a @UniqueSupply@ and some annotations, which
258 presumably include source-file location information:
259 -}
260
261 -- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
262 -- variables found in 'Data.Array.Parallel'.
263 --
264 data PArrBuiltin
265 = PArrBuiltin
266 { lengthPVar :: Var -- ^ lengthP
267 , replicatePVar :: Var -- ^ replicateP
268 , singletonPVar :: Var -- ^ singletonP
269 , mapPVar :: Var -- ^ mapP
270 , filterPVar :: Var -- ^ filterP
271 , zipPVar :: Var -- ^ zipP
272 , crossMapPVar :: Var -- ^ crossMapP
273 , indexPVar :: Var -- ^ (!:)
274 , emptyPVar :: Var -- ^ emptyP
275 , appPVar :: Var -- ^ (+:+)
276 , enumFromToPVar :: Var -- ^ enumFromToP
277 , enumFromThenToPVar :: Var -- ^ enumFromThenToP
278 }
279
280 data DsGblEnv
281 = DsGblEnv
282 { ds_mod :: Module -- For SCC profiling
283 , ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
284 , ds_unqual :: PrintUnqualified
285 , ds_msgs :: IORef Messages -- Warning messages
286 , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
287 -- possibly-imported things
288 , ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
289 -- iff '-fvectorise' flag was given as well as
290 -- exported entities of 'Data.Array.Parallel' iff
291 -- '-XParallelArrays' was given; otherwise, empty
292 , ds_parr_bi :: PArrBuiltin -- desugarar names for '-XParallelArrays'
293 , ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
294 -- ^ Bindings resulted from floating static forms
295 }
296
297 instance ContainsModule DsGblEnv where
298 extractModule = ds_mod
299
300 data DsLclEnv = DsLclEnv {
301 dsl_meta :: DsMetaEnv, -- Template Haskell bindings
302 dsl_loc :: SrcSpan -- to put in pattern-matching error msgs
303 }
304
305 -- Inside [| |] brackets, the desugarer looks
306 -- up variables in the DsMetaEnv
307 type DsMetaEnv = NameEnv DsMetaVal
308
309 data DsMetaVal
310 = DsBound Id -- Bound by a pattern inside the [| |].
311 -- Will be dynamically alpha renamed.
312 -- The Id has type THSyntax.Var
313
314 | DsSplice (HsExpr Id) -- These bindings are introduced by
315 -- the PendingSplices on a HsBracketOut
316
317
318 {-
319 ************************************************************************
320 * *
321 Global typechecker environment
322 * *
323 ************************************************************************
324 -}
325
326 -- | 'TcGblEnv' describes the top-level of the module at the
327 -- point at which the typechecker is finished work.
328 -- It is this structure that is handed on to the desugarer
329 -- For state that needs to be updated during the typechecking
330 -- phase and returned at end, use a 'TcRef' (= 'IORef').
331 data TcGblEnv
332 = TcGblEnv {
333 tcg_mod :: Module, -- ^ Module being compiled
334 tcg_src :: HscSource,
335 -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
336 tcg_sig_of :: Maybe Module,
337 -- ^ Are we being compiled as a signature of an implementation?
338 tcg_mod_name :: Maybe (Located ModuleName),
339 -- ^ @Nothing@: \"module X where\" is omitted
340 tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
341 -- ^ Environment used only during -sig-of for resolving top level
342 -- bindings. See Note [Signature parameters in TcGblEnv and DynFlags]
343
344 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
345 tcg_default :: Maybe [Type],
346 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
347
348 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
349 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
350 -- See Note [The interactive package] in HscTypes
351
352 tcg_type_env :: TypeEnv,
353 -- ^ Global type env for the module we are compiling now. All
354 -- TyCons and Classes (for this module) end up in here right away,
355 -- along with their derived constructors, selectors.
356 --
357 -- (Ids defined in this module start in the local envt, though they
358 -- move to the global envt during zonking)
359 --
360 -- NB: for what "things in this module" means, see
361 -- Note [The interactive package] in HscTypes
362
363 tcg_type_env_var :: TcRef TypeEnv,
364 -- Used only to initialise the interface-file
365 -- typechecker in initIfaceTcRn, so that it can see stuff
366 -- bound in this module when dealing with hi-boot recursions
367 -- Updated at intervals (e.g. after dealing with types and classes)
368
369 tcg_inst_env :: InstEnv,
370 -- ^ Instance envt for all /home-package/ modules;
371 -- Includes the dfuns in tcg_insts
372 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
373 tcg_ann_env :: AnnEnv, -- ^ And for annotations
374
375 tcg_visible_orphan_mods :: ModuleSet,
376 -- ^ The set of orphan modules which transitively reachable from
377 -- direct imports. We use this to figure out if an orphan instance
378 -- in the global InstEnv should be considered visible.
379 -- See Note [Instance lookup and orphan instances] in InstEnv
380
381 -- Now a bunch of things about this module that are simply
382 -- accumulated, but never consulted until the end.
383 -- Nevertheless, it's convenient to accumulate them along
384 -- with the rest of the info from this module.
385 tcg_exports :: [AvailInfo], -- ^ What is exported
386 tcg_imports :: ImportAvails,
387 -- ^ Information about what was imported from where, including
388 -- things bound in this module. Also store Safe Haskell info
389 -- here about transative trusted packaage requirements.
390
391 tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
392 tcg_used_rdrnames :: TcRef (Set RdrName),
393 -- See Note [Tracking unused binding and imports]
394
395 tcg_keep :: TcRef NameSet,
396 -- ^ Locally-defined top-level names to keep alive.
397 --
398 -- "Keep alive" means give them an Exported flag, so that the
399 -- simplifier does not discard them as dead code, and so that they
400 -- are exposed in the interface file (but not to export to the
401 -- user).
402 --
403 -- Some things, like dict-fun Ids and default-method Ids are "born"
404 -- with the Exported flag on, for exactly the above reason, but some
405 -- we only discover as we go. Specifically:
406 --
407 -- * The to/from functions for generic data types
408 --
409 -- * Top-level variables appearing free in the RHS of an orphan
410 -- rule
411 --
412 -- * Top-level variables appearing free in a TH bracket
413
414 tcg_th_used :: TcRef Bool,
415 -- ^ @True@ <=> Template Haskell syntax used.
416 --
417 -- We need this so that we can generate a dependency on the
418 -- Template Haskell package, because the desugarer is going
419 -- to emit loads of references to TH symbols. The reference
420 -- is implicit rather than explicit, so we have to zap a
421 -- mutable variable.
422
423 tcg_th_splice_used :: TcRef Bool,
424 -- ^ @True@ <=> A Template Haskell splice was used.
425 --
426 -- Splices disable recompilation avoidance (see #481)
427
428 tcg_dfun_n :: TcRef OccSet,
429 -- ^ Allows us to choose unique DFun names.
430
431 -- The next fields accumulate the payload of the module
432 -- The binds, rules and foreign-decl fields are collected
433 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
434
435 tcg_rn_exports :: Maybe [Located (IE Name)],
436 -- Nothing <=> no explicit export list
437
438 tcg_rn_imports :: [LImportDecl Name],
439 -- Keep the renamed imports regardless. They are not
440 -- voluminous and are needed if you want to report unused imports
441
442 tcg_rn_decls :: Maybe (HsGroup Name),
443 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
444 -- decls.
445
446 tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
447
448 #ifdef GHCI
449 tcg_th_topdecls :: TcRef [LHsDecl RdrName],
450 -- ^ Top-level declarations from addTopDecls
451
452 tcg_th_topnames :: TcRef NameSet,
453 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
454
455 tcg_th_modfinalizers :: TcRef [TH.Q ()],
456 -- ^ Template Haskell module finalizers
457
458 tcg_th_state :: TcRef (Map TypeRep Dynamic),
459 -- ^ Template Haskell state
460 #endif /* GHCI */
461
462 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
463
464 -- Things defined in this module, or (in GHCi)
465 -- in the declarations for a single GHCi command.
466 -- For the latter, see Note [The interactive package] in HscTypes
467 tcg_binds :: LHsBinds Id, -- Value bindings in this module
468 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
469 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
470 tcg_warns :: Warnings, -- ...Warnings and deprecations
471 tcg_anns :: [Annotation], -- ...Annotations
472 tcg_tcs :: [TyCon], -- ...TyCons and Classes
473 tcg_insts :: [ClsInst], -- ...Instances
474 tcg_fam_insts :: [FamInst], -- ...Family instances
475 tcg_rules :: [LRuleDecl Id], -- ...Rules
476 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
477 tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
478 tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
479
480 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
481 tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
482 -- prog uses hpc instrumentation.
483
484 tcg_main :: Maybe Name, -- ^ The Name of the main
485 -- function, if this module is
486 -- the main module.
487
488 tcg_safeInfer :: TcRef (Bool, WarningMessages),
489 -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
490 -- See Note [Safe Haskell Overlapping Instances Implementation],
491 -- although this is used for more than just that failure case.
492
493 tcg_tc_plugins :: [TcPluginSolver],
494 -- ^ A list of user-defined plugins for the constraint solver.
495
496 tcg_static_wc :: TcRef WantedConstraints
497 -- ^ Wanted constraints of static forms.
498 }
499
500 -- Note [Signature parameters in TcGblEnv and DynFlags]
501 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 -- When compiling signature files, we need to know which implementation
503 -- we've actually linked against the signature. There are three seemingly
504 -- redundant places where this information is stored: in DynFlags, there
505 -- is sigOf, and in TcGblEnv, there is tcg_sig_of and tcg_impl_rdr_env.
506 -- Here's the difference between each of them:
507 --
508 -- * DynFlags.sigOf is global per invocation of GHC. If we are compiling
509 -- with --make, there may be multiple signature files being compiled; in
510 -- which case this parameter is a map from local module name to implementing
511 -- Module.
512 --
513 -- * HscEnv.tcg_sig_of is global per the compilation of a single file, so
514 -- it is simply the result of looking up tcg_mod in the DynFlags.sigOf
515 -- parameter. It's setup in TcRnMonad.initTc. This prevents us
516 -- from having to repeatedly do a lookup in DynFlags.sigOf.
517 --
518 -- * HscEnv.tcg_impl_rdr_env is a RdrEnv that lets us look up names
519 -- according to the sig-of module. It's setup in TcRnDriver.tcRnSignature.
520 -- Here is an example showing why we need this map:
521 --
522 -- module A where
523 -- a = True
524 --
525 -- module ASig where
526 -- import B
527 -- a :: Bool
528 --
529 -- module B where
530 -- b = False
531 --
532 -- When we compile ASig --sig-of main:A, the default
533 -- global RdrEnv (tcg_rdr_env) has an entry for b, but not for a
534 -- (we never imported A). So we have to look in a different environment
535 -- to actually get the original name.
536 --
537 -- By the way, why do we need to do the lookup; can't we just use A:a
538 -- as the name directly? Well, if A is reexporting the entity from another
539 -- module, then the original name needs to be the real original name:
540 --
541 -- module C where
542 -- a = True
543 --
544 -- module A(a) where
545 -- import C
546
547 instance ContainsModule TcGblEnv where
548 extractModule env = tcg_mod env
549
550 data RecFieldEnv
551 = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
552 -- to the fields for that constructor
553 NameSet -- Set of all fields declared *in this module*;
554 -- used to suppress name-shadowing complaints
555 -- when using record wild cards
556 -- E.g. let fld = e in C {..}
557 -- This is used when dealing with ".." notation in record
558 -- construction and pattern matching.
559 -- The FieldEnv deals *only* with constructors defined in *this*
560 -- module. For imported modules, we get the same info from the
561 -- TypeEnv
562
563 {-
564 Note [Tracking unused binding and imports]
565 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
566 We gather two sorts of usage information
567 * tcg_dus (defs/uses)
568 Records *defined* Names (local, top-level)
569 and *used* Names (local or imported)
570
571 Used (a) to report "defined but not used"
572 (see RnNames.reportUnusedNames)
573 (b) to generate version-tracking usage info in interface
574 files (see MkIface.mkUsedNames)
575 This usage info is mainly gathered by the renamer's
576 gathering of free-variables
577
578 * tcg_used_rdrnames
579 Records used *imported* (not locally-defined) RdrNames
580 Used only to report unused import declarations
581 Notice that they are RdrNames, not Names, so we can
582 tell whether the reference was qualified or unqualified, which
583 is esssential in deciding whether a particular import decl
584 is unnecessary. This info isn't present in Names.
585
586
587 ************************************************************************
588 * *
589 The local typechecker environment
590 * *
591 ************************************************************************
592
593 Note [The Global-Env/Local-Env story]
594 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
595 During type checking, we keep in the tcg_type_env
596 * All types and classes
597 * All Ids derived from types and classes (constructors, selectors)
598
599 At the end of type checking, we zonk the local bindings,
600 and as we do so we add to the tcg_type_env
601 * Locally defined top-level Ids
602
603 Why? Because they are now Ids not TcIds. This final GlobalEnv is
604 a) fed back (via the knot) to typechecking the
605 unfoldings of interface signatures
606 b) used in the ModDetails of this module
607 -}
608
609 data TcLclEnv -- Changes as we move inside an expression
610 -- Discarded after typecheck/rename; not passed on to desugarer
611 = TcLclEnv {
612 tcl_loc :: RealSrcSpan, -- Source span
613 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
614 tcl_tclvl :: TcLevel, -- Birthplace for new unification variables
615
616 tcl_th_ctxt :: ThStage, -- Template Haskell context
617 tcl_th_bndrs :: ThBindEnv, -- Binding level of in-scope Names
618 -- defined in this module (not imported)
619
620 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
621
622 tcl_rdr :: LocalRdrEnv, -- Local name envt
623 -- Maintained during renaming, of course, but also during
624 -- type checking, solely so that when renaming a Template-Haskell
625 -- splice we have the right environment for the renamer.
626 --
627 -- Does *not* include global name envt; may shadow it
628 -- Includes both ordinary variables and type variables;
629 -- they are kept distinct because tyvar have a different
630 -- occurrence contructor (Name.TvOcc)
631 -- We still need the unsullied global name env so that
632 -- we can look up record field names
633
634 tcl_env :: TcTypeEnv, -- The local type environment:
635 -- Ids and TyVars defined in this module
636
637 tcl_bndrs :: TcIdBinderStack, -- Used for reporting relevant bindings
638
639 tcl_tidy :: TidyEnv, -- Used for tidying types; contains all
640 -- in-scope type variables (but not term variables)
641
642 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
643 -- Namely, the in-scope TyVars bound in tcl_env,
644 -- plus the tyvars mentioned in the types of Ids bound
645 -- in tcl_lenv.
646 -- Why mutable? see notes with tcGetGlobalTyVars
647
648 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
649 tcl_errs :: TcRef Messages -- Place to accumulate errors
650 }
651
652 type TcTypeEnv = NameEnv TcTyThing
653
654 type ThBindEnv = NameEnv (TopLevelFlag, ThLevel)
655 -- Domain = all Ids bound in this module (ie not imported)
656 -- The TopLevelFlag tells if the binding is syntactically top level.
657 -- We need to know this, because the cross-stage persistence story allows
658 -- cross-stage at arbitrary types if the Id is bound at top level.
659 --
660 -- Nota bene: a ThLevel of 'outerLevel' is *not* the same as being
661 -- bound at top level! See Note [Template Haskell levels] in TcSplice
662
663 {- Note [Given Insts]
664 ~~~~~~~~~~~~~~~~~~
665 Because of GADTs, we have to pass inwards the Insts provided by type signatures
666 and existential contexts. Consider
667 data T a where { T1 :: b -> b -> T [b] }
668 f :: Eq a => T a -> Bool
669 f (T1 x y) = [x]==[y]
670
671 The constructor T1 binds an existential variable 'b', and we need Eq [b].
672 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
673 pass it inwards.
674
675 -}
676
677 -- | Type alias for 'IORef'; the convention is we'll use this for mutable
678 -- bits of data in 'TcGblEnv' which are updated during typechecking and
679 -- returned at the end.
680 type TcRef a = IORef a
681 -- ToDo: when should I refer to it as a 'TcId' instead of an 'Id'?
682 type TcId = Id
683 type TcIdSet = IdSet
684
685 ---------------------------
686 -- The TcIdBinderStack
687 ---------------------------
688
689 type TcIdBinderStack = [TcIdBinder]
690 -- This is a stack of locally-bound ids, innermost on top
691 -- Used ony in error reporting (relevantBindings in TcError)
692
693 data TcIdBinder
694 = TcIdBndr
695 TcId
696 TopLevelFlag -- Tells whether the bindind is syntactically top-level
697 -- (The monomorphic Ids for a recursive group count
698 -- as not-top-level for this purpose.)
699
700 instance Outputable TcIdBinder where
701 ppr (TcIdBndr id top_lvl) = ppr id <> brackets (ppr top_lvl)
702
703 ---------------------------
704 -- Template Haskell stages and levels
705 ---------------------------
706
707 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
708 = Splice -- Inside a top-level splice splice
709 -- This code will be run *at compile time*;
710 -- the result replaces the splice
711 -- Binding level = 0
712 Bool -- True if in a typed splice, False otherwise
713
714 | Comp -- Ordinary Haskell code
715 -- Binding level = 1
716
717 | Brack -- Inside brackets
718 ThStage -- Enclosing stage
719 PendingStuff
720
721 data PendingStuff
722 = RnPendingUntyped -- Renaming the inside of an *untyped* bracket
723 (TcRef [PendingRnSplice]) -- Pending splices in here
724
725 | RnPendingTyped -- Renaming the inside of a *typed* bracket
726
727 | TcPending -- Typechecking the inside of a typed bracket
728 (TcRef [PendingTcSplice]) -- Accumulate pending splices here
729 (TcRef WantedConstraints) -- and type constraints here
730
731 topStage, topAnnStage, topSpliceStage :: ThStage
732 topStage = Comp
733 topAnnStage = Splice False
734 topSpliceStage = Splice False
735
736 instance Outputable ThStage where
737 ppr (Splice _) = text "Splice"
738 ppr Comp = text "Comp"
739 ppr (Brack s _) = text "Brack" <> parens (ppr s)
740
741 type ThLevel = Int
742 -- NB: see Note [Template Haskell levels] in TcSplice
743 -- Incremented when going inside a bracket,
744 -- decremented when going inside a splice
745 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
746 -- original "Template meta-programming for Haskell" paper
747
748 impLevel, outerLevel :: ThLevel
749 impLevel = 0 -- Imported things; they can be used inside a top level splice
750 outerLevel = 1 -- Things defined outside brackets
751
752 thLevel :: ThStage -> ThLevel
753 thLevel (Splice _) = 0
754 thLevel Comp = 1
755 thLevel (Brack s _) = thLevel s + 1
756
757 ---------------------------
758 -- Arrow-notation context
759 ---------------------------
760
761 {- Note [Escaping the arrow scope]
762 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
763 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
764 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
765 For example
766
767 proc x -> (e1 -< e2)
768
769 Here, x is not in scope in e1, but it is in scope in e2. This can get
770 a bit complicated:
771
772 let x = 3 in
773 proc y -> (proc z -> e1) -< e2
774
775 Here, x and z are in scope in e1, but y is not.
776
777 We implement this by
778 recording the environment when passing a proc (using newArrowScope),
779 and returning to that (using escapeArrowScope) on the left of -< and the
780 head of (|..|).
781
782 All this can be dealt with by the *renamer*. But the type checker needs
783 to be involved too. Example (arrowfail001)
784 class Foo a where foo :: a -> ()
785 data Bar = forall a. Foo a => Bar a
786 get :: Bar -> ()
787 get = proc x -> case x of Bar a -> foo -< a
788 Here the call of 'foo' gives rise to a (Foo a) constraint that should not
789 be captured by the pattern match on 'Bar'. Rather it should join the
790 constraints from further out. So we must capture the constraint bag
791 from further out in the ArrowCtxt that we push inwards.
792 -}
793
794 data ArrowCtxt -- Note [Escaping the arrow scope]
795 = NoArrowCtxt
796 | ArrowCtxt LocalRdrEnv (TcRef WantedConstraints)
797
798
799 ---------------------------
800 -- TcTyThing
801 ---------------------------
802
803 -- | A typecheckable thing available in a local context. Could be
804 -- 'AGlobal' 'TyThing', but also lexically scoped variables, etc.
805 -- See 'TcEnv' for how to retrieve a 'TyThing' given a 'Name'.
806 data TcTyThing
807 = AGlobal TyThing -- Used only in the return type of a lookup
808
809 | ATcId { -- Ids defined in this module; may not be fully zonked
810 tct_id :: TcId,
811 tct_closed :: TopLevelFlag } -- See Note [Bindings with closed types]
812
813 | ATyVar Name TcTyVar -- The type variable to which the lexically scoped type
814 -- variable is bound. We only need the Name
815 -- for error-message purposes; it is the corresponding
816 -- Name in the domain of the envt
817
818 | AThing TcKind -- Used temporarily, during kind checking, for the
819 -- tycons and clases in this recursive group
820 -- Can be a mono-kind or a poly-kind; in TcTyClsDcls see
821 -- Note [Type checking recursive type and class declarations]
822
823 | APromotionErr PromotionErr
824
825 data PromotionErr
826 = TyConPE -- TyCon used in a kind before we are ready
827 -- data T :: T -> * where ...
828 | ClassPE -- Ditto Class
829
830 | FamDataConPE -- Data constructor for a data family
831 -- See Note [AFamDataCon: not promoting data family constructors] in TcRnDriver
832
833 | RecDataConPE -- Data constructor in a recursive loop
834 -- See Note [ARecDataCon: recusion and promoting data constructors] in TcTyClsDecls
835 | NoDataKinds -- -XDataKinds not enabled
836
837 instance Outputable TcTyThing where -- Debugging only
838 ppr (AGlobal g) = pprTyThing g
839 ppr elt@(ATcId {}) = text "Identifier" <>
840 brackets (ppr (tct_id elt) <> dcolon
841 <> ppr (varType (tct_id elt)) <> comma
842 <+> ppr (tct_closed elt))
843 ppr (ATyVar n tv) = text "Type variable" <+> quotes (ppr n) <+> equals <+> ppr tv
844 ppr (AThing k) = text "AThing" <+> ppr k
845 ppr (APromotionErr err) = text "APromotionErr" <+> ppr err
846
847 instance Outputable PromotionErr where
848 ppr ClassPE = text "ClassPE"
849 ppr TyConPE = text "TyConPE"
850 ppr FamDataConPE = text "FamDataConPE"
851 ppr RecDataConPE = text "RecDataConPE"
852 ppr NoDataKinds = text "NoDataKinds"
853
854 pprTcTyThingCategory :: TcTyThing -> SDoc
855 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
856 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
857 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
858 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
859 pprTcTyThingCategory (APromotionErr pe) = pprPECategory pe
860
861 pprPECategory :: PromotionErr -> SDoc
862 pprPECategory ClassPE = ptext (sLit "Class")
863 pprPECategory TyConPE = ptext (sLit "Type constructor")
864 pprPECategory FamDataConPE = ptext (sLit "Data constructor")
865 pprPECategory RecDataConPE = ptext (sLit "Data constructor")
866 pprPECategory NoDataKinds = ptext (sLit "Data constructor")
867
868 {- Note [Bindings with closed types]
869 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
870 Consider
871
872 f x = let g ys = map not ys
873 in ...
874
875 Can we generalise 'g' under the OutsideIn algorithm? Yes,
876 because all g's free variables are top-level; that is they themselves
877 have no free type variables, and it is the type variables in the
878 environment that makes things tricky for OutsideIn generalisation.
879
880 Definition:
881 A variable is "closed", and has tct_closed set to TopLevel,
882 iff
883 a) all its free variables are imported, or are let-bound with closed types
884 b) generalisation is not restricted by the monomorphism restriction
885
886 Under OutsideIn we are free to generalise a closed let-binding.
887 This is an extension compared to the JFP paper on OutsideIn, which
888 used "top-level" as a proxy for "closed". (It's not a good proxy
889 anyway -- the MR can make a top-level binding with a free type
890 variable.)
891
892 Note that:
893 * A top-level binding may not be closed, if it suffers from the MR
894
895 * A nested binding may be closed (eg 'g' in the example we started with)
896 Indeed, that's the point; whether a function is defined at top level
897 or nested is orthogonal to the question of whether or not it is closed
898
899 * A binding may be non-closed because it mentions a lexically scoped
900 *type variable* Eg
901 f :: forall a. blah
902 f x = let g y = ...(y::a)...
903 -}
904
905 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, MsgDoc))
906 -- Monadic so that we have a chance
907 -- to deal with bound type variables just before error
908 -- message construction
909
910 -- Bool: True <=> this is a landmark context; do not
911 -- discard it when trimming for display
912
913 {-
914 ************************************************************************
915 * *
916 Operations over ImportAvails
917 * *
918 ************************************************************************
919 -}
920
921 -- | 'ImportAvails' summarises what was imported from where, irrespective of
922 -- whether the imported things are actually used or not. It is used:
923 --
924 -- * when processing the export list,
925 --
926 -- * when constructing usage info for the interface file,
927 --
928 -- * to identify the list of directly imported modules for initialisation
929 -- purposes and for optimised overlap checking of family instances,
930 --
931 -- * when figuring out what things are really unused
932 --
933 data ImportAvails
934 = ImportAvails {
935 imp_mods :: ImportedMods,
936 -- = ModuleEnv [(ModuleName, Bool, SrcSpan, Bool)],
937 -- ^ Domain is all directly-imported modules
938 -- The 'ModuleName' is what the module was imported as, e.g. in
939 -- @
940 -- import Foo as Bar
941 -- @
942 -- it is @Bar@.
943 --
944 -- The 'Bool' means:
945 --
946 -- - @True@ => import was @import Foo ()@
947 --
948 -- - @False@ => import was some other form
949 --
950 -- Used
951 --
952 -- (a) to help construct the usage information in the interface
953 -- file; if we import something we need to recompile if the
954 -- export version changes
955 --
956 -- (b) to specify what child modules to initialise
957 --
958 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
959 -- because we might be importing modules of the same name from
960 -- different packages. (currently not the case, but might be in the
961 -- future).
962
963 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
964 -- ^ Home-package modules needed by the module being compiled
965 --
966 -- It doesn't matter whether any of these dependencies
967 -- are actually /used/ when compiling the module; they
968 -- are listed if they are below it at all. For
969 -- example, suppose M imports A which imports X. Then
970 -- compiling M might not need to consult X.hi, but X
971 -- is still listed in M's dependencies.
972
973 imp_dep_pkgs :: [PackageKey],
974 -- ^ Packages needed by the module being compiled, whether directly,
975 -- or via other modules in this package, or via modules imported
976 -- from other packages.
977
978 imp_trust_pkgs :: [PackageKey],
979 -- ^ This is strictly a subset of imp_dep_pkgs and records the
980 -- packages the current module needs to trust for Safe Haskell
981 -- compilation to succeed. A package is required to be trusted if
982 -- we are dependent on a trustworthy module in that package.
983 -- While perhaps making imp_dep_pkgs a tuple of (PackageKey, Bool)
984 -- where True for the bool indicates the package is required to be
985 -- trusted is the more logical design, doing so complicates a lot
986 -- of code not concerned with Safe Haskell.
987 -- See Note [RnNames . Tracking Trust Transitively]
988
989 imp_trust_own_pkg :: Bool,
990 -- ^ Do we require that our own package is trusted?
991 -- This is to handle efficiently the case where a Safe module imports
992 -- a Trustworthy module that resides in the same package as it.
993 -- See Note [RnNames . Trust Own Package]
994
995 imp_orphs :: [Module],
996 -- ^ Orphan modules below us in the import tree (and maybe including
997 -- us for imported modules)
998
999 imp_finsts :: [Module]
1000 -- ^ Family instance modules below us in the import tree (and maybe
1001 -- including us for imported modules)
1002 }
1003
1004 mkModDeps :: [(ModuleName, IsBootInterface)]
1005 -> ModuleNameEnv (ModuleName, IsBootInterface)
1006 mkModDeps deps = foldl add emptyUFM deps
1007 where
1008 add env elt@(m,_) = addToUFM env m elt
1009
1010 emptyImportAvails :: ImportAvails
1011 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
1012 imp_dep_mods = emptyUFM,
1013 imp_dep_pkgs = [],
1014 imp_trust_pkgs = [],
1015 imp_trust_own_pkg = False,
1016 imp_orphs = [],
1017 imp_finsts = [] }
1018
1019 -- | Union two ImportAvails
1020 --
1021 -- This function is a key part of Import handling, basically
1022 -- for each import we create a separate ImportAvails structure
1023 -- and then union them all together with this function.
1024 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
1025 plusImportAvails
1026 (ImportAvails { imp_mods = mods1,
1027 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
1028 imp_trust_pkgs = tpkgs1, imp_trust_own_pkg = tself1,
1029 imp_orphs = orphs1, imp_finsts = finsts1 })
1030 (ImportAvails { imp_mods = mods2,
1031 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
1032 imp_trust_pkgs = tpkgs2, imp_trust_own_pkg = tself2,
1033 imp_orphs = orphs2, imp_finsts = finsts2 })
1034 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
1035 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
1036 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
1037 imp_trust_pkgs = tpkgs1 `unionLists` tpkgs2,
1038 imp_trust_own_pkg = tself1 || tself2,
1039 imp_orphs = orphs1 `unionLists` orphs2,
1040 imp_finsts = finsts1 `unionLists` finsts2 }
1041 where
1042 plus_mod_dep (m1, boot1) (m2, boot2)
1043 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
1044 -- Check mod-names match
1045 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
1046
1047 {-
1048 ************************************************************************
1049 * *
1050 \subsection{Where from}
1051 * *
1052 ************************************************************************
1053
1054 The @WhereFrom@ type controls where the renamer looks for an interface file
1055 -}
1056
1057 data WhereFrom
1058 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
1059 | ImportBySystem -- Non user import.
1060 | ImportByPlugin -- Importing a plugin;
1061 -- See Note [Care with plugin imports] in LoadIface
1062
1063 instance Outputable WhereFrom where
1064 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
1065 | otherwise = empty
1066 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
1067 ppr ImportByPlugin = ptext (sLit "{- PLUGIN -}")
1068
1069 {-
1070 ************************************************************************
1071 * *
1072 * Canonical constraints *
1073 * *
1074 * These are the constraints the low-level simplifier works with *
1075 * *
1076 ************************************************************************
1077 -}
1078
1079 -- The syntax of xi types:
1080 -- xi ::= a | T xis | xis -> xis | ... | forall a. tau
1081 -- Two important notes:
1082 -- (i) No type families, unless we are under a ForAll
1083 -- (ii) Note that xi types can contain unexpanded type synonyms;
1084 -- however, the (transitive) expansions of those type synonyms
1085 -- will not contain any type functions, unless we are under a ForAll.
1086 -- We enforce the structure of Xi types when we flatten (TcCanonical)
1087
1088 type Xi = Type -- In many comments, "xi" ranges over Xi
1089
1090 type Cts = Bag Ct
1091
1092 data Ct
1093 -- Atomic canonical constraints
1094 = CDictCan { -- e.g. Num xi
1095 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1096 cc_class :: Class,
1097 cc_tyargs :: [Xi] -- cc_tyargs are function-free, hence Xi
1098 }
1099
1100 | CIrredEvCan { -- These stand for yet-unusable predicates
1101 cc_ev :: CtEvidence -- See Note [Ct/evidence invariant]
1102 -- The ctev_pred of the evidence is
1103 -- of form (tv xi1 xi2 ... xin)
1104 -- or (tv1 ~ ty2) where the CTyEqCan kind invariant fails
1105 -- or (F tys ~ ty) where the CFunEqCan kind invariant fails
1106 -- See Note [CIrredEvCan constraints]
1107 }
1108
1109 | CTyEqCan { -- tv ~ rhs
1110 -- Invariants:
1111 -- * See Note [Applying the inert substitution] in TcFlatten
1112 -- * tv not in tvs(rhs) (occurs check)
1113 -- * If tv is a TauTv, then rhs has no foralls
1114 -- (this avoids substituting a forall for the tyvar in other types)
1115 -- * typeKind ty `subKind` typeKind tv
1116 -- See Note [Kind orientation for CTyEqCan]
1117 -- * rhs is not necessarily function-free,
1118 -- but it has no top-level function.
1119 -- E.g. a ~ [F b] is fine
1120 -- but a ~ F b is not
1121 -- * If the equality is representational, rhs has no top-level newtype
1122 -- See Note [No top-level newtypes on RHS of representational
1123 -- equalities] in TcCanonical
1124 -- * If rhs is also a tv, then it is oriented to give best chance of
1125 -- unification happening; eg if rhs is touchable then lhs is too
1126 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1127 cc_tyvar :: TcTyVar,
1128 cc_rhs :: TcType, -- Not necessarily function-free (hence not Xi)
1129 -- See invariants above
1130 cc_eq_rel :: EqRel
1131 }
1132
1133 | CFunEqCan { -- F xis ~ fsk
1134 -- Invariants:
1135 -- * isTypeFamilyTyCon cc_fun
1136 -- * typeKind (F xis) = tyVarKind fsk
1137 -- * always Nominal role
1138 -- * always Given or Wanted, never Derived
1139 cc_ev :: CtEvidence, -- See Note [Ct/evidence invariant]
1140 cc_fun :: TyCon, -- A type function
1141
1142 cc_tyargs :: [Xi], -- cc_tyargs are function-free (hence Xi)
1143 -- Either under-saturated or exactly saturated
1144 -- *never* over-saturated (because if so
1145 -- we should have decomposed)
1146
1147 cc_fsk :: TcTyVar -- [Given] always a FlatSkol skolem
1148 -- [Wanted] always a FlatMetaTv unification variable
1149 -- See Note [The flattening story] in TcFlatten
1150 }
1151
1152 | CNonCanonical { -- See Note [NonCanonical Semantics]
1153 cc_ev :: CtEvidence
1154 }
1155
1156 | CHoleCan { -- See Note [Hole constraints]
1157 -- Treated as an "insoluble" constraint
1158 -- See Note [Insoluble constraints]
1159 cc_ev :: CtEvidence,
1160 cc_occ :: OccName, -- The name of this hole
1161 cc_hole :: HoleSort -- The sort of this hole (expr, type, ...)
1162 }
1163
1164 -- | Used to indicate which sort of hole we have.
1165 data HoleSort = ExprHole -- ^ A hole in an expression (TypedHoles)
1166 | TypeHole -- ^ A hole in a type (PartialTypeSignatures)
1167
1168 {-
1169 Note [Hole constraints]
1170 ~~~~~~~~~~~~~~~~~~~~~~~
1171 CHoleCan constraints are used for two kinds of holes,
1172 distinguished by cc_hole:
1173
1174 * For holes in expressions
1175 e.g. f x = g _ x
1176
1177 * For holes in type signatures
1178 e.g. f :: _ -> _
1179 f x = [x,True]
1180
1181 Note [Kind orientation for CTyEqCan]
1182 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1183 Given an equality (t:* ~ s:Open), we can't solve it by updating t:=s,
1184 ragardless of how touchable 't' is, because the kinds don't work.
1185
1186 Instead we absolutely must re-orient it. Reason: if that gets into the
1187 inert set we'll start replacing t's by s's, and that might make a
1188 kind-correct type into a kind error. After re-orienting,
1189 we may be able to solve by updating s:=t.
1190
1191 Hence in a CTyEqCan, (t:k1 ~ xi:k2) we require that k2 is a subkind of k1.
1192
1193 If the two have incompatible kinds, we just don't use a CTyEqCan at all.
1194 See Note [Equalities with incompatible kinds] in TcCanonical
1195
1196 We can't require *equal* kinds, because
1197 * wanted constraints don't necessarily have identical kinds
1198 eg alpha::? ~ Int
1199 * a solved wanted constraint becomes a given
1200
1201 Note [Kind orientation for CFunEqCan]
1202 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1203 For (F xis ~ rhs) we require that kind(lhs) is a subkind of kind(rhs).
1204 This really only maters when rhs is an Open type variable (since only type
1205 variables have Open kinds):
1206 F ty ~ (a:Open)
1207 which can happen, say, from
1208 f :: F a b
1209 f = undefined -- The a:Open comes from instantiating 'undefined'
1210
1211 Note that the kind invariant is maintained by rewriting.
1212 Eg wanted1 rewrites wanted2; if both were compatible kinds before,
1213 wanted2 will be afterwards. Similarly givens.
1214
1215 Caveat:
1216 - Givens from higher-rank, such as:
1217 type family T b :: * -> * -> *
1218 type instance T Bool = (->)
1219
1220 f :: forall a. ((T a ~ (->)) => ...) -> a -> ...
1221 flop = f (...) True
1222 Whereas we would be able to apply the type instance, we would not be able to
1223 use the given (T Bool ~ (->)) in the body of 'flop'
1224
1225
1226 Note [CIrredEvCan constraints]
1227 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1228 CIrredEvCan constraints are used for constraints that are "stuck"
1229 - we can't solve them (yet)
1230 - we can't use them to solve other constraints
1231 - but they may become soluble if we substitute for some
1232 of the type variables in the constraint
1233
1234 Example 1: (c Int), where c :: * -> Constraint. We can't do anything
1235 with this yet, but if later c := Num, *then* we can solve it
1236
1237 Example 2: a ~ b, where a :: *, b :: k, where k is a kind variable
1238 We don't want to use this to substitute 'b' for 'a', in case
1239 'k' is subequently unifed with (say) *->*, because then
1240 we'd have ill-kinded types floating about. Rather we want
1241 to defer using the equality altogether until 'k' get resolved.
1242
1243 Note [Ct/evidence invariant]
1244 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1245 If ct :: Ct, then extra fields of 'ct' cache precisely the ctev_pred field
1246 of (cc_ev ct), and is fully rewritten wrt the substitution. Eg for CDictCan,
1247 ctev_pred (cc_ev ct) = (cc_class ct) (cc_tyargs ct)
1248 This holds by construction; look at the unique place where CDictCan is
1249 built (in TcCanonical).
1250
1251 In contrast, the type of the evidence *term* (ccev_evtm or ctev_evar) in
1252 the evidence may *not* be fully zonked; we are careful not to look at it
1253 during constraint solving. See Note [Evidence field of CtEvidence]
1254 -}
1255
1256 mkNonCanonical :: CtEvidence -> Ct
1257 mkNonCanonical ev = CNonCanonical { cc_ev = ev }
1258
1259 mkNonCanonicalCt :: Ct -> Ct
1260 mkNonCanonicalCt ct = CNonCanonical { cc_ev = cc_ev ct }
1261
1262 ctEvidence :: Ct -> CtEvidence
1263 ctEvidence = cc_ev
1264
1265 ctLoc :: Ct -> CtLoc
1266 ctLoc = ctEvLoc . ctEvidence
1267
1268 ctPred :: Ct -> PredType
1269 -- See Note [Ct/evidence invariant]
1270 ctPred ct = ctEvPred (cc_ev ct)
1271
1272 -- | Get the flavour of the given 'Ct'
1273 ctFlavour :: Ct -> CtFlavour
1274 ctFlavour = ctEvFlavour . ctEvidence
1275
1276 -- | Get the equality relation for the given 'Ct'
1277 ctEqRel :: Ct -> EqRel
1278 ctEqRel = ctEvEqRel . ctEvidence
1279
1280 dropDerivedWC :: WantedConstraints -> WantedConstraints
1281 -- See Note [Dropping derived constraints]
1282 dropDerivedWC wc@(WC { wc_simple = simples, wc_insol = insols })
1283 = wc { wc_simple = dropDerivedSimples simples
1284 , wc_insol = dropDerivedInsols insols }
1285 -- The wc_impl implications are already (recursively) filtered
1286
1287 dropDerivedSimples :: Cts -> Cts
1288 dropDerivedSimples simples = filterBag isWantedCt simples
1289 -- simples are all Wanted or Derived
1290
1291 dropDerivedInsols :: Cts -> Cts
1292 -- See Note [Dropping derived constraints]
1293 dropDerivedInsols insols = filterBag keep insols
1294 where -- insols can include Given
1295 keep ct
1296 | isDerivedCt ct = keep_orig (ctLocOrigin (ctLoc ct))
1297 | otherwise = True
1298
1299 keep_orig :: CtOrigin -> Bool
1300 keep_orig (KindEqOrigin {}) = True
1301 keep_orig (GivenOrigin {}) = True
1302 keep_orig (FunDepOrigin1 {}) = True
1303 keep_orig (FunDepOrigin2 {}) = True
1304 -- keep_orig (FunDepOrigin1 _ loc _ _) = keep_orig (ctLocOrigin loc)
1305 -- keep_orig (FunDepOrigin2 _ orig _ _) = keep_orig orig
1306 keep_orig _ = False
1307
1308
1309 {- Note [Dropping derived constraints]
1310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1311 In general we discard derived constraints at the end of constraint solving;
1312 see dropDerivedWC. For example
1313
1314 * If we have an unsolved [W] (Ord a), we don't want to complain about
1315 an unsolved [D] (Eq a) as well.
1316
1317 * If we have [W] a ~ Int, [W] a ~ Bool, improvement will generate
1318 [D] Int ~ Bool, and we don't want to report that because it's incomprehensible.
1319 That is why we don't rewrite wanteds with wanteds!
1320
1321 But (tiresomely) we do keep *some* Derived insolubles:
1322
1323 * Insoluble kind equalities (e.g. [D] * ~ (* -> *)) may arise from
1324 a type equality a ~ Int#, say. In future they'll be Wanted, not Derived,
1325 but at the moment they are Derived.
1326
1327 * Insoluble derived equalities (e.g. [D] Int ~ Bool) may arise from
1328 functional dependency interactions, either between Givens or
1329 Wanteds. It seems sensible to retain these:
1330 - For Givens they reflect unreachable code
1331 - For Wanteds it is arguably better to get a fundep error than
1332 a no-instance error (Trac #9612)
1333
1334 To distinguish these cases we use the CtOrigin.
1335
1336
1337 ************************************************************************
1338 * *
1339 CtEvidence
1340 The "flavor" of a canonical constraint
1341 * *
1342 ************************************************************************
1343 -}
1344
1345 isWantedCt :: Ct -> Bool
1346 isWantedCt = isWanted . cc_ev
1347
1348 isGivenCt :: Ct -> Bool
1349 isGivenCt = isGiven . cc_ev
1350
1351 isDerivedCt :: Ct -> Bool
1352 isDerivedCt = isDerived . cc_ev
1353
1354 isCTyEqCan :: Ct -> Bool
1355 isCTyEqCan (CTyEqCan {}) = True
1356 isCTyEqCan (CFunEqCan {}) = False
1357 isCTyEqCan _ = False
1358
1359 isCDictCan_Maybe :: Ct -> Maybe Class
1360 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
1361 isCDictCan_Maybe _ = Nothing
1362
1363 isCIrredEvCan :: Ct -> Bool
1364 isCIrredEvCan (CIrredEvCan {}) = True
1365 isCIrredEvCan _ = False
1366
1367 isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
1368 isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
1369 isCFunEqCan_maybe _ = Nothing
1370
1371 isCFunEqCan :: Ct -> Bool
1372 isCFunEqCan (CFunEqCan {}) = True
1373 isCFunEqCan _ = False
1374
1375 isCNonCanonical :: Ct -> Bool
1376 isCNonCanonical (CNonCanonical {}) = True
1377 isCNonCanonical _ = False
1378
1379 isHoleCt:: Ct -> Bool
1380 isHoleCt (CHoleCan {}) = True
1381 isHoleCt _ = False
1382
1383 isExprHoleCt :: Ct -> Bool
1384 isExprHoleCt (CHoleCan { cc_hole = ExprHole }) = True
1385 isExprHoleCt _ = False
1386
1387 isTypeHoleCt :: Ct -> Bool
1388 isTypeHoleCt (CHoleCan { cc_hole = TypeHole }) = True
1389 isTypeHoleCt _ = False
1390
1391 instance Outputable Ct where
1392 ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
1393 where ct_sort = case ct of
1394 CTyEqCan {} -> "CTyEqCan"
1395 CFunEqCan {} -> "CFunEqCan"
1396 CNonCanonical {} -> "CNonCanonical"
1397 CDictCan {} -> "CDictCan"
1398 CIrredEvCan {} -> "CIrredEvCan"
1399 CHoleCan {} -> "CHoleCan"
1400
1401 singleCt :: Ct -> Cts
1402 singleCt = unitBag
1403
1404 andCts :: Cts -> Cts -> Cts
1405 andCts = unionBags
1406
1407 listToCts :: [Ct] -> Cts
1408 listToCts = listToBag
1409
1410 ctsElts :: Cts -> [Ct]
1411 ctsElts = bagToList
1412
1413 consCts :: Ct -> Cts -> Cts
1414 consCts = consBag
1415
1416 snocCts :: Cts -> Ct -> Cts
1417 snocCts = snocBag
1418
1419 extendCtsList :: Cts -> [Ct] -> Cts
1420 extendCtsList cts xs | null xs = cts
1421 | otherwise = cts `unionBags` listToBag xs
1422
1423 andManyCts :: [Cts] -> Cts
1424 andManyCts = unionManyBags
1425
1426 emptyCts :: Cts
1427 emptyCts = emptyBag
1428
1429 isEmptyCts :: Cts -> Bool
1430 isEmptyCts = isEmptyBag
1431
1432 pprCts :: Cts -> SDoc
1433 pprCts cts = vcat (map ppr (bagToList cts))
1434
1435 {-
1436 ************************************************************************
1437 * *
1438 Wanted constraints
1439 These are forced to be in TcRnTypes because
1440 TcLclEnv mentions WantedConstraints
1441 WantedConstraint mentions CtLoc
1442 CtLoc mentions ErrCtxt
1443 ErrCtxt mentions TcM
1444 * *
1445 v%************************************************************************
1446 -}
1447
1448 data WantedConstraints
1449 = WC { wc_simple :: Cts -- Unsolved constraints, all wanted
1450 , wc_impl :: Bag Implication
1451 , wc_insol :: Cts -- Insoluble constraints, can be
1452 -- wanted, given, or derived
1453 -- See Note [Insoluble constraints]
1454 }
1455
1456 emptyWC :: WantedConstraints
1457 emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
1458
1459 mkSimpleWC :: [CtEvidence] -> WantedConstraints
1460 mkSimpleWC cts
1461 = WC { wc_simple = listToBag (map mkNonCanonical cts)
1462 , wc_impl = emptyBag
1463 , wc_insol = emptyBag }
1464
1465 isEmptyWC :: WantedConstraints -> Bool
1466 isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_insol = n })
1467 = isEmptyBag f && isEmptyBag i && isEmptyBag n
1468
1469 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
1470 andWC (WC { wc_simple = f1, wc_impl = i1, wc_insol = n1 })
1471 (WC { wc_simple = f2, wc_impl = i2, wc_insol = n2 })
1472 = WC { wc_simple = f1 `unionBags` f2
1473 , wc_impl = i1 `unionBags` i2
1474 , wc_insol = n1 `unionBags` n2 }
1475
1476 unionsWC :: [WantedConstraints] -> WantedConstraints
1477 unionsWC = foldr andWC emptyWC
1478
1479 addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
1480 addSimples wc cts
1481 = wc { wc_simple = wc_simple wc `unionBags` cts }
1482 -- Consider: Put the new constraints at the front, so they get solved first
1483
1484 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
1485 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
1486
1487 addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
1488 addInsols wc cts
1489 = wc { wc_insol = wc_insol wc `unionBags` cts }
1490
1491 isInsolubleStatus :: ImplicStatus -> Bool
1492 isInsolubleStatus IC_Insoluble = True
1493 isInsolubleStatus _ = False
1494
1495 insolubleImplic :: Implication -> Bool
1496 insolubleImplic ic = isInsolubleStatus (ic_status ic)
1497
1498 insolubleWC :: WantedConstraints -> Bool
1499 insolubleWC (WC { wc_impl = implics, wc_insol = insols })
1500 = anyBag trulyInsoluble insols
1501 || anyBag insolubleImplic implics
1502
1503 trulyInsoluble :: Ct -> Bool
1504 -- The constraint is in the wc_insol set,
1505 -- but we do not treat as truly isoluble
1506 -- a) type-holes, arising from PartialTypeSignatures,
1507 -- b) superclass constraints, arising from the emitInsoluble
1508 -- in TcInstDcls.tcSuperClasses. In fact only equalities
1509 -- are truly-insoluble.
1510 -- Yuk!
1511 trulyInsoluble insol
1512 = isEqPred (ctPred insol)
1513 && not (isTypeHoleCt insol)
1514
1515 instance Outputable WantedConstraints where
1516 ppr (WC {wc_simple = s, wc_impl = i, wc_insol = n})
1517 = ptext (sLit "WC") <+> braces (vcat
1518 [ ppr_bag (ptext (sLit "wc_simple")) s
1519 , ppr_bag (ptext (sLit "wc_insol")) n
1520 , ppr_bag (ptext (sLit "wc_impl")) i ])
1521
1522 ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
1523 ppr_bag doc bag
1524 | isEmptyBag bag = empty
1525 | otherwise = hang (doc <+> equals)
1526 2 (foldrBag (($$) . ppr) empty bag)
1527
1528 {-
1529 ************************************************************************
1530 * *
1531 Implication constraints
1532 * *
1533 ************************************************************************
1534 -}
1535
1536 data Implication
1537 = Implic {
1538 ic_tclvl :: TcLevel, -- TcLevel: unification variables
1539 -- free in the environment
1540
1541 ic_skols :: [TcTyVar], -- Introduced skolems
1542 ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
1543 -- See Note [Shadowing in a constraint]
1544
1545 ic_given :: [EvVar], -- Given evidence variables
1546 -- (order does not matter)
1547 -- See Invariant (GivenInv) in TcType
1548
1549 ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
1550 -- False <=> ic_givens might have equalities
1551
1552 ic_env :: TcLclEnv, -- Gives the source location and error context
1553 -- for the implication, and hence for all the
1554 -- given evidence variables
1555
1556 ic_wanted :: WantedConstraints, -- The wanted
1557
1558 ic_binds :: EvBindsVar, -- Points to the place to fill in the
1559 -- abstraction and bindings
1560
1561 ic_status :: ImplicStatus
1562 }
1563
1564 data ImplicStatus
1565 = IC_Solved -- All wanteds in the tree are solved, all the way down
1566 { ics_need :: VarSet -- Evidence variables needed by this implication
1567 , ics_dead :: [EvVar] } -- Subset of ic_given that are not needed
1568 -- See Note [Tracking redundant constraints] in TcSimplify
1569
1570 | IC_Insoluble -- At least one insoluble constraint in the tree
1571
1572 | IC_Unsolved -- Neither of the above; might go either way
1573
1574 instance Outputable Implication where
1575 ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
1576 , ic_given = given, ic_no_eqs = no_eqs
1577 , ic_wanted = wanted, ic_status = status
1578 , ic_binds = binds, ic_info = info })
1579 = hang (ptext (sLit "Implic") <+> lbrace)
1580 2 (sep [ ptext (sLit "TcLevel =") <+> ppr tclvl
1581 , ptext (sLit "Skolems =") <+> pprTvBndrs skols
1582 , ptext (sLit "No-eqs =") <+> ppr no_eqs
1583 , ptext (sLit "Status =") <+> ppr status
1584 , hang (ptext (sLit "Given =")) 2 (pprEvVars given)
1585 , hang (ptext (sLit "Wanted =")) 2 (ppr wanted)
1586 , ptext (sLit "Binds =") <+> ppr binds
1587 , pprSkolInfo info ] <+> rbrace)
1588
1589 instance Outputable ImplicStatus where
1590 ppr IC_Insoluble = ptext (sLit "Insoluble")
1591 ppr IC_Unsolved = ptext (sLit "Unsolved")
1592 ppr (IC_Solved { ics_need = vs, ics_dead = dead })
1593 = ptext (sLit "Solved")
1594 <+> (braces $ vcat [ ptext (sLit "Dead givens =") <+> ppr dead
1595 , ptext (sLit "Needed =") <+> ppr vs ])
1596
1597 {-
1598 Note [Needed evidence variables]
1599 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1600 Th ic_need_evs field holds the free vars of ic_binds, and all the
1601 ic_binds in nested implications.
1602
1603 * Main purpose: if one of the ic_givens is not mentioned in here, it
1604 is redundant.
1605
1606 * solveImplication may drop an implication altogether if it has no
1607 remaining 'wanteds'. But we still track the free vars of its
1608 evidence binds, even though it has now disappeared.
1609
1610 Note [Shadowing in a constraint]
1611 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1612 We assume NO SHADOWING in a constraint. Specifically
1613 * The unification variables are all implicitly quantified at top
1614 level, and are all unique
1615 * The skolem varibles bound in ic_skols are all freah when the
1616 implication is created.
1617 So we can safely substitute. For example, if we have
1618 forall a. a~Int => ...(forall b. ...a...)...
1619 we can push the (a~Int) constraint inwards in the "givens" without
1620 worrying that 'b' might clash.
1621
1622 Note [Skolems in an implication]
1623 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1624 The skolems in an implication are not there to perform a skolem escape
1625 check. That happens because all the environment variables are in the
1626 untouchables, and therefore cannot be unified with anything at all,
1627 let alone the skolems.
1628
1629 Instead, ic_skols is used only when considering floating a constraint
1630 outside the implication in TcSimplify.floatEqualities or
1631 TcSimplify.approximateImplications
1632
1633 Note [Insoluble constraints]
1634 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1635 Some of the errors that we get during canonicalization are best
1636 reported when all constraints have been simplified as much as
1637 possible. For instance, assume that during simplification the
1638 following constraints arise:
1639
1640 [Wanted] F alpha ~ uf1
1641 [Wanted] beta ~ uf1 beta
1642
1643 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
1644 we will simply see a message:
1645 'Can't construct the infinite type beta ~ uf1 beta'
1646 and the user has no idea what the uf1 variable is.
1647
1648 Instead our plan is that we will NOT fail immediately, but:
1649 (1) Record the "frozen" error in the ic_insols field
1650 (2) Isolate the offending constraint from the rest of the inerts
1651 (3) Keep on simplifying/canonicalizing
1652
1653 At the end, we will hopefully have substituted uf1 := F alpha, and we
1654 will be able to report a more informative error:
1655 'Can't construct the infinite type beta ~ F alpha beta'
1656
1657 Insoluble constraints *do* include Derived constraints. For example,
1658 a functional dependency might give rise to [D] Int ~ Bool, and we must
1659 report that. If insolubles did not contain Deriveds, reportErrors would
1660 never see it.
1661
1662
1663 ************************************************************************
1664 * *
1665 Pretty printing
1666 * *
1667 ************************************************************************
1668 -}
1669
1670 pprEvVars :: [EvVar] -> SDoc -- Print with their types
1671 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
1672
1673 pprEvVarTheta :: [EvVar] -> SDoc
1674 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
1675
1676 pprEvVarWithType :: EvVar -> SDoc
1677 pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
1678
1679 {-
1680 ************************************************************************
1681 * *
1682 CtEvidence
1683 * *
1684 ************************************************************************
1685
1686 Note [Evidence field of CtEvidence]
1687 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1688 During constraint solving we never look at the type of ctev_evar;
1689 instead we look at the cte_pred field. The evtm/evar field
1690 may be un-zonked.
1691
1692 Note [Bind new Givens immediately]
1693 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1694 For Givens we make new EvVars and bind them immediately. Two main reasons:
1695 * Gain sharing. E.g. suppose we start with g :: C a b, where
1696 class D a => C a b
1697 class (E a, F a) => D a
1698 If we generate all g's superclasses as separate EvTerms we might
1699 get selD1 (selC1 g) :: E a
1700 selD2 (selC1 g) :: F a
1701 selC1 g :: D a
1702 which we could do more economically as:
1703 g1 :: D a = selC1 g
1704 g2 :: E a = selD1 g1
1705 g3 :: F a = selD2 g1
1706
1707 * For *coercion* evidence we *must* bind each given:
1708 class (a~b) => C a b where ....
1709 f :: C a b => ....
1710 Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
1711 But that superclass selector can't (yet) appear in a coercion
1712 (see evTermCoercion), so the easy thing is to bind it to an Id.
1713
1714 So a Given has EvVar inside it rather that (as previously) an EvTerm.
1715 -}
1716
1717
1718 data CtEvidence
1719 = CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1720 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
1721 , ctev_loc :: CtLoc }
1722 -- Truly given, not depending on subgoals
1723 -- NB: Spontaneous unifications belong here
1724
1725 | CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1726 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
1727 , ctev_loc :: CtLoc }
1728 -- Wanted goal
1729
1730 | CtDerived { ctev_pred :: TcPredType
1731 , ctev_loc :: CtLoc }
1732 -- A goal that we don't really have to solve and can't immediately
1733 -- rewrite anything other than a derived (there's no evidence!)
1734 -- but if we do manage to solve it may help in solving other goals.
1735
1736 ctEvPred :: CtEvidence -> TcPredType
1737 -- The predicate of a flavor
1738 ctEvPred = ctev_pred
1739
1740 ctEvLoc :: CtEvidence -> CtLoc
1741 ctEvLoc = ctev_loc
1742
1743 -- | Get the equality relation relevant for a 'CtEvidence'
1744 ctEvEqRel :: CtEvidence -> EqRel
1745 ctEvEqRel = predTypeEqRel . ctEvPred
1746
1747 -- | Get the role relevant for a 'CtEvidence'
1748 ctEvRole :: CtEvidence -> Role
1749 ctEvRole = eqRelRole . ctEvEqRel
1750
1751 ctEvTerm :: CtEvidence -> EvTerm
1752 ctEvTerm ev = EvId (ctEvId ev)
1753
1754 ctEvCoercion :: CtEvidence -> TcCoercion
1755 ctEvCoercion ev = mkTcCoVarCo (ctEvId ev)
1756
1757 ctEvId :: CtEvidence -> TcId
1758 ctEvId (CtWanted { ctev_evar = ev }) = ev
1759 ctEvId (CtGiven { ctev_evar = ev }) = ev
1760 ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
1761
1762 instance Outputable CtEvidence where
1763 ppr fl = case fl of
1764 CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evar fl) <+> ppr_pty
1765 CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
1766 CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
1767 where ppr_pty = dcolon <+> ppr (ctEvPred fl)
1768
1769 isWanted :: CtEvidence -> Bool
1770 isWanted (CtWanted {}) = True
1771 isWanted _ = False
1772
1773 isGiven :: CtEvidence -> Bool
1774 isGiven (CtGiven {}) = True
1775 isGiven _ = False
1776
1777 isDerived :: CtEvidence -> Bool
1778 isDerived (CtDerived {}) = True
1779 isDerived _ = False
1780
1781 {-
1782 %************************************************************************
1783 %* *
1784 CtFlavour
1785 %* *
1786 %************************************************************************
1787
1788 Just an enum type that tracks whether a constraint is wanted, derived,
1789 or given, when we need to separate that info from the constraint itself.
1790
1791 -}
1792
1793 data CtFlavour = Given | Wanted | Derived
1794 deriving Eq
1795
1796 instance Outputable CtFlavour where
1797 ppr Given = text "[G]"
1798 ppr Wanted = text "[W]"
1799 ppr Derived = text "[D]"
1800
1801 ctEvFlavour :: CtEvidence -> CtFlavour
1802 ctEvFlavour (CtWanted {}) = Wanted
1803 ctEvFlavour (CtGiven {}) = Given
1804 ctEvFlavour (CtDerived {}) = Derived
1805
1806 {-
1807 ************************************************************************
1808 * *
1809 SubGoalDepth
1810 * *
1811 ************************************************************************
1812
1813 Note [SubGoalDepth]
1814 ~~~~~~~~~~~~~~~~~~~
1815 The 'SubGoalDepth' takes care of stopping the constraint solver from looping.
1816
1817 The counter starts at zero and increases. It includes dictionary constraints,
1818 equality simplification, and type family reduction. (Why combine these? Because
1819 it's actually quite easy to mistake one for another, in sufficiently involved
1820 scenarios, like ConstraintKinds.)
1821
1822 The flag -fcontext-stack=n (not very well named!) fixes the maximium
1823 level.
1824
1825 * The counter includes the depth of type class instance declarations. Example:
1826 [W] d{7} : Eq [Int]
1827 That is d's dictionary-constraint depth is 7. If we use the instance
1828 $dfEqList :: Eq a => Eq [a]
1829 to simplify it, we get
1830 d{7} = $dfEqList d'{8}
1831 where d'{8} : Eq Int, and d' has depth 8.
1832
1833 For civilised (decidable) instance declarations, each increase of
1834 depth removes a type constructor from the type, so the depth never
1835 gets big; i.e. is bounded by the structural depth of the type.
1836
1837 * The counter also increments when resolving
1838 equalities involving type functions. Example:
1839 Assume we have a wanted at depth 7:
1840 [W] d{7} : F () ~ a
1841 If thre is an type function equation "F () = Int", this would be rewritten to
1842 [W] d{8} : Int ~ a
1843 and remembered as having depth 8.
1844
1845 Again, without UndecidableInstances, this counter is bounded, but without it
1846 can resolve things ad infinitum. Hence there is a maximum level.
1847
1848 * Lastly, every time an equality is rewritten, the counter increases. Again,
1849 rewriting an equality constraint normally makes progress, but it's possible
1850 the "progress" is just the reduction of an infinitely-reducing type family.
1851 Hence we need to track the rewrites.
1852
1853 When compiling a program requires a greater depth, then GHC recommends turning
1854 off this check entirely by setting -freduction-depth=0. This is because the
1855 exact number that works is highly variable, and is likely to change even between
1856 minor releases. Because this check is solely to prevent infinite compilation
1857 times, it seems safe to disable it when a user has ascertained that their program
1858 doesn't loop at the type level.
1859
1860 -}
1861
1862 -- | See Note [SubGoalDepth]
1863 newtype SubGoalDepth = SubGoalDepth Int
1864 deriving (Eq, Ord, Outputable)
1865
1866 initialSubGoalDepth :: SubGoalDepth
1867 initialSubGoalDepth = SubGoalDepth 0
1868
1869 bumpSubGoalDepth :: SubGoalDepth -> SubGoalDepth
1870 bumpSubGoalDepth (SubGoalDepth n) = SubGoalDepth (n + 1)
1871
1872 subGoalDepthExceeded :: DynFlags -> SubGoalDepth -> Bool
1873 subGoalDepthExceeded dflags (SubGoalDepth d)
1874 = mkIntWithInf d > reductionDepth dflags
1875
1876 {-
1877 ************************************************************************
1878 * *
1879 CtLoc
1880 * *
1881 ************************************************************************
1882
1883 The 'CtLoc' gives information about where a constraint came from.
1884 This is important for decent error message reporting because
1885 dictionaries don't appear in the original source code.
1886 type will evolve...
1887 -}
1888
1889 data CtLoc = CtLoc { ctl_origin :: CtOrigin
1890 , ctl_env :: TcLclEnv
1891 , ctl_depth :: !SubGoalDepth }
1892 -- The TcLclEnv includes particularly
1893 -- source location: tcl_loc :: RealSrcSpan
1894 -- context: tcl_ctxt :: [ErrCtxt]
1895 -- binder stack: tcl_bndrs :: TcIdBinderStack
1896 -- level: tcl_tclvl :: TcLevel
1897
1898 mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
1899 mkGivenLoc tclvl skol_info env
1900 = CtLoc { ctl_origin = GivenOrigin skol_info
1901 , ctl_env = env { tcl_tclvl = tclvl }
1902 , ctl_depth = initialSubGoalDepth }
1903
1904 ctLocEnv :: CtLoc -> TcLclEnv
1905 ctLocEnv = ctl_env
1906
1907 ctLocLevel :: CtLoc -> TcLevel
1908 ctLocLevel loc = tcl_tclvl (ctLocEnv loc)
1909
1910 ctLocDepth :: CtLoc -> SubGoalDepth
1911 ctLocDepth = ctl_depth
1912
1913 ctLocOrigin :: CtLoc -> CtOrigin
1914 ctLocOrigin = ctl_origin
1915
1916 ctLocSpan :: CtLoc -> RealSrcSpan
1917 ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
1918
1919 setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
1920 setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
1921
1922 bumpCtLocDepth :: CtLoc -> CtLoc
1923 bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth d }
1924
1925 setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
1926 setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
1927
1928 setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
1929 setCtLocEnv ctl env = ctl { ctl_env = env }
1930
1931 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
1932 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
1933 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
1934
1935 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
1936 -- Just add information w/o updating the origin!
1937 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
1938 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
1939
1940 pprArising :: CtOrigin -> SDoc
1941 -- Used for the main, top-level error message
1942 -- We've done special processing for TypeEq and FunDep origins
1943 pprArising (TypeEqOrigin {}) = empty
1944 pprArising orig = pprCtOrigin orig
1945
1946 pprArisingAt :: CtLoc -> SDoc
1947 pprArisingAt (CtLoc { ctl_origin = o, ctl_env = lcl})
1948 = sep [ pprCtOrigin o
1949 , text "at" <+> ppr (tcl_loc lcl)]
1950
1951 {-
1952 ************************************************************************
1953 * *
1954 SkolemInfo
1955 * *
1956 ************************************************************************
1957 -}
1958
1959 -- SkolemInfo gives the origin of *given* constraints
1960 -- a) type variables are skolemised
1961 -- b) an implication constraint is generated
1962 data SkolemInfo
1963 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
1964 Type -- a programmer-supplied type signature
1965 -- Location of the binding site is on the TyVar
1966
1967 -- The rest are for non-scoped skolems
1968 | ClsSkol Class -- Bound at a class decl
1969
1970 | InstSkol -- Bound at an instance decl
1971 | InstSC TypeSize -- A "given" constraint obtained by superclass selection
1972 -- from an InstSkol, giving the largest class from
1973 -- which we made a superclass selection in the chain
1974 -- See Note [Solving superclass constraints] in TcInstDcls
1975
1976 | DataSkol -- Bound at a data type declaration
1977 | FamInstSkol -- Bound at a family instance decl
1978 | PatSkol -- An existential type variable bound by a pattern for
1979 ConLike -- a data constructor with an existential type.
1980 (HsMatchContext Name)
1981 -- e.g. data T = forall a. Eq a => MkT a
1982 -- f (MkT x) = ...
1983 -- The pattern MkT x will allocate an existential type
1984 -- variable for 'a'.
1985
1986 | ArrowSkol -- An arrow form (see TcArrows)
1987
1988 | IPSkol [HsIPName] -- Binding site of an implicit parameter
1989
1990 | RuleSkol RuleName -- The LHS of a RULE
1991
1992 | InferSkol [(Name,TcType)]
1993 -- We have inferred a type for these (mutually-recursivive)
1994 -- polymorphic Ids, and are now checking that their RHS
1995 -- constraints are satisfied.
1996
1997 | BracketSkol -- Template Haskell bracket
1998
1999 | UnifyForAllSkol -- We are unifying two for-all types
2000 [TcTyVar] -- The instantiated skolem variables
2001 TcType -- The instantiated type *inside* the forall
2002
2003 | UnkSkol -- Unhelpful info (until I improve it)
2004
2005 instance Outputable SkolemInfo where
2006 ppr = pprSkolInfo
2007
2008 pprSkolInfo :: SkolemInfo -> SDoc
2009 -- Complete the sentence "is a rigid type variable bound by..."
2010 pprSkolInfo (SigSkol ctxt ty) = pprSigSkolInfo ctxt ty
2011 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter binding") <> plural ips <+> ptext (sLit "for")
2012 <+> pprWithCommas ppr ips
2013 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
2014 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
2015 pprSkolInfo (InstSC n) = ptext (sLit "the instance declaration") <> ifPprDebug (parens (ppr n))
2016 pprSkolInfo DataSkol = ptext (sLit "a data type declaration")
2017 pprSkolInfo FamInstSkol = ptext (sLit "a family instance declaration")
2018 pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
2019 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
2020 pprSkolInfo ArrowSkol = ptext (sLit "an arrow form")
2021 pprSkolInfo (PatSkol cl mc) = sep [ pprPatSkolInfo cl
2022 , ptext (sLit "in") <+> pprMatchContext mc ]
2023 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
2024 , vcat [ ppr name <+> dcolon <+> ppr ty
2025 | (name,ty) <- ids ]]
2026 pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
2027
2028 -- UnkSkol
2029 -- For type variables the others are dealt with by pprSkolTvBinding.
2030 -- For Insts, these cases should not happen
2031 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
2032
2033 pprSigSkolInfo :: UserTypeCtxt -> Type -> SDoc
2034 pprSigSkolInfo ctxt ty
2035 = case ctxt of
2036 FunSigCtxt f _ -> pp_sig f
2037 _ -> hang (pprUserTypeCtxt ctxt <> colon)
2038 2 (ppr ty)
2039 where
2040 pp_sig f = sep [ ptext (sLit "the type signature for:")
2041 , pprPrefixOcc f <+> dcolon <+> ppr ty ]
2042
2043 pprPatSkolInfo :: ConLike -> SDoc
2044 pprPatSkolInfo (RealDataCon dc)
2045 = sep [ ptext (sLit "a pattern with constructor:")
2046 , nest 2 $ ppr dc <+> dcolon
2047 <+> pprType (dataConUserType dc) <> comma ]
2048 -- pprType prints forall's regardless of -fprint-explict-foralls
2049 -- which is what we want here, since we might be saying
2050 -- type variable 't' is bound by ...
2051
2052 pprPatSkolInfo (PatSynCon ps)
2053 = sep [ ptext (sLit "a pattern with pattern synonym:")
2054 , nest 2 $ ppr ps <+> dcolon
2055 <+> pprType (patSynType ps) <> comma ]
2056
2057 {-
2058 ************************************************************************
2059 * *
2060 CtOrigin
2061 * *
2062 ************************************************************************
2063 -}
2064
2065 data CtOrigin
2066 = GivenOrigin SkolemInfo
2067
2068 -- All the others are for *wanted* constraints
2069 | OccurrenceOf Name -- Occurrence of an overloaded identifier
2070 | AppOrigin -- An application of some kind
2071
2072 | SpecPragOrigin UserTypeCtxt -- Specialisation pragma for
2073 -- function or instance
2074
2075 | TypeEqOrigin { uo_actual :: TcType
2076 , uo_expected :: TcType }
2077 | KindEqOrigin
2078 TcType TcType -- A kind equality arising from unifying these two types
2079 CtOrigin -- originally arising from this
2080 | CoercibleOrigin TcType TcType -- a Coercible constraint
2081
2082 | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
2083
2084 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
2085 | NegateOrigin -- Occurrence of syntactic negation
2086
2087 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
2088 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
2089 | SectionOrigin
2090 | TupleOrigin -- (..,..)
2091 | ExprSigOrigin -- e :: ty
2092 | PatSigOrigin -- p :: ty
2093 | PatOrigin -- Instantiating a polytyped pattern at a constructor
2094 | RecordUpdOrigin
2095 | ViewPatOrigin
2096
2097 | ScOrigin TypeSize -- Typechecking superclasses of an instance declaration
2098 -- whose head has the given size
2099 -- See Note [Solving superclass constraints] in TcInstDcls
2100
2101 | DerivOrigin -- Typechecking deriving
2102 | DerivOriginDC DataCon Int
2103 -- Checking constraints arising from this data con and field index
2104 | DerivOriginCoerce Id Type Type
2105 -- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
2106 -- `ty1` to `ty2`.
2107 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
2108 | DefaultOrigin -- Typechecking a default decl
2109 | DoOrigin -- Arising from a do expression
2110 | MCompOrigin -- Arising from a monad comprehension
2111 | IfOrigin -- Arising from an if statement
2112 | ProcOrigin -- Arising from a proc expression
2113 | AnnOrigin -- An annotation
2114
2115 | FunDepOrigin1 -- A functional dependency from combining
2116 PredType CtLoc -- This constraint arising from ...
2117 PredType CtLoc -- and this constraint arising from ...
2118
2119 | FunDepOrigin2 -- A functional dependency from combining
2120 PredType CtOrigin -- This constraint arising from ...
2121 PredType SrcSpan -- and this instance
2122 -- We only need a CtOrigin on the first, because the location
2123 -- is pinned on the entire error message
2124
2125 | HoleOrigin
2126 | UnboundOccurrenceOf RdrName
2127 | ListOrigin -- An overloaded list
2128 | StaticOrigin -- A static form
2129
2130 ctoHerald :: SDoc
2131 ctoHerald = ptext (sLit "arising from")
2132
2133 pprCtOrigin :: CtOrigin -> SDoc
2134
2135 pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
2136
2137 pprCtOrigin (SpecPragOrigin ctxt)
2138 = case ctxt of
2139 FunSigCtxt n _ -> ptext (sLit "a SPECIALISE pragma for") <+> quotes (ppr n)
2140 SpecInstCtxt -> ptext (sLit "a SPECIALISE INSTANCE pragma")
2141 _ -> ptext (sLit "a SPECIALISE pragma") -- Never happens I think
2142
2143 pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
2144 = hang (ctoHerald <+> ptext (sLit "a functional dependency between constraints:"))
2145 2 (vcat [ hang (quotes (ppr pred1)) 2 (pprArisingAt loc1)
2146 , hang (quotes (ppr pred2)) 2 (pprArisingAt loc2) ])
2147
2148 pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
2149 = hang (ctoHerald <+> ptext (sLit "a functional dependency between:"))
2150 2 (vcat [ hang (ptext (sLit "constraint") <+> quotes (ppr pred1))
2151 2 (pprArising orig1 )
2152 , hang (ptext (sLit "instance") <+> quotes (ppr pred2))
2153 2 (ptext (sLit "at") <+> ppr loc2) ])
2154
2155 pprCtOrigin (KindEqOrigin t1 t2 _)
2156 = hang (ctoHerald <+> ptext (sLit "a kind equality arising from"))
2157 2 (sep [ppr t1, char '~', ppr t2])
2158
2159 pprCtOrigin (UnboundOccurrenceOf name)
2160 = ctoHerald <+> ptext (sLit "an undeclared identifier") <+> quotes (ppr name)
2161
2162 pprCtOrigin (DerivOriginDC dc n)
2163 = hang (ctoHerald <+> ptext (sLit "the") <+> speakNth n
2164 <+> ptext (sLit "field of") <+> quotes (ppr dc))
2165 2 (parens (ptext (sLit "type") <+> quotes (ppr ty)))
2166 where
2167 ty = dataConOrigArgTys dc !! (n-1)
2168
2169 pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
2170 = hang (ctoHerald <+> ptext (sLit "the coercion of the method") <+> quotes (ppr meth))
2171 2 (sep [ text "from type" <+> quotes (ppr ty1)
2172 , nest 2 $ text "to type" <+> quotes (ppr ty2) ])
2173
2174 pprCtOrigin (CoercibleOrigin ty1 ty2)
2175 = hang (ctoHerald <+> text "trying to show that the representations of")
2176 2 (quotes (ppr ty1) <+> text "and" $$
2177 quotes (ppr ty2) <+> text "are the same")
2178
2179 pprCtOrigin simple_origin
2180 = ctoHerald <+> pprCtO simple_origin
2181
2182 ----------------
2183 pprCtO :: CtOrigin -> SDoc -- Ones that are short one-liners
2184 pprCtO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
2185 pprCtO AppOrigin = ptext (sLit "an application")
2186 pprCtO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
2187 pprCtO RecordUpdOrigin = ptext (sLit "a record update")
2188 pprCtO ExprSigOrigin = ptext (sLit "an expression type signature")
2189 pprCtO PatSigOrigin = ptext (sLit "a pattern type signature")
2190 pprCtO PatOrigin = ptext (sLit "a pattern")
2191 pprCtO ViewPatOrigin = ptext (sLit "a view pattern")
2192 pprCtO IfOrigin = ptext (sLit "an if statement")
2193 pprCtO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
2194 pprCtO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
2195 pprCtO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
2196 pprCtO SectionOrigin = ptext (sLit "an operator section")
2197 pprCtO TupleOrigin = ptext (sLit "a tuple")
2198 pprCtO NegateOrigin = ptext (sLit "a use of syntactic negation")
2199 pprCtO (ScOrigin n) = ptext (sLit "the superclasses of an instance declaration")
2200 <> ifPprDebug (parens (ppr n))
2201 pprCtO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
2202 pprCtO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
2203 pprCtO DefaultOrigin = ptext (sLit "a 'default' declaration")
2204 pprCtO DoOrigin = ptext (sLit "a do statement")
2205 pprCtO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
2206 pprCtO ProcOrigin = ptext (sLit "a proc expression")
2207 pprCtO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
2208 pprCtO AnnOrigin = ptext (sLit "an annotation")
2209 pprCtO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
2210 pprCtO ListOrigin = ptext (sLit "an overloaded list")
2211 pprCtO StaticOrigin = ptext (sLit "a static form")
2212 pprCtO _ = panic "pprCtOrigin"
2213
2214 {-
2215 Constraint Solver Plugins
2216 -------------------------
2217 -}
2218
2219 type TcPluginSolver = [Ct] -- given
2220 -> [Ct] -- derived
2221 -> [Ct] -- wanted
2222 -> TcPluginM TcPluginResult
2223
2224 newtype TcPluginM a = TcPluginM (Maybe EvBindsVar -> TcM a)
2225
2226 instance Functor TcPluginM where
2227 fmap = liftM
2228
2229 instance Applicative TcPluginM where
2230 pure = return
2231 (<*>) = ap
2232
2233 instance Monad TcPluginM where
2234 return x = TcPluginM (const $ return x)
2235 fail x = TcPluginM (const $ fail x)
2236 TcPluginM m >>= k =
2237 TcPluginM (\ ev -> do a <- m ev
2238 runTcPluginM (k a) ev)
2239
2240 runTcPluginM :: TcPluginM a -> Maybe EvBindsVar -> TcM a
2241 runTcPluginM (TcPluginM m) = m
2242
2243 -- | This function provides an escape for direct access to
2244 -- the 'TcM` monad. It should not be used lightly, and
2245 -- the provided 'TcPluginM' API should be favoured instead.
2246 unsafeTcPluginTcM :: TcM a -> TcPluginM a
2247 unsafeTcPluginTcM = TcPluginM . const
2248
2249 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
2250 -- constraint solving. Returns 'Nothing' if invoked during
2251 -- 'tcPluginInit' or 'tcPluginStop'.
2252 getEvBindsTcPluginM_maybe :: TcPluginM (Maybe EvBindsVar)
2253 getEvBindsTcPluginM_maybe = TcPluginM return
2254
2255
2256 data TcPlugin = forall s. TcPlugin
2257 { tcPluginInit :: TcPluginM s
2258 -- ^ Initialize plugin, when entering type-checker.
2259
2260 , tcPluginSolve :: s -> TcPluginSolver
2261 -- ^ Solve some constraints.
2262 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
2263
2264 , tcPluginStop :: s -> TcPluginM ()
2265 -- ^ Clean up after the plugin, when exiting the type-checker.
2266 }
2267
2268 data TcPluginResult
2269 = TcPluginContradiction [Ct]
2270 -- ^ The plugin found a contradiction.
2271 -- The returned constraints are removed from the inert set,
2272 -- and recorded as insoluable.
2273
2274 | TcPluginOk [(EvTerm,Ct)] [Ct]
2275 -- ^ The first field is for constraints that were solved.
2276 -- These are removed from the inert set,
2277 -- and the evidence for them is recorded.
2278 -- The second field contains new work, that should be processed by
2279 -- the constraint solver.