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