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