Clean outdated ext-core references in comments.
[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 tcVisibleOrphanMods,
30
31 -- Renamer types
32 ErrCtxt, RecFieldEnv(..),
33 ImportAvails(..), emptyImportAvails, plusImportAvails,
34 WhereFrom(..), mkModDeps,
35
36 -- Typechecker types
37 TcTypeEnv, TcIdBinderStack, TcIdBinder(..),
38 TcTyThing(..), PromotionErr(..),
39 pprTcTyThingCategory, pprPECategory,
40
41 -- Desugaring types
42 DsM, DsLclEnv(..), DsGblEnv(..), PArrBuiltin(..),
43 DsMetaEnv, DsMetaVal(..),
44
45 -- Template Haskell
46 ThStage(..), PendingStuff(..), topStage, topAnnStage, topSpliceStage,
47 ThLevel, impLevel, outerLevel, thLevel,
48
49 -- Arrows
50 ArrowCtxt(..),
51
52 -- Canonical constraints
53 Xi, Ct(..), Cts, emptyCts, andCts, andManyCts, pprCts,
54 singleCt, listToCts, ctsElts, consCts, snocCts, extendCtsList,
55 isEmptyCts, isCTyEqCan, isCFunEqCan,
56 isCDictCan_Maybe, isCFunEqCan_maybe,
57 isCIrredEvCan, isCNonCanonical, isWantedCt, isDerivedCt,
58 isGivenCt, isHoleCt, isExprHoleCt, isTypeHoleCt,
59 ctEvidence, ctLoc, setCtLoc, ctPred, ctFlavour, ctEqRel, ctOrigin,
60 mkNonCanonical, mkNonCanonicalCt,
61 ctEvPred, ctEvLoc, ctEvOrigin, ctEvEqRel,
62 ctEvTerm, ctEvCoercion, ctEvId,
63
64 WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
65 andWC, unionsWC, addSimples, addImplics, mkSimpleWC, addInsols,
66 dropDerivedWC, dropDerivedSimples, dropDerivedInsols,
67 isDroppableDerivedLoc, insolubleImplic, trulyInsoluble,
68
69 Implication(..), ImplicStatus(..), isInsolubleStatus,
70 SubGoalDepth, initialSubGoalDepth,
71 bumpSubGoalDepth, subGoalDepthExceeded,
72 CtLoc(..), ctLocSpan, ctLocEnv, ctLocLevel, ctLocOrigin,
73 ctLocDepth, bumpCtLocDepth,
74 setCtLocOrigin, setCtLocEnv, setCtLocSpan,
75 CtOrigin(..), pprCtOrigin, pprCtLoc,
76 pushErrCtxt, pushErrCtxtSameOrigin,
77
78 SkolemInfo(..),
79
80 CtEvidence(..),
81 mkGivenLoc,
82 isWanted, isGiven, isDerived,
83 ctEvRole,
84
85 -- Constraint solver plugins
86 TcPlugin(..), TcPluginResult(..), TcPluginSolver,
87 TcPluginM, runTcPluginM, unsafeTcPluginTcM,
88 getEvBindsTcPluginM_maybe,
89
90 CtFlavour(..), ctEvFlavour,
91 CtFlavourRole, ctEvFlavourRole, ctFlavourRole,
92 eqCanRewrite, eqCanRewriteFR, canDischarge, canDischargeF,
93
94 -- Pretty printing
95 pprEvVarTheta,
96 pprEvVars, pprEvVarWithType,
97
98 -- Misc other types
99 TcId, TcIdSet, HoleSort(..)
100
101 ) where
102
103 #include "HsVersions.h"
104
105 import HsSyn
106 import CoreSyn
107 import HscTypes
108 import TcEvidence
109 import Type
110 import CoAxiom ( Role )
111 import Class ( Class )
112 import TyCon ( TyCon )
113 import ConLike ( ConLike(..) )
114 import DataCon ( DataCon, dataConUserType, dataConOrigArgTys )
115 import PatSyn ( PatSyn, patSynType )
116 import TcType
117 import Annotations
118 import InstEnv
119 import FamInstEnv
120 import IOEnv
121 import RdrName
122 import Name
123 import NameEnv
124 import NameSet
125 import Avail
126 import Var
127 import VarEnv
128 import Module
129 import SrcLoc
130 import VarSet
131 import ErrUtils
132 import UniqFM
133 import UniqSupply
134 import BasicTypes
135 import Bag
136 import DynFlags
137 import Outputable
138 import ListSetOps
139 import FastString
140 import GHC.Fingerprint
141
142 import Data.Set (Set)
143 import Control.Monad (ap, liftM)
144
145 #ifdef GHCI
146 import Data.Map ( Map )
147 import Data.Dynamic ( Dynamic )
148 import Data.Typeable ( TypeRep )
149
150 import qualified Language.Haskell.TH as TH
151 #endif
152
153 {-
154 ************************************************************************
155 * *
156 Standard monad definition for TcRn
157 All the combinators for the monad can be found in TcRnMonad
158 * *
159 ************************************************************************
160
161 The monad itself has to be defined here, because it is mentioned by ErrCtxt
162 -}
163
164 type TcRnIf a b = IOEnv (Env a b)
165 type TcRn = TcRnIf TcGblEnv TcLclEnv -- Type inference
166 type IfM lcl = TcRnIf IfGblEnv lcl -- Iface stuff
167 type IfG = IfM () -- Top level
168 type IfL = IfM IfLclEnv -- Nested
169 type DsM = TcRnIf DsGblEnv DsLclEnv -- Desugaring
170
171 -- TcRn is the type-checking and renaming monad: the main monad that
172 -- most type-checking takes place in. The global environment is
173 -- 'TcGblEnv', which tracks all of the top-level type-checking
174 -- information we've accumulated while checking a module, while the
175 -- local environment is 'TcLclEnv', which tracks local information as
176 -- we move inside expressions.
177
178 -- | Historical "renaming monad" (now it's just 'TcRn').
179 type RnM = TcRn
180
181 -- | Historical "type-checking monad" (now it's just 'TcRn').
182 type TcM = TcRn
183
184 -- We 'stack' these envs through the Reader like monad infastructure
185 -- as we move into an expression (although the change is focused in
186 -- the lcl type).
187 data Env gbl lcl
188 = Env {
189 env_top :: HscEnv, -- Top-level stuff that never changes
190 -- Includes all info about imported things
191
192 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
193 -- Unique supply for local varibles
194
195 env_gbl :: gbl, -- Info about things defined at the top level
196 -- of the module being compiled
197
198 env_lcl :: lcl -- Nested stuff; changes as we go into
199 }
200
201 instance ContainsDynFlags (Env gbl lcl) where
202 extractDynFlags env = hsc_dflags (env_top env)
203 replaceDynFlags env dflags
204 = env {env_top = replaceDynFlags (env_top env) dflags}
205
206 instance ContainsModule gbl => ContainsModule (Env gbl lcl) where
207 extractModule env = extractModule (env_gbl env)
208
209
210 {-
211 ************************************************************************
212 * *
213 The interface environments
214 Used when dealing with IfaceDecls
215 * *
216 ************************************************************************
217 -}
218
219 data IfGblEnv
220 = IfGblEnv {
221 -- The type environment for the module being compiled,
222 -- in case the interface refers back to it via a reference that
223 -- was originally a hi-boot file.
224 -- We need the module name so we can test when it's appropriate
225 -- to look in this env.
226 if_rec_types :: Maybe (Module, IfG TypeEnv)
227 -- Allows a read effect, so it can be in a mutable
228 -- variable; c.f. handling the external package type env
229 -- Nothing => interactive stuff, no loops possible
230 }
231
232 data IfLclEnv
233 = IfLclEnv {
234 -- The module for the current IfaceDecl
235 -- So if we see f = \x -> x
236 -- it means M.f = \x -> x, where M is the if_mod
237 if_mod :: Module,
238
239 -- The field is used only for error reporting
240 -- if (say) there's a Lint error in it
241 if_loc :: SDoc,
242 -- Where the interface came from:
243 -- .hi file, or GHCi state, or ext core
244 -- plus which bit is currently being examined
245
246 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
247 -- (and coercions)
248 if_id_env :: UniqFM Id -- Nested id binding
249 }
250
251 {-
252 ************************************************************************
253 * *
254 Desugarer monad
255 * *
256 ************************************************************************
257
258 Now the mondo monad magic (yes, @DsM@ is a silly name)---carry around
259 a @UniqueSupply@ and some annotations, which
260 presumably include source-file location information:
261 -}
262
263 -- If '-XParallelArrays' is given, the desugarer populates this table with the corresponding
264 -- variables found in 'Data.Array.Parallel'.
265 --
266 data PArrBuiltin
267 = PArrBuiltin
268 { lengthPVar :: Var -- ^ lengthP
269 , replicatePVar :: Var -- ^ replicateP
270 , singletonPVar :: Var -- ^ singletonP
271 , mapPVar :: Var -- ^ mapP
272 , filterPVar :: Var -- ^ filterP
273 , zipPVar :: Var -- ^ zipP
274 , crossMapPVar :: Var -- ^ crossMapP
275 , indexPVar :: Var -- ^ (!:)
276 , emptyPVar :: Var -- ^ emptyP
277 , appPVar :: Var -- ^ (+:+)
278 , enumFromToPVar :: Var -- ^ enumFromToP
279 , enumFromThenToPVar :: Var -- ^ enumFromThenToP
280 }
281
282 data DsGblEnv
283 = DsGblEnv
284 { ds_mod :: Module -- For SCC profiling
285 , ds_fam_inst_env :: FamInstEnv -- Like tcg_fam_inst_env
286 , ds_unqual :: PrintUnqualified
287 , ds_msgs :: IORef Messages -- Warning messages
288 , ds_if_env :: (IfGblEnv, IfLclEnv) -- Used for looking up global,
289 -- possibly-imported things
290 , ds_dph_env :: GlobalRdrEnv -- exported entities of 'Data.Array.Parallel.Prim'
291 -- iff '-fvectorise' flag was given as well as
292 -- exported entities of 'Data.Array.Parallel' iff
293 -- '-XParallelArrays' was given; otherwise, empty
294 , ds_parr_bi :: PArrBuiltin -- desugarar names for '-XParallelArrays'
295 , ds_static_binds :: IORef [(Fingerprint, (Id,CoreExpr))]
296 -- ^ Bindings resulted from floating static forms
297 }
298
299 instance ContainsModule DsGblEnv where
300 extractModule = ds_mod
301
302 data DsLclEnv = DsLclEnv {
303 dsl_meta :: DsMetaEnv, -- Template Haskell bindings
304 dsl_loc :: SrcSpan -- to put in pattern-matching error msgs
305 }
306
307 -- Inside [| |] brackets, the desugarer looks
308 -- up variables in the DsMetaEnv
309 type DsMetaEnv = NameEnv DsMetaVal
310
311 data DsMetaVal
312 = DsBound Id -- Bound by a pattern inside the [| |].
313 -- Will be dynamically alpha renamed.
314 -- The Id has type THSyntax.Var
315
316 | DsSplice (HsExpr Id) -- These bindings are introduced by
317 -- the PendingSplices on a HsBracketOut
318
319
320 {-
321 ************************************************************************
322 * *
323 Global typechecker environment
324 * *
325 ************************************************************************
326 -}
327
328 -- | 'TcGblEnv' describes the top-level of the module at the
329 -- point at which the typechecker is finished work.
330 -- It is this structure that is handed on to the desugarer
331 -- For state that needs to be updated during the typechecking
332 -- phase and returned at end, use a 'TcRef' (= 'IORef').
333 data TcGblEnv
334 = TcGblEnv {
335 tcg_mod :: Module, -- ^ Module being compiled
336 tcg_src :: HscSource,
337 -- ^ What kind of module (regular Haskell, hs-boot, hsig)
338 tcg_sig_of :: Maybe Module,
339 -- ^ Are we being compiled as a signature of an implementation?
340 tcg_mod_name :: Maybe (Located ModuleName),
341 -- ^ @Nothing@: \"module X where\" is omitted
342 tcg_impl_rdr_env :: Maybe GlobalRdrEnv,
343 -- ^ Environment used only during -sig-of for resolving top level
344 -- bindings. See Note [Signature parameters in TcGblEnv and DynFlags]
345
346 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
347 tcg_default :: Maybe [Type],
348 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
349
350 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
351 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
352 -- See Note [The interactive package] in HscTypes
353
354 tcg_type_env :: TypeEnv,
355 -- ^ Global type env for the module we are compiling now. All
356 -- TyCons and Classes (for this module) end up in here right away,
357 -- along with their derived constructors, selectors.
358 --
359 -- (Ids defined in this module start in the local envt, though they
360 -- move to the global envt during zonking)
361 --
362 -- NB: for what "things in this module" means, see
363 -- Note [The interactive package] in HscTypes
364
365 tcg_type_env_var :: TcRef TypeEnv,
366 -- Used only to initialise the interface-file
367 -- typechecker in initIfaceTcRn, so that it can see stuff
368 -- bound in this module when dealing with hi-boot recursions
369 -- Updated at intervals (e.g. after dealing with types and classes)
370
371 tcg_inst_env :: InstEnv,
372 -- ^ Instance envt for all /home-package/ modules;
373 -- Includes the dfuns in tcg_insts
374 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
375 tcg_ann_env :: AnnEnv, -- ^ And for annotations
376
377 -- Now a bunch of things about this module that are simply
378 -- accumulated, but never consulted until the end.
379 -- Nevertheless, it's convenient to accumulate them along
380 -- with the rest of the info from this module.
381 tcg_exports :: [AvailInfo], -- ^ What is exported
382 tcg_imports :: ImportAvails,
383 -- ^ Information about what was imported from where, including
384 -- things bound in this module. Also store Safe Haskell info
385 -- here about transative trusted packaage requirements.
386
387 tcg_dus :: DefUses, -- ^ What is defined in this module and what is used.
388 tcg_used_rdrnames :: TcRef (Set RdrName),
389 -- See Note [Tracking unused binding and imports]
390
391 tcg_keep :: TcRef NameSet,
392 -- ^ Locally-defined top-level names to keep alive.
393 --
394 -- "Keep alive" means give them an Exported flag, so that the
395 -- simplifier does not discard them as dead code, and so that they
396 -- are exposed in the interface file (but not to export to the
397 -- user).
398 --
399 -- Some things, like dict-fun Ids and default-method Ids are "born"
400 -- with the Exported flag on, for exactly the above reason, but some
401 -- we only discover as we go. Specifically:
402 --
403 -- * The to/from functions for generic data types
404 --
405 -- * Top-level variables appearing free in the RHS of an orphan
406 -- rule
407 --
408 -- * Top-level variables appearing free in a TH bracket
409
410 tcg_th_used :: TcRef Bool,
411 -- ^ @True@ <=> Template Haskell syntax used.
412 --
413 -- We need this so that we can generate a dependency on the
414 -- Template Haskell package, because the desugarer is going
415 -- to emit loads of references to TH symbols. The reference
416 -- is implicit rather than explicit, so we have to zap a
417 -- mutable variable.
418
419 tcg_th_splice_used :: TcRef Bool,
420 -- ^ @True@ <=> A Template Haskell splice was used.
421 --
422 -- Splices disable recompilation avoidance (see #481)
423
424 tcg_dfun_n :: TcRef OccSet,
425 -- ^ Allows us to choose unique DFun names.
426
427 -- The next fields accumulate the payload of the module
428 -- The binds, rules and foreign-decl fields are collected
429 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
430
431 tcg_rn_exports :: Maybe [Located (IE Name)],
432 -- Nothing <=> no explicit export list
433
434 tcg_rn_imports :: [LImportDecl Name],
435 -- Keep the renamed imports regardless. They are not
436 -- voluminous and are needed if you want to report unused imports
437
438 tcg_rn_decls :: Maybe (HsGroup Name),
439 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
440 -- decls.
441
442 tcg_dependent_files :: TcRef [FilePath], -- ^ dependencies from addDependentFile
443
444 #ifdef GHCI
445 tcg_th_topdecls :: TcRef [LHsDecl RdrName],
446 -- ^ Top-level declarations from addTopDecls
447
448 tcg_th_topnames :: TcRef NameSet,
449 -- ^ Exact names bound in top-level declarations in tcg_th_topdecls
450
451 tcg_th_modfinalizers :: TcRef [TH.Q ()],
452 -- ^ Template Haskell module finalizers
453
454 tcg_th_state :: TcRef (Map TypeRep Dynamic),
455 -- ^ Template Haskell state
456 #endif /* GHCI */
457
458 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
459
460 -- Things defined in this module, or (in GHCi)
461 -- in the declarations for a single GHCi command.
462 -- For the latter, see Note [The interactive package] in HscTypes
463 tcg_binds :: LHsBinds Id, -- Value bindings in this module
464 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
465 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
466 tcg_warns :: Warnings, -- ...Warnings and deprecations
467 tcg_anns :: [Annotation], -- ...Annotations
468 tcg_tcs :: [TyCon], -- ...TyCons and Classes
469 tcg_insts :: [ClsInst], -- ...Instances
470 tcg_fam_insts :: [FamInst], -- ...Family instances
471 tcg_rules :: [LRuleDecl Id], -- ...Rules
472 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
473 tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
474 tcg_patsyns :: [PatSyn], -- ...Pattern synonyms
475
476 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
477 tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
478 -- prog uses hpc instrumentation.
479
480 tcg_main :: Maybe Name, -- ^ The Name of the main
481 -- function, if this module is
482 -- the main module.
483
484 tcg_safeInfer :: TcRef (Bool, WarningMessages),
485 -- ^ Has the typechecker inferred this module as -XSafe (Safe Haskell)
486 -- See Note [Safe Haskell Overlapping Instances Implementation],
487 -- although this is used for more than just that failure case.
488
489 tcg_tc_plugins :: [TcPluginSolver],
490 -- ^ A list of user-defined plugins for the constraint solver.
491
492 tcg_static_wc :: TcRef WantedConstraints
493 -- ^ Wanted constraints of static forms.
494 }
495
496 tcVisibleOrphanMods :: TcGblEnv -> ModuleSet
497 tcVisibleOrphanMods tcg_env
498 = mkModuleSet (tcg_mod tcg_env : imp_orphs (tcg_imports tcg_env))
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 setCtLoc :: Ct -> CtLoc -> Ct
1269 setCtLoc ct loc = ct { cc_ev = (cc_ev ct) { ctev_loc = loc } }
1270
1271 ctOrigin :: Ct -> CtOrigin
1272 ctOrigin = ctLocOrigin . ctLoc
1273
1274 ctPred :: Ct -> PredType
1275 -- See Note [Ct/evidence invariant]
1276 ctPred ct = ctEvPred (cc_ev ct)
1277
1278 -- | Get the flavour of the given 'Ct'
1279 ctFlavour :: Ct -> CtFlavour
1280 ctFlavour = ctEvFlavour . ctEvidence
1281
1282 -- | Get the equality relation for the given 'Ct'
1283 ctEqRel :: Ct -> EqRel
1284 ctEqRel = ctEvEqRel . ctEvidence
1285
1286 dropDerivedWC :: WantedConstraints -> WantedConstraints
1287 -- See Note [Dropping derived constraints]
1288 dropDerivedWC wc@(WC { wc_simple = simples, wc_insol = insols })
1289 = wc { wc_simple = dropDerivedSimples simples
1290 , wc_insol = dropDerivedInsols insols }
1291 -- The wc_impl implications are already (recursively) filtered
1292
1293 dropDerivedSimples :: Cts -> Cts
1294 dropDerivedSimples simples = filterBag isWantedCt simples
1295 -- simples are all Wanted or Derived
1296
1297 dropDerivedInsols :: Cts -> Cts
1298 -- See Note [Dropping derived constraints]
1299 dropDerivedInsols insols = filterBag keep insols
1300 where -- insols can include Given
1301 keep ct
1302 | isDerivedCt ct = not (isDroppableDerivedLoc (ctLoc ct))
1303 | otherwise = True
1304
1305 isDroppableDerivedLoc :: CtLoc -> Bool
1306 -- Note [Dropping derived constraints]
1307 isDroppableDerivedLoc loc
1308 = case ctLocOrigin loc of
1309 KindEqOrigin {} -> False
1310 GivenOrigin {} -> False
1311 FunDepOrigin1 {} -> False
1312 FunDepOrigin2 {} -> False
1313 _ -> True
1314
1315
1316 {- Note [Dropping derived constraints]
1317 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1318 In general we discard derived constraints at the end of constraint solving;
1319 see dropDerivedWC. For example
1320
1321 * If we have an unsolved [W] (Ord a), we don't want to complain about
1322 an unsolved [D] (Eq a) as well.
1323
1324 * If we have [W] a ~ Int, [W] a ~ Bool, improvement will generate
1325 [D] Int ~ Bool, and we don't want to report that because it's incomprehensible.
1326 That is why we don't rewrite wanteds with wanteds!
1327
1328 But (tiresomely) we do keep *some* Derived insolubles:
1329
1330 * Insoluble kind equalities (e.g. [D] * ~ (* -> *)) may arise from
1331 a type equality a ~ Int#, say. In future they'll be Wanted, not Derived,
1332 but at the moment they are Derived.
1333
1334 * Insoluble derived equalities (e.g. [D] Int ~ Bool) may arise from
1335 functional dependency interactions, either between Givens or
1336 Wanteds. It seems sensible to retain these:
1337 - For Givens they reflect unreachable code
1338 - For Wanteds it is arguably better to get a fundep error than
1339 a no-instance error (Trac #9612)
1340
1341 Moreover, we keep *all* derived insolubles under some circumstances:
1342
1343 * They are looked at by simplifyInfer, to decide whether to
1344 generalise. Example: [W] a ~ Int, [W] a ~ Bool
1345 We get [D] Int ~ Bool, and indeed the constraints are insoluble,
1346 and we want simplifyInfer to see that, even though we don't
1347 ultimately want to generate an (inexplicable) error message from
1348
1349 To distinguish these cases we use the CtOrigin.
1350
1351
1352 ************************************************************************
1353 * *
1354 CtEvidence
1355 The "flavor" of a canonical constraint
1356 * *
1357 ************************************************************************
1358 -}
1359
1360 isWantedCt :: Ct -> Bool
1361 isWantedCt = isWanted . cc_ev
1362
1363 isGivenCt :: Ct -> Bool
1364 isGivenCt = isGiven . cc_ev
1365
1366 isDerivedCt :: Ct -> Bool
1367 isDerivedCt = isDerived . cc_ev
1368
1369 isCTyEqCan :: Ct -> Bool
1370 isCTyEqCan (CTyEqCan {}) = True
1371 isCTyEqCan (CFunEqCan {}) = False
1372 isCTyEqCan _ = False
1373
1374 isCDictCan_Maybe :: Ct -> Maybe Class
1375 isCDictCan_Maybe (CDictCan {cc_class = cls }) = Just cls
1376 isCDictCan_Maybe _ = Nothing
1377
1378 isCIrredEvCan :: Ct -> Bool
1379 isCIrredEvCan (CIrredEvCan {}) = True
1380 isCIrredEvCan _ = False
1381
1382 isCFunEqCan_maybe :: Ct -> Maybe (TyCon, [Type])
1383 isCFunEqCan_maybe (CFunEqCan { cc_fun = tc, cc_tyargs = xis }) = Just (tc, xis)
1384 isCFunEqCan_maybe _ = Nothing
1385
1386 isCFunEqCan :: Ct -> Bool
1387 isCFunEqCan (CFunEqCan {}) = True
1388 isCFunEqCan _ = False
1389
1390 isCNonCanonical :: Ct -> Bool
1391 isCNonCanonical (CNonCanonical {}) = True
1392 isCNonCanonical _ = False
1393
1394 isHoleCt:: Ct -> Bool
1395 isHoleCt (CHoleCan {}) = True
1396 isHoleCt _ = False
1397
1398 isExprHoleCt :: Ct -> Bool
1399 isExprHoleCt (CHoleCan { cc_hole = ExprHole }) = True
1400 isExprHoleCt _ = False
1401
1402 isTypeHoleCt :: Ct -> Bool
1403 isTypeHoleCt (CHoleCan { cc_hole = TypeHole }) = True
1404 isTypeHoleCt _ = False
1405
1406 instance Outputable Ct where
1407 ppr ct = ppr (cc_ev ct) <+> parens (text ct_sort)
1408 where ct_sort = case ct of
1409 CTyEqCan {} -> "CTyEqCan"
1410 CFunEqCan {} -> "CFunEqCan"
1411 CNonCanonical {} -> "CNonCanonical"
1412 CDictCan {} -> "CDictCan"
1413 CIrredEvCan {} -> "CIrredEvCan"
1414 CHoleCan {} -> "CHoleCan"
1415
1416 singleCt :: Ct -> Cts
1417 singleCt = unitBag
1418
1419 andCts :: Cts -> Cts -> Cts
1420 andCts = unionBags
1421
1422 listToCts :: [Ct] -> Cts
1423 listToCts = listToBag
1424
1425 ctsElts :: Cts -> [Ct]
1426 ctsElts = bagToList
1427
1428 consCts :: Ct -> Cts -> Cts
1429 consCts = consBag
1430
1431 snocCts :: Cts -> Ct -> Cts
1432 snocCts = snocBag
1433
1434 extendCtsList :: Cts -> [Ct] -> Cts
1435 extendCtsList cts xs | null xs = cts
1436 | otherwise = cts `unionBags` listToBag xs
1437
1438 andManyCts :: [Cts] -> Cts
1439 andManyCts = unionManyBags
1440
1441 emptyCts :: Cts
1442 emptyCts = emptyBag
1443
1444 isEmptyCts :: Cts -> Bool
1445 isEmptyCts = isEmptyBag
1446
1447 pprCts :: Cts -> SDoc
1448 pprCts cts = vcat (map ppr (bagToList cts))
1449
1450 {-
1451 ************************************************************************
1452 * *
1453 Wanted constraints
1454 These are forced to be in TcRnTypes because
1455 TcLclEnv mentions WantedConstraints
1456 WantedConstraint mentions CtLoc
1457 CtLoc mentions ErrCtxt
1458 ErrCtxt mentions TcM
1459 * *
1460 v%************************************************************************
1461 -}
1462
1463 data WantedConstraints
1464 = WC { wc_simple :: Cts -- Unsolved constraints, all wanted
1465 , wc_impl :: Bag Implication
1466 , wc_insol :: Cts -- Insoluble constraints, can be
1467 -- wanted, given, or derived
1468 -- See Note [Insoluble constraints]
1469 }
1470
1471 emptyWC :: WantedConstraints
1472 emptyWC = WC { wc_simple = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
1473
1474 mkSimpleWC :: [CtEvidence] -> WantedConstraints
1475 mkSimpleWC cts
1476 = WC { wc_simple = listToBag (map mkNonCanonical cts)
1477 , wc_impl = emptyBag
1478 , wc_insol = emptyBag }
1479
1480 isEmptyWC :: WantedConstraints -> Bool
1481 isEmptyWC (WC { wc_simple = f, wc_impl = i, wc_insol = n })
1482 = isEmptyBag f && isEmptyBag i && isEmptyBag n
1483
1484 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
1485 andWC (WC { wc_simple = f1, wc_impl = i1, wc_insol = n1 })
1486 (WC { wc_simple = f2, wc_impl = i2, wc_insol = n2 })
1487 = WC { wc_simple = f1 `unionBags` f2
1488 , wc_impl = i1 `unionBags` i2
1489 , wc_insol = n1 `unionBags` n2 }
1490
1491 unionsWC :: [WantedConstraints] -> WantedConstraints
1492 unionsWC = foldr andWC emptyWC
1493
1494 addSimples :: WantedConstraints -> Bag Ct -> WantedConstraints
1495 addSimples wc cts
1496 = wc { wc_simple = wc_simple wc `unionBags` cts }
1497 -- Consider: Put the new constraints at the front, so they get solved first
1498
1499 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
1500 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
1501
1502 addInsols :: WantedConstraints -> Bag Ct -> WantedConstraints
1503 addInsols wc cts
1504 = wc { wc_insol = wc_insol wc `unionBags` cts }
1505
1506 isInsolubleStatus :: ImplicStatus -> Bool
1507 isInsolubleStatus IC_Insoluble = True
1508 isInsolubleStatus _ = False
1509
1510 insolubleImplic :: Implication -> Bool
1511 insolubleImplic ic = isInsolubleStatus (ic_status ic)
1512
1513 insolubleWC :: WantedConstraints -> Bool
1514 insolubleWC (WC { wc_impl = implics, wc_insol = insols })
1515 = anyBag trulyInsoluble insols
1516 || anyBag insolubleImplic implics
1517
1518 trulyInsoluble :: Ct -> Bool
1519 -- The constraint is in the wc_insol set,
1520 -- but we do not treat as truly isoluble
1521 -- a) type-holes, arising from PartialTypeSignatures,
1522 -- b) superclass constraints, arising from the emitInsoluble
1523 -- in TcInstDcls.tcSuperClasses. In fact only equalities
1524 -- are truly-insoluble.
1525 -- Yuk!
1526 trulyInsoluble insol
1527 = isEqPred (ctPred insol)
1528 && not (isTypeHoleCt insol)
1529
1530 instance Outputable WantedConstraints where
1531 ppr (WC {wc_simple = s, wc_impl = i, wc_insol = n})
1532 = ptext (sLit "WC") <+> braces (vcat
1533 [ ppr_bag (ptext (sLit "wc_simple")) s
1534 , ppr_bag (ptext (sLit "wc_insol")) n
1535 , ppr_bag (ptext (sLit "wc_impl")) i ])
1536
1537 ppr_bag :: Outputable a => SDoc -> Bag a -> SDoc
1538 ppr_bag doc bag
1539 | isEmptyBag bag = empty
1540 | otherwise = hang (doc <+> equals)
1541 2 (foldrBag (($$) . ppr) empty bag)
1542
1543 {-
1544 ************************************************************************
1545 * *
1546 Implication constraints
1547 * *
1548 ************************************************************************
1549 -}
1550
1551 data Implication
1552 = Implic {
1553 ic_tclvl :: TcLevel, -- TcLevel: unification variables
1554 -- free in the environment
1555
1556 ic_skols :: [TcTyVar], -- Introduced skolems
1557 ic_info :: SkolemInfo, -- See Note [Skolems in an implication]
1558 -- See Note [Shadowing in a constraint]
1559
1560 ic_given :: [EvVar], -- Given evidence variables
1561 -- (order does not matter)
1562 -- See Invariant (GivenInv) in TcType
1563
1564 ic_no_eqs :: Bool, -- True <=> ic_givens have no equalities, for sure
1565 -- False <=> ic_givens might have equalities
1566
1567 ic_env :: TcLclEnv, -- Gives the source location and error context
1568 -- for the implication, and hence for all the
1569 -- given evidence variables
1570
1571 ic_wanted :: WantedConstraints, -- The wanted
1572
1573 ic_binds :: EvBindsVar, -- Points to the place to fill in the
1574 -- abstraction and bindings
1575
1576 ic_status :: ImplicStatus
1577 }
1578
1579 data ImplicStatus
1580 = IC_Solved -- All wanteds in the tree are solved, all the way down
1581 { ics_need :: VarSet -- Evidence variables needed by this implication
1582 , ics_dead :: [EvVar] } -- Subset of ic_given that are not needed
1583 -- See Note [Tracking redundant constraints] in TcSimplify
1584
1585 | IC_Insoluble -- At least one insoluble constraint in the tree
1586
1587 | IC_Unsolved -- Neither of the above; might go either way
1588
1589 instance Outputable Implication where
1590 ppr (Implic { ic_tclvl = tclvl, ic_skols = skols
1591 , ic_given = given, ic_no_eqs = no_eqs
1592 , ic_wanted = wanted, ic_status = status
1593 , ic_binds = binds, ic_info = info })
1594 = hang (ptext (sLit "Implic") <+> lbrace)
1595 2 (sep [ ptext (sLit "TcLevel =") <+> ppr tclvl
1596 , ptext (sLit "Skolems =") <+> pprTvBndrs skols
1597 , ptext (sLit "No-eqs =") <+> ppr no_eqs
1598 , ptext (sLit "Status =") <+> ppr status
1599 , hang (ptext (sLit "Given =")) 2 (pprEvVars given)
1600 , hang (ptext (sLit "Wanted =")) 2 (ppr wanted)
1601 , ptext (sLit "Binds =") <+> ppr binds
1602 , pprSkolInfo info ] <+> rbrace)
1603
1604 instance Outputable ImplicStatus where
1605 ppr IC_Insoluble = ptext (sLit "Insoluble")
1606 ppr IC_Unsolved = ptext (sLit "Unsolved")
1607 ppr (IC_Solved { ics_need = vs, ics_dead = dead })
1608 = ptext (sLit "Solved")
1609 <+> (braces $ vcat [ ptext (sLit "Dead givens =") <+> ppr dead
1610 , ptext (sLit "Needed =") <+> ppr vs ])
1611
1612 {-
1613 Note [Needed evidence variables]
1614 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1615 Th ic_need_evs field holds the free vars of ic_binds, and all the
1616 ic_binds in nested implications.
1617
1618 * Main purpose: if one of the ic_givens is not mentioned in here, it
1619 is redundant.
1620
1621 * solveImplication may drop an implication altogether if it has no
1622 remaining 'wanteds'. But we still track the free vars of its
1623 evidence binds, even though it has now disappeared.
1624
1625 Note [Shadowing in a constraint]
1626 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1627 We assume NO SHADOWING in a constraint. Specifically
1628 * The unification variables are all implicitly quantified at top
1629 level, and are all unique
1630 * The skolem varibles bound in ic_skols are all freah when the
1631 implication is created.
1632 So we can safely substitute. For example, if we have
1633 forall a. a~Int => ...(forall b. ...a...)...
1634 we can push the (a~Int) constraint inwards in the "givens" without
1635 worrying that 'b' might clash.
1636
1637 Note [Skolems in an implication]
1638 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1639 The skolems in an implication are not there to perform a skolem escape
1640 check. That happens because all the environment variables are in the
1641 untouchables, and therefore cannot be unified with anything at all,
1642 let alone the skolems.
1643
1644 Instead, ic_skols is used only when considering floating a constraint
1645 outside the implication in TcSimplify.floatEqualities or
1646 TcSimplify.approximateImplications
1647
1648 Note [Insoluble constraints]
1649 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1650 Some of the errors that we get during canonicalization are best
1651 reported when all constraints have been simplified as much as
1652 possible. For instance, assume that during simplification the
1653 following constraints arise:
1654
1655 [Wanted] F alpha ~ uf1
1656 [Wanted] beta ~ uf1 beta
1657
1658 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
1659 we will simply see a message:
1660 'Can't construct the infinite type beta ~ uf1 beta'
1661 and the user has no idea what the uf1 variable is.
1662
1663 Instead our plan is that we will NOT fail immediately, but:
1664 (1) Record the "frozen" error in the ic_insols field
1665 (2) Isolate the offending constraint from the rest of the inerts
1666 (3) Keep on simplifying/canonicalizing
1667
1668 At the end, we will hopefully have substituted uf1 := F alpha, and we
1669 will be able to report a more informative error:
1670 'Can't construct the infinite type beta ~ F alpha beta'
1671
1672 Insoluble constraints *do* include Derived constraints. For example,
1673 a functional dependency might give rise to [D] Int ~ Bool, and we must
1674 report that. If insolubles did not contain Deriveds, reportErrors would
1675 never see it.
1676
1677
1678 ************************************************************************
1679 * *
1680 Pretty printing
1681 * *
1682 ************************************************************************
1683 -}
1684
1685 pprEvVars :: [EvVar] -> SDoc -- Print with their types
1686 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
1687
1688 pprEvVarTheta :: [EvVar] -> SDoc
1689 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
1690
1691 pprEvVarWithType :: EvVar -> SDoc
1692 pprEvVarWithType v = ppr v <+> dcolon <+> pprType (evVarPred v)
1693
1694 {-
1695 ************************************************************************
1696 * *
1697 CtEvidence
1698 * *
1699 ************************************************************************
1700
1701 Note [Evidence field of CtEvidence]
1702 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1703 During constraint solving we never look at the type of ctev_evar;
1704 instead we look at the cte_pred field. The evtm/evar field
1705 may be un-zonked.
1706
1707 Note [Bind new Givens immediately]
1708 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1709 For Givens we make new EvVars and bind them immediately. Two main reasons:
1710 * Gain sharing. E.g. suppose we start with g :: C a b, where
1711 class D a => C a b
1712 class (E a, F a) => D a
1713 If we generate all g's superclasses as separate EvTerms we might
1714 get selD1 (selC1 g) :: E a
1715 selD2 (selC1 g) :: F a
1716 selC1 g :: D a
1717 which we could do more economically as:
1718 g1 :: D a = selC1 g
1719 g2 :: E a = selD1 g1
1720 g3 :: F a = selD2 g1
1721
1722 * For *coercion* evidence we *must* bind each given:
1723 class (a~b) => C a b where ....
1724 f :: C a b => ....
1725 Then in f's Givens we have g:(C a b) and the superclass sc(g,0):a~b.
1726 But that superclass selector can't (yet) appear in a coercion
1727 (see evTermCoercion), so the easy thing is to bind it to an Id.
1728
1729 So a Given has EvVar inside it rather that (as previously) an EvTerm.
1730 -}
1731
1732
1733 data CtEvidence
1734 = CtGiven { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1735 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
1736 , ctev_loc :: CtLoc }
1737 -- Truly given, not depending on subgoals
1738 -- NB: Spontaneous unifications belong here
1739
1740 | CtWanted { ctev_pred :: TcPredType -- See Note [Ct/evidence invariant]
1741 , ctev_evar :: EvVar -- See Note [Evidence field of CtEvidence]
1742 , ctev_loc :: CtLoc }
1743 -- Wanted goal
1744
1745 | CtDerived { ctev_pred :: TcPredType
1746 , ctev_loc :: CtLoc }
1747 -- A goal that we don't really have to solve and can't immediately
1748 -- rewrite anything other than a derived (there's no evidence!)
1749 -- but if we do manage to solve it may help in solving other goals.
1750
1751 ctEvPred :: CtEvidence -> TcPredType
1752 -- The predicate of a flavor
1753 ctEvPred = ctev_pred
1754
1755 ctEvLoc :: CtEvidence -> CtLoc
1756 ctEvLoc = ctev_loc
1757
1758 ctEvOrigin :: CtEvidence -> CtOrigin
1759 ctEvOrigin = ctLocOrigin . ctEvLoc
1760
1761 -- | Get the equality relation relevant for a 'CtEvidence'
1762 ctEvEqRel :: CtEvidence -> EqRel
1763 ctEvEqRel = predTypeEqRel . ctEvPred
1764
1765 -- | Get the role relevant for a 'CtEvidence'
1766 ctEvRole :: CtEvidence -> Role
1767 ctEvRole = eqRelRole . ctEvEqRel
1768
1769 ctEvTerm :: CtEvidence -> EvTerm
1770 ctEvTerm ev = EvId (ctEvId ev)
1771
1772 ctEvCoercion :: CtEvidence -> TcCoercion
1773 ctEvCoercion ev = mkTcCoVarCo (ctEvId ev)
1774
1775 ctEvId :: CtEvidence -> TcId
1776 ctEvId (CtWanted { ctev_evar = ev }) = ev
1777 ctEvId (CtGiven { ctev_evar = ev }) = ev
1778 ctEvId ctev = pprPanic "ctEvId:" (ppr ctev)
1779
1780 instance Outputable CtEvidence where
1781 ppr fl = case fl of
1782 CtGiven {} -> ptext (sLit "[G]") <+> ppr (ctev_evar fl) <+> ppr_pty
1783 CtWanted {} -> ptext (sLit "[W]") <+> ppr (ctev_evar fl) <+> ppr_pty
1784 CtDerived {} -> ptext (sLit "[D]") <+> text "_" <+> ppr_pty
1785 where ppr_pty = dcolon <+> ppr (ctEvPred fl)
1786
1787 isWanted :: CtEvidence -> Bool
1788 isWanted (CtWanted {}) = True
1789 isWanted _ = False
1790
1791 isGiven :: CtEvidence -> Bool
1792 isGiven (CtGiven {}) = True
1793 isGiven _ = False
1794
1795 isDerived :: CtEvidence -> Bool
1796 isDerived (CtDerived {}) = True
1797 isDerived _ = False
1798
1799 {-
1800 %************************************************************************
1801 %* *
1802 CtFlavour
1803 %* *
1804 %************************************************************************
1805
1806 Just an enum type that tracks whether a constraint is wanted, derived,
1807 or given, when we need to separate that info from the constraint itself.
1808
1809 -}
1810
1811 data CtFlavour = Given | Wanted | Derived
1812 deriving Eq
1813
1814 instance Outputable CtFlavour where
1815 ppr Given = text "[G]"
1816 ppr Wanted = text "[W]"
1817 ppr Derived = text "[D]"
1818
1819 ctEvFlavour :: CtEvidence -> CtFlavour
1820 ctEvFlavour (CtWanted {}) = Wanted
1821 ctEvFlavour (CtGiven {}) = Given
1822 ctEvFlavour (CtDerived {}) = Derived
1823
1824 -- | Whether or not one 'Ct' can rewrite another is determined by its
1825 -- flavour and its equality relation
1826 type CtFlavourRole = (CtFlavour, EqRel)
1827
1828 -- | Extract the flavour and role from a 'CtEvidence'
1829 ctEvFlavourRole :: CtEvidence -> CtFlavourRole
1830 ctEvFlavourRole ev = (ctEvFlavour ev, ctEvEqRel ev)
1831
1832 -- | Extract the flavour and role from a 'Ct'
1833 ctFlavourRole :: Ct -> CtFlavourRole
1834 ctFlavourRole = ctEvFlavourRole . cc_ev
1835
1836 {- Note [eqCanRewrite]
1837 ~~~~~~~~~~~~~~~~~~~
1838 (eqCanRewrite ct1 ct2) holds if the constraint ct1 (a CTyEqCan of form
1839 tv ~ ty) can be used to rewrite ct2. It must satisfy the properties of
1840 a can-rewrite relation, see Definition [Can-rewrite relation]
1841
1842 With the solver handling Coercible constraints like equality constraints,
1843 the rewrite conditions must take role into account, never allowing
1844 a representational equality to rewrite a nominal one.
1845
1846 Note [Wanteds do not rewrite Wanteds]
1847 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1848 We don't allow Wanteds to rewrite Wanteds, because that can give rise
1849 to very confusing type error messages. A good example is Trac #8450.
1850 Here's another
1851 f :: a -> Bool
1852 f x = ( [x,'c'], [x,True] ) `seq` True
1853 Here we get
1854 [W] a ~ Char
1855 [W] a ~ Bool
1856 but we do not want to complain about Bool ~ Char!
1857
1858 Note [Deriveds do rewrite Deriveds]
1859 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1860 However we DO allow Deriveds to rewrite Deriveds, because that's how
1861 improvement works; see Note [The improvement story] in TcInteract.
1862
1863 However, for now at least I'm only letting (Derived,NomEq) rewrite
1864 (Derived,NomEq) and not doing anything for ReprEq. If we have
1865 eqCanRewriteFR (Derived, NomEq) (Derived, _) = True
1866 then we lose the property of Note [Can-rewrite relation]
1867 R2. If f1 >= f, and f2 >= f,
1868 then either f1 >= f2 or f2 >= f1
1869 Consider f1 = (Given, ReprEq)
1870 f2 = (Derived, NomEq)
1871 f = (Derived, ReprEq)
1872
1873 I thought maybe we could never get Derived ReprEq constraints, but
1874 we can; straight from the Wanteds during improvment. And from a Derived
1875 ReprEq we could conceivably get a Derived NomEq improvment (by decomposing
1876 a type constructor with Nomninal role), and hence unify.
1877
1878 Note [canRewriteOrSame]
1879 ~~~~~~~~~~~~~~~~~~~~~~~
1880 canRewriteOrSame is similar but
1881 * returns True for Wanted/Wanted.
1882 * works for all kinds of constraints, not just CTyEqCans
1883 See the call sites for explanations.
1884 -}
1885
1886 eqCanRewrite :: CtEvidence -> CtEvidence -> Bool
1887 eqCanRewrite ev1 ev2 = ctEvFlavourRole ev1 `eqCanRewriteFR` ctEvFlavourRole ev2
1888
1889 eqCanRewriteFR :: CtFlavourRole -> CtFlavourRole -> Bool
1890 -- Very important function!
1891 -- See Note [eqCanRewrite]
1892 -- See Note [Wanteds do not rewrite Wanteds]
1893 -- See Note [Deriveds do rewrite Deriveds]
1894 eqCanRewriteFR (Given, NomEq) (_, _) = True
1895 eqCanRewriteFR (Given, ReprEq) (_, ReprEq) = True
1896 eqCanRewriteFR (Derived, NomEq) (Derived, NomEq) = True
1897 eqCanRewriteFR _ _ = False
1898
1899 canDischarge :: CtEvidence -> CtEvidence -> Bool
1900 -- See Note [canRewriteOrSame]
1901 canDischarge ev1 ev2 = ctEvFlavour ev1 `canDischargeF` ctEvFlavour ev2
1902
1903 canDischargeF :: CtFlavour -> CtFlavour -> Bool
1904 canDischargeF Given _ = True
1905 canDischargeF Wanted Wanted = True
1906 canDischargeF Wanted Derived = True
1907 canDischargeF Derived Derived = True
1908 canDischargeF _ _ = False
1909
1910
1911 {-
1912 ************************************************************************
1913 * *
1914 SubGoalDepth
1915 * *
1916 ************************************************************************
1917
1918 Note [SubGoalDepth]
1919 ~~~~~~~~~~~~~~~~~~~
1920 The 'SubGoalDepth' takes care of stopping the constraint solver from looping.
1921
1922 The counter starts at zero and increases. It includes dictionary constraints,
1923 equality simplification, and type family reduction. (Why combine these? Because
1924 it's actually quite easy to mistake one for another, in sufficiently involved
1925 scenarios, like ConstraintKinds.)
1926
1927 The flag -fcontext-stack=n (not very well named!) fixes the maximium
1928 level.
1929
1930 * The counter includes the depth of type class instance declarations. Example:
1931 [W] d{7} : Eq [Int]
1932 That is d's dictionary-constraint depth is 7. If we use the instance
1933 $dfEqList :: Eq a => Eq [a]
1934 to simplify it, we get
1935 d{7} = $dfEqList d'{8}
1936 where d'{8} : Eq Int, and d' has depth 8.
1937
1938 For civilised (decidable) instance declarations, each increase of
1939 depth removes a type constructor from the type, so the depth never
1940 gets big; i.e. is bounded by the structural depth of the type.
1941
1942 * The counter also increments when resolving
1943 equalities involving type functions. Example:
1944 Assume we have a wanted at depth 7:
1945 [W] d{7} : F () ~ a
1946 If thre is an type function equation "F () = Int", this would be rewritten to
1947 [W] d{8} : Int ~ a
1948 and remembered as having depth 8.
1949
1950 Again, without UndecidableInstances, this counter is bounded, but without it
1951 can resolve things ad infinitum. Hence there is a maximum level.
1952
1953 * Lastly, every time an equality is rewritten, the counter increases. Again,
1954 rewriting an equality constraint normally makes progress, but it's possible
1955 the "progress" is just the reduction of an infinitely-reducing type family.
1956 Hence we need to track the rewrites.
1957
1958 When compiling a program requires a greater depth, then GHC recommends turning
1959 off this check entirely by setting -freduction-depth=0. This is because the
1960 exact number that works is highly variable, and is likely to change even between
1961 minor releases. Because this check is solely to prevent infinite compilation
1962 times, it seems safe to disable it when a user has ascertained that their program
1963 doesn't loop at the type level.
1964
1965 -}
1966
1967 -- | See Note [SubGoalDepth]
1968 newtype SubGoalDepth = SubGoalDepth Int
1969 deriving (Eq, Ord, Outputable)
1970
1971 initialSubGoalDepth :: SubGoalDepth
1972 initialSubGoalDepth = SubGoalDepth 0
1973
1974 bumpSubGoalDepth :: SubGoalDepth -> SubGoalDepth
1975 bumpSubGoalDepth (SubGoalDepth n) = SubGoalDepth (n + 1)
1976
1977 subGoalDepthExceeded :: DynFlags -> SubGoalDepth -> Bool
1978 subGoalDepthExceeded dflags (SubGoalDepth d)
1979 = mkIntWithInf d > reductionDepth dflags
1980
1981 {-
1982 ************************************************************************
1983 * *
1984 CtLoc
1985 * *
1986 ************************************************************************
1987
1988 The 'CtLoc' gives information about where a constraint came from.
1989 This is important for decent error message reporting because
1990 dictionaries don't appear in the original source code.
1991 type will evolve...
1992 -}
1993
1994 data CtLoc = CtLoc { ctl_origin :: CtOrigin
1995 , ctl_env :: TcLclEnv
1996 , ctl_depth :: !SubGoalDepth }
1997 -- The TcLclEnv includes particularly
1998 -- source location: tcl_loc :: RealSrcSpan
1999 -- context: tcl_ctxt :: [ErrCtxt]
2000 -- binder stack: tcl_bndrs :: TcIdBinderStack
2001 -- level: tcl_tclvl :: TcLevel
2002
2003 mkGivenLoc :: TcLevel -> SkolemInfo -> TcLclEnv -> CtLoc
2004 mkGivenLoc tclvl skol_info env
2005 = CtLoc { ctl_origin = GivenOrigin skol_info
2006 , ctl_env = env { tcl_tclvl = tclvl }
2007 , ctl_depth = initialSubGoalDepth }
2008
2009 ctLocEnv :: CtLoc -> TcLclEnv
2010 ctLocEnv = ctl_env
2011
2012 ctLocLevel :: CtLoc -> TcLevel
2013 ctLocLevel loc = tcl_tclvl (ctLocEnv loc)
2014
2015 ctLocDepth :: CtLoc -> SubGoalDepth
2016 ctLocDepth = ctl_depth
2017
2018 ctLocOrigin :: CtLoc -> CtOrigin
2019 ctLocOrigin = ctl_origin
2020
2021 ctLocSpan :: CtLoc -> RealSrcSpan
2022 ctLocSpan (CtLoc { ctl_env = lcl}) = tcl_loc lcl
2023
2024 setCtLocSpan :: CtLoc -> RealSrcSpan -> CtLoc
2025 setCtLocSpan ctl@(CtLoc { ctl_env = lcl }) loc = setCtLocEnv ctl (lcl { tcl_loc = loc })
2026
2027 bumpCtLocDepth :: CtLoc -> CtLoc
2028 bumpCtLocDepth loc@(CtLoc { ctl_depth = d }) = loc { ctl_depth = bumpSubGoalDepth d }
2029
2030 setCtLocOrigin :: CtLoc -> CtOrigin -> CtLoc
2031 setCtLocOrigin ctl orig = ctl { ctl_origin = orig }
2032
2033 setCtLocEnv :: CtLoc -> TcLclEnv -> CtLoc
2034 setCtLocEnv ctl env = ctl { ctl_env = env }
2035
2036 pushErrCtxt :: CtOrigin -> ErrCtxt -> CtLoc -> CtLoc
2037 pushErrCtxt o err loc@(CtLoc { ctl_env = lcl })
2038 = loc { ctl_origin = o, ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
2039
2040 pushErrCtxtSameOrigin :: ErrCtxt -> CtLoc -> CtLoc
2041 -- Just add information w/o updating the origin!
2042 pushErrCtxtSameOrigin err loc@(CtLoc { ctl_env = lcl })
2043 = loc { ctl_env = lcl { tcl_ctxt = err : tcl_ctxt lcl } }
2044
2045 {-
2046 ************************************************************************
2047 * *
2048 SkolemInfo
2049 * *
2050 ************************************************************************
2051 -}
2052
2053 -- SkolemInfo gives the origin of *given* constraints
2054 -- a) type variables are skolemised
2055 -- b) an implication constraint is generated
2056 data SkolemInfo
2057 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
2058 Type -- a programmer-supplied type signature
2059 -- Location of the binding site is on the TyVar
2060
2061 -- The rest are for non-scoped skolems
2062 | ClsSkol Class -- Bound at a class decl
2063
2064 | InstSkol -- Bound at an instance decl
2065 | InstSC TypeSize -- A "given" constraint obtained by superclass selection
2066 -- from an InstSkol, giving the largest class from
2067 -- which we made a superclass selection in the chain
2068 -- See Note [Solving superclass constraints] in TcInstDcls
2069
2070 | DataSkol -- Bound at a data type declaration
2071 | FamInstSkol -- Bound at a family instance decl
2072 | PatSkol -- An existential type variable bound by a pattern for
2073 ConLike -- a data constructor with an existential type.
2074 (HsMatchContext Name)
2075 -- e.g. data T = forall a. Eq a => MkT a
2076 -- f (MkT x) = ...
2077 -- The pattern MkT x will allocate an existential type
2078 -- variable for 'a'.
2079
2080 | ArrowSkol -- An arrow form (see TcArrows)
2081
2082 | IPSkol [HsIPName] -- Binding site of an implicit parameter
2083
2084 | RuleSkol RuleName -- The LHS of a RULE
2085
2086 | InferSkol [(Name,TcType)]
2087 -- We have inferred a type for these (mutually-recursivive)
2088 -- polymorphic Ids, and are now checking that their RHS
2089 -- constraints are satisfied.
2090
2091 | BracketSkol -- Template Haskell bracket
2092
2093 | UnifyForAllSkol -- We are unifying two for-all types
2094 [TcTyVar] -- The instantiated skolem variables
2095 TcType -- The instantiated type *inside* the forall
2096
2097 | UnkSkol -- Unhelpful info (until I improve it)
2098
2099 instance Outputable SkolemInfo where
2100 ppr = pprSkolInfo
2101
2102 pprSkolInfo :: SkolemInfo -> SDoc
2103 -- Complete the sentence "is a rigid type variable bound by..."
2104 pprSkolInfo (SigSkol ctxt ty) = pprSigSkolInfo ctxt ty
2105 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter binding") <> plural ips <+> ptext (sLit "for")
2106 <+> pprWithCommas ppr ips
2107 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
2108 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
2109 pprSkolInfo (InstSC n) = ptext (sLit "the instance declaration") <> ifPprDebug (parens (ppr n))
2110 pprSkolInfo DataSkol = ptext (sLit "a data type declaration")
2111 pprSkolInfo FamInstSkol = ptext (sLit "a family instance declaration")
2112 pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
2113 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
2114 pprSkolInfo ArrowSkol = ptext (sLit "an arrow form")
2115 pprSkolInfo (PatSkol cl mc) = sep [ pprPatSkolInfo cl
2116 , ptext (sLit "in") <+> pprMatchContext mc ]
2117 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
2118 , vcat [ ppr name <+> dcolon <+> ppr ty
2119 | (name,ty) <- ids ]]
2120 pprSkolInfo (UnifyForAllSkol tvs ty) = ptext (sLit "the type") <+> ppr (mkForAllTys tvs ty)
2121
2122 -- UnkSkol
2123 -- For type variables the others are dealt with by pprSkolTvBinding.
2124 -- For Insts, these cases should not happen
2125 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
2126
2127 pprSigSkolInfo :: UserTypeCtxt -> Type -> SDoc
2128 pprSigSkolInfo ctxt ty
2129 = case ctxt of
2130 FunSigCtxt f _ -> pp_sig f
2131 _ -> hang (pprUserTypeCtxt ctxt <> colon)
2132 2 (ppr ty)
2133 where
2134 pp_sig f = sep [ ptext (sLit "the type signature for:")
2135 , pprPrefixOcc f <+> dcolon <+> ppr ty ]
2136
2137 pprPatSkolInfo :: ConLike -> SDoc
2138 pprPatSkolInfo (RealDataCon dc)
2139 = sep [ ptext (sLit "a pattern with constructor:")
2140 , nest 2 $ ppr dc <+> dcolon
2141 <+> pprType (dataConUserType dc) <> comma ]
2142 -- pprType prints forall's regardless of -fprint-explict-foralls
2143 -- which is what we want here, since we might be saying
2144 -- type variable 't' is bound by ...
2145
2146 pprPatSkolInfo (PatSynCon ps)
2147 = sep [ ptext (sLit "a pattern with pattern synonym:")
2148 , nest 2 $ ppr ps <+> dcolon
2149 <+> pprType (patSynType ps) <> comma ]
2150
2151 {-
2152 ************************************************************************
2153 * *
2154 CtOrigin
2155 * *
2156 ************************************************************************
2157 -}
2158
2159 data CtOrigin
2160 = GivenOrigin SkolemInfo
2161
2162 -- All the others are for *wanted* constraints
2163 | OccurrenceOf Name -- Occurrence of an overloaded identifier
2164 | AppOrigin -- An application of some kind
2165
2166 | SpecPragOrigin UserTypeCtxt -- Specialisation pragma for
2167 -- function or instance
2168
2169 | TypeEqOrigin { uo_actual :: TcType
2170 , uo_expected :: TcType }
2171 | KindEqOrigin
2172 TcType TcType -- A kind equality arising from unifying these two types
2173 CtOrigin -- originally arising from this
2174
2175 | IPOccOrigin HsIPName -- Occurrence of an implicit parameter
2176
2177 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
2178 | NegateOrigin -- Occurrence of syntactic negation
2179
2180 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
2181 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
2182 | SectionOrigin
2183 | TupleOrigin -- (..,..)
2184 | ExprSigOrigin -- e :: ty
2185 | PatSigOrigin -- p :: ty
2186 | PatOrigin -- Instantiating a polytyped pattern at a constructor
2187 | RecordUpdOrigin
2188 | ViewPatOrigin
2189
2190 | ScOrigin TypeSize -- Typechecking superclasses of an instance declaration
2191 -- whose head has the given size
2192 -- See Note [Solving superclass constraints] in TcInstDcls
2193
2194 | DerivOrigin -- Typechecking deriving
2195 | DerivOriginDC DataCon Int
2196 -- Checking constraints arising from this data con and field index
2197 | DerivOriginCoerce Id Type Type
2198 -- DerivOriginCoerce id ty1 ty2: Trying to coerce class method `id` from
2199 -- `ty1` to `ty2`.
2200 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
2201 | DefaultOrigin -- Typechecking a default decl
2202 | DoOrigin -- Arising from a do expression
2203 | MCompOrigin -- Arising from a monad comprehension
2204 | IfOrigin -- Arising from an if statement
2205 | ProcOrigin -- Arising from a proc expression
2206 | AnnOrigin -- An annotation
2207
2208 | FunDepOrigin1 -- A functional dependency from combining
2209 PredType CtLoc -- This constraint arising from ...
2210 PredType CtLoc -- and this constraint arising from ...
2211
2212 | FunDepOrigin2 -- A functional dependency from combining
2213 PredType CtOrigin -- This constraint arising from ...
2214 PredType SrcSpan -- and this instance
2215 -- We only need a CtOrigin on the first, because the location
2216 -- is pinned on the entire error message
2217
2218 | HoleOrigin
2219 | UnboundOccurrenceOf RdrName
2220 | ListOrigin -- An overloaded list
2221 | StaticOrigin -- A static form
2222
2223 ctoHerald :: SDoc
2224 ctoHerald = ptext (sLit "arising from")
2225
2226 pprCtLoc :: CtLoc -> SDoc
2227 -- "arising from ... at ..."
2228 -- Not an instance of Outputable because of the "arising from" prefix
2229 pprCtLoc (CtLoc { ctl_origin = o, ctl_env = lcl})
2230 = sep [ pprCtOrigin o
2231 , text "at" <+> ppr (tcl_loc lcl)]
2232
2233 pprCtOrigin :: CtOrigin -> SDoc
2234 -- "arising from ..."
2235 -- Not an instance of Outputable because of the "arising from" prefix
2236 pprCtOrigin (GivenOrigin sk) = ctoHerald <+> ppr sk
2237
2238 pprCtOrigin (SpecPragOrigin ctxt)
2239 = case ctxt of
2240 FunSigCtxt n _ -> ptext (sLit "a SPECIALISE pragma for") <+> quotes (ppr n)
2241 SpecInstCtxt -> ptext (sLit "a SPECIALISE INSTANCE pragma")
2242 _ -> ptext (sLit "a SPECIALISE pragma") -- Never happens I think
2243
2244 pprCtOrigin (FunDepOrigin1 pred1 loc1 pred2 loc2)
2245 = hang (ctoHerald <+> ptext (sLit "a functional dependency between constraints:"))
2246 2 (vcat [ hang (quotes (ppr pred1)) 2 (pprCtLoc loc1)
2247 , hang (quotes (ppr pred2)) 2 (pprCtLoc loc2) ])
2248
2249 pprCtOrigin (FunDepOrigin2 pred1 orig1 pred2 loc2)
2250 = hang (ctoHerald <+> ptext (sLit "a functional dependency between:"))
2251 2 (vcat [ hang (ptext (sLit "constraint") <+> quotes (ppr pred1))
2252 2 (pprCtOrigin orig1 )
2253 , hang (ptext (sLit "instance") <+> quotes (ppr pred2))
2254 2 (ptext (sLit "at") <+> ppr loc2) ])
2255
2256 pprCtOrigin (KindEqOrigin t1 t2 _)
2257 = hang (ctoHerald <+> ptext (sLit "a kind equality arising from"))
2258 2 (sep [ppr t1, char '~', ppr t2])
2259
2260 pprCtOrigin (UnboundOccurrenceOf name)
2261 = ctoHerald <+> ptext (sLit "an undeclared identifier") <+> quotes (ppr name)
2262
2263 pprCtOrigin (DerivOriginDC dc n)
2264 = hang (ctoHerald <+> ptext (sLit "the") <+> speakNth n
2265 <+> ptext (sLit "field of") <+> quotes (ppr dc))
2266 2 (parens (ptext (sLit "type") <+> quotes (ppr ty)))
2267 where
2268 ty = dataConOrigArgTys dc !! (n-1)
2269
2270 pprCtOrigin (DerivOriginCoerce meth ty1 ty2)
2271 = hang (ctoHerald <+> ptext (sLit "the coercion of the method") <+> quotes (ppr meth))
2272 2 (sep [ text "from type" <+> quotes (ppr ty1)
2273 , nest 2 $ text "to type" <+> quotes (ppr ty2) ])
2274
2275 pprCtOrigin simple_origin
2276 = ctoHerald <+> pprCtO simple_origin
2277
2278 ----------------
2279 pprCtO :: CtOrigin -> SDoc -- Ones that are short one-liners
2280 pprCtO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
2281 pprCtO AppOrigin = ptext (sLit "an application")
2282 pprCtO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
2283 pprCtO RecordUpdOrigin = ptext (sLit "a record update")
2284 pprCtO ExprSigOrigin = ptext (sLit "an expression type signature")
2285 pprCtO PatSigOrigin = ptext (sLit "a pattern type signature")
2286 pprCtO PatOrigin = ptext (sLit "a pattern")
2287 pprCtO ViewPatOrigin = ptext (sLit "a view pattern")
2288 pprCtO IfOrigin = ptext (sLit "an if statement")
2289 pprCtO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
2290 pprCtO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
2291 pprCtO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
2292 pprCtO SectionOrigin = ptext (sLit "an operator section")
2293 pprCtO TupleOrigin = ptext (sLit "a tuple")
2294 pprCtO NegateOrigin = ptext (sLit "a use of syntactic negation")
2295 pprCtO (ScOrigin n) = ptext (sLit "the superclasses of an instance declaration")
2296 <> ifPprDebug (parens (ppr n))
2297 pprCtO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
2298 pprCtO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
2299 pprCtO DefaultOrigin = ptext (sLit "a 'default' declaration")
2300 pprCtO DoOrigin = ptext (sLit "a do statement")
2301 pprCtO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
2302 pprCtO ProcOrigin = ptext (sLit "a proc expression")
2303 pprCtO (TypeEqOrigin t1 t2) = ptext (sLit "a type equality") <+> sep [ppr t1, char '~', ppr t2]
2304 pprCtO AnnOrigin = ptext (sLit "an annotation")
2305 pprCtO HoleOrigin = ptext (sLit "a use of") <+> quotes (ptext $ sLit "_")
2306 pprCtO ListOrigin = ptext (sLit "an overloaded list")
2307 pprCtO StaticOrigin = ptext (sLit "a static form")
2308 pprCtO _ = panic "pprCtOrigin"
2309
2310 {-
2311 Constraint Solver Plugins
2312 -------------------------
2313 -}
2314
2315 type TcPluginSolver = [Ct] -- given
2316 -> [Ct] -- derived
2317 -> [Ct] -- wanted
2318 -> TcPluginM TcPluginResult
2319
2320 newtype TcPluginM a = TcPluginM (Maybe EvBindsVar -> TcM a)
2321
2322 instance Functor TcPluginM where
2323 fmap = liftM
2324
2325 instance Applicative TcPluginM where
2326 pure = return
2327 (<*>) = ap
2328
2329 instance Monad TcPluginM where
2330 return x = TcPluginM (const $ return x)
2331 fail x = TcPluginM (const $ fail x)
2332 TcPluginM m >>= k =
2333 TcPluginM (\ ev -> do a <- m ev
2334 runTcPluginM (k a) ev)
2335
2336 runTcPluginM :: TcPluginM a -> Maybe EvBindsVar -> TcM a
2337 runTcPluginM (TcPluginM m) = m
2338
2339 -- | This function provides an escape for direct access to
2340 -- the 'TcM` monad. It should not be used lightly, and
2341 -- the provided 'TcPluginM' API should be favoured instead.
2342 unsafeTcPluginTcM :: TcM a -> TcPluginM a
2343 unsafeTcPluginTcM = TcPluginM . const
2344
2345 -- | Access the 'EvBindsVar' carried by the 'TcPluginM' during
2346 -- constraint solving. Returns 'Nothing' if invoked during
2347 -- 'tcPluginInit' or 'tcPluginStop'.
2348 getEvBindsTcPluginM_maybe :: TcPluginM (Maybe EvBindsVar)
2349 getEvBindsTcPluginM_maybe = TcPluginM return
2350
2351
2352 data TcPlugin = forall s. TcPlugin
2353 { tcPluginInit :: TcPluginM s
2354 -- ^ Initialize plugin, when entering type-checker.
2355
2356 , tcPluginSolve :: s -> TcPluginSolver
2357 -- ^ Solve some constraints.
2358 -- TODO: WRITE MORE DETAILS ON HOW THIS WORKS.
2359
2360 , tcPluginStop :: s -> TcPluginM ()
2361 -- ^ Clean up after the plugin, when exiting the type-checker.
2362 }
2363
2364 data TcPluginResult
2365 = TcPluginContradiction [Ct]
2366 -- ^ The plugin found a contradiction.
2367 -- The returned constraints are removed from the inert set,
2368 -- and recorded as insoluable.
2369
2370 | TcPluginOk [(EvTerm,Ct)] [Ct]
2371 -- ^ The first field is for constraints that were solved.
2372 -- These are removed from the inert set,
2373 -- and the evidence for them is recorded.
2374 -- The second field contains new work, that should be processed by
2375 -- the constraint solver.