2 % (c) The University of Glasgow 2006
3 % (c) The GRASP Project, Glasgow University, 1992-2002
7 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
10 -- The environment types
12 TcGblEnv(..), TcLclEnv(..),
13 IfGblEnv(..), IfLclEnv(..),
16 ErrCtxt, RecFieldEnv(..),
17 ImportAvails(..), emptyImportAvails, plusImportAvails,
18 WhereFrom(..), mkModDeps,
21 TcTypeEnv, TcTyThing(..), pprTcTyThingCategory,
24 ThStage(..), topStage, topAnnStage, topSpliceStage,
25 ThLevel, impLevel, outerLevel, thLevel,
28 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
31 Untouchables(..), inTouchableRange, isNoUntouchables,
33 WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
34 andWC, addFlats, addImplics, mkFlatWC,
36 EvVarX(..), mkEvVarX, evVarOf, evVarX, evVarOfPred,
37 WantedEvVar, wantedToFlavored,
41 CtLoc(..), ctLocSpan, ctLocOrigin, setCtLocOrigin,
42 CtOrigin(..), EqOrigin(..),
43 WantedLoc, GivenLoc, GivenKind(..), pushErrCtxt,
47 CtFlavor(..), pprFlavorArising, isWanted,
48 isGivenOrSolved, isGiven_maybe,
53 pprEvVarTheta, pprWantedEvVar, pprWantedsWithLocs,
54 pprEvVars, pprEvVarWithType,
55 pprArising, pprArisingAt,
58 TcId, TcIdSet, TcTyVarBind(..), TcTyVarBinds
62 #include "HsVersions.h"
67 import Id ( evVarPred )
68 import Class ( Class )
69 import DataCon ( DataCon, dataConUserType )
98 %************************************************************************
100 Standard monad definition for TcRn
101 All the combinators for the monad can be found in TcRnMonad
103 %************************************************************************
105 The monad itself has to be defined here, because it is mentioned by ErrCtxt
108 type TcRef a = IORef a
109 type TcId = Id -- Type may be a TcType DV: WHAT??????????
113 type TcRnIf a b c = IOEnv (Env a b) c
114 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
116 type IfG a = IfM () a -- Top level
117 type IfL a = IfM IfLclEnv a -- Nested
118 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
119 type RnM a = TcRn a -- Historical
120 type TcM a = TcRn a -- Historical
123 Representation of type bindings to uninstantiated meta variables used during
127 data TcTyVarBind = TcTyVarBind TcTyVar TcType
129 type TcTyVarBinds = Bag TcTyVarBind
131 instance Outputable TcTyVarBind where
132 ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
136 %************************************************************************
138 The main environment types
140 %************************************************************************
143 data Env gbl lcl -- Changes as we move into an expression
145 env_top :: HscEnv, -- Top-level stuff that never changes
146 -- Includes all info about imported things
148 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
149 -- Unique supply for local varibles
151 env_gbl :: gbl, -- Info about things defined at the top level
152 -- of the module being compiled
154 env_lcl :: lcl -- Nested stuff; changes as we go into
157 -- TcGblEnv describes the top-level of the module at the
158 -- point at which the typechecker is finished work.
159 -- It is this structure that is handed on to the desugarer
163 tcg_mod :: Module, -- ^ Module being compiled
164 tcg_src :: HscSource,
165 -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
167 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
168 tcg_default :: Maybe [Type],
169 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
171 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
172 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
174 tcg_type_env :: TypeEnv,
175 -- ^ Global type env for the module we are compiling now. All
176 -- TyCons and Classes (for this module) end up in here right away,
177 -- along with their derived constructors, selectors.
179 -- (Ids defined in this module start in the local envt, though they
180 -- move to the global envt during zonking)
182 tcg_type_env_var :: TcRef TypeEnv,
183 -- Used only to initialise the interface-file
184 -- typechecker in initIfaceTcRn, so that it can see stuff
185 -- bound in this module when dealing with hi-boot recursions
186 -- Updated at intervals (e.g. after dealing with types and classes)
188 tcg_inst_env :: InstEnv,
189 -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
191 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
193 -- Now a bunch of things about this module that are simply
194 -- accumulated, but never consulted until the end.
195 -- Nevertheless, it's convenient to accumulate them along
196 -- with the rest of the info from this module.
197 tcg_exports :: [AvailInfo], -- ^ What is exported
198 tcg_imports :: ImportAvails,
199 -- ^ Information about what was imported from where, including
200 -- things bound in this module.
203 -- ^ What is defined in this module and what is used.
204 -- The latter is used to generate
206 -- (a) version tracking; no need to recompile if these things have
207 -- not changed version stamp
209 -- (b) unused-import info
211 tcg_keep :: TcRef NameSet,
212 -- ^ Locally-defined top-level names to keep alive.
214 -- "Keep alive" means give them an Exported flag, so that the
215 -- simplifier does not discard them as dead code, and so that they
216 -- are exposed in the interface file (but not to export to the
219 -- Some things, like dict-fun Ids and default-method Ids are "born"
220 -- with the Exported flag on, for exactly the above reason, but some
221 -- we only discover as we go. Specifically:
223 -- * The to/from functions for generic data types
225 -- * Top-level variables appearing free in the RHS of an orphan
228 -- * Top-level variables appearing free in a TH bracket
230 tcg_th_used :: TcRef Bool,
231 -- ^ @True@ <=> Template Haskell syntax used.
233 -- We need this so that we can generate a dependency on the
234 -- Template Haskell package, becuase the desugarer is going
235 -- to emit loads of references to TH symbols. The reference
236 -- is implicit rather than explicit, so we have to zap a
239 tcg_dfun_n :: TcRef OccSet,
240 -- ^ Allows us to choose unique DFun names.
242 -- The next fields accumulate the payload of the module
243 -- The binds, rules and foreign-decl fiels are collected
244 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
246 tcg_rn_exports :: Maybe [Located (IE Name)],
247 tcg_rn_imports :: [LImportDecl Name],
248 -- Keep the renamed imports regardless. They are not
249 -- voluminous and are needed if you want to report unused imports
251 tcg_used_rdrnames :: TcRef (Set RdrName),
252 -- The set of used *imported* (not locally-defined) RdrNames
253 -- Used only to report unused import declarations
255 tcg_rn_decls :: Maybe (HsGroup Name),
256 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
259 tcg_ev_binds :: Bag EvBind, -- Top-level evidence bindings
260 tcg_binds :: LHsBinds Id, -- Value bindings in this module
261 tcg_sigs :: NameSet, -- ...Top-level names that *lack* a signature
262 tcg_imp_specs :: [LTcSpecPrag], -- ...SPECIALISE prags for imported Ids
263 tcg_warns :: Warnings, -- ...Warnings and deprecations
264 tcg_anns :: [Annotation], -- ...Annotations
265 tcg_insts :: [Instance], -- ...Instances
266 tcg_fam_insts :: [FamInst], -- ...Family instances
267 tcg_rules :: [LRuleDecl Id], -- ...Rules
268 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
269 tcg_vects :: [LVectDecl Id], -- ...Vectorisation declarations
271 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
272 tcg_hpc :: AnyHpcUsage, -- ^ @True@ if any part of the
273 -- prog uses hpc instrumentation.
275 tcg_main :: Maybe Name -- ^ The Name of the main
276 -- function, if this module is
281 = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
282 -- to the fields for that constructor
283 NameSet -- Set of all fields declared *in this module*;
284 -- used to suppress name-shadowing complaints
285 -- when using record wild cards
286 -- E.g. let fld = e in C {..}
287 -- This is used when dealing with ".." notation in record
288 -- construction and pattern matching.
289 -- The FieldEnv deals *only* with constructors defined in *this*
290 -- module. For imported modules, we get the same info from the
294 %************************************************************************
296 The interface environments
297 Used when dealing with IfaceDecls
299 %************************************************************************
304 -- The type environment for the module being compiled,
305 -- in case the interface refers back to it via a reference that
306 -- was originally a hi-boot file.
307 -- We need the module name so we can test when it's appropriate
308 -- to look in this env.
309 if_rec_types :: Maybe (Module, IfG TypeEnv)
310 -- Allows a read effect, so it can be in a mutable
311 -- variable; c.f. handling the external package type env
312 -- Nothing => interactive stuff, no loops possible
317 -- The module for the current IfaceDecl
318 -- So if we see f = \x -> x
319 -- it means M.f = \x -> x, where M is the if_mod
322 -- The field is used only for error reporting
323 -- if (say) there's a Lint error in it
325 -- Where the interface came from:
326 -- .hi file, or GHCi state, or ext core
327 -- plus which bit is currently being examined
329 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
331 if_id_env :: UniqFM Id -- Nested id binding
336 %************************************************************************
338 The local typechecker environment
340 %************************************************************************
342 The Global-Env/Local-Env story
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
344 During type checking, we keep in the tcg_type_env
345 * All types and classes
346 * All Ids derived from types and classes (constructors, selectors)
348 At the end of type checking, we zonk the local bindings,
349 and as we do so we add to the tcg_type_env
350 * Locally defined top-level Ids
352 Why? Because they are now Ids not TcIds. This final GlobalEnv is
353 a) fed back (via the knot) to typechecking the
354 unfoldings of interface signatures
355 b) used in the ModDetails of this module
358 data TcLclEnv -- Changes as we move inside an expression
359 -- Discarded after typecheck/rename; not passed on to desugarer
361 tcl_loc :: SrcSpan, -- Source span
362 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
363 tcl_errs :: TcRef Messages, -- Place to accumulate errors
365 tcl_th_ctxt :: ThStage, -- Template Haskell context
366 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
368 tcl_rdr :: LocalRdrEnv, -- Local name envt
369 -- Maintained during renaming, of course, but also during
370 -- type checking, solely so that when renaming a Template-Haskell
371 -- splice we have the right environment for the renamer.
373 -- Does *not* include global name envt; may shadow it
374 -- Includes both ordinary variables and type variables;
375 -- they are kept distinct because tyvar have a different
376 -- occurrence contructor (Name.TvOcc)
377 -- We still need the unsullied global name env so that
378 -- we can look up record field names
380 tcl_env :: TcTypeEnv, -- The local type environment: Ids and
381 -- TyVars defined in this module
383 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
384 -- Namely, the in-scope TyVars bound in tcl_env,
385 -- plus the tyvars mentioned in the types of Ids bound
387 -- Why mutable? see notes with tcGetGlobalTyVars
389 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
392 tcl_meta :: TcRef Unique, -- The next free unique for TcMetaTyVars
393 -- Guaranteed to be allocated linearly
394 tcl_untch :: Unique -- Any TcMetaTyVar with
395 -- unique >= tcl_untch is touchable
396 -- unique < tcl_untch is untouchable
399 type TcTypeEnv = NameEnv TcTyThing
402 {- Note [Given Insts]
404 Because of GADTs, we have to pass inwards the Insts provided by type signatures
405 and existential contexts. Consider
406 data T a where { T1 :: b -> b -> T [b] }
407 f :: Eq a => T a -> Bool
408 f (T1 x y) = [x]==[y]
410 The constructor T1 binds an existential variable 'b', and we need Eq [b].
411 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
416 ---------------------------
417 -- Template Haskell stages and levels
418 ---------------------------
420 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
421 = Splice -- Top-level splicing
422 -- This code will be run *at compile time*;
423 -- the result replaces the splice
426 | Comp -- Ordinary Haskell code
429 | Brack -- Inside brackets
430 ThStage -- Binding level = level(stage) + 1
431 (TcRef [PendingSplice]) -- Accumulate pending splices here
432 (TcRef WantedConstraints) -- and type constraints here
434 topStage, topAnnStage, topSpliceStage :: ThStage
437 topSpliceStage = Splice
439 instance Outputable ThStage where
440 ppr Splice = text "Splice"
441 ppr Comp = text "Comp"
442 ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
445 -- See Note [Template Haskell levels] in TcSplice
446 -- Incremented when going inside a bracket,
447 -- decremented when going inside a splice
448 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
449 -- original "Template meta-programming for Haskell" paper
451 impLevel, outerLevel :: ThLevel
452 impLevel = 0 -- Imported things; they can be used inside a top level splice
453 outerLevel = 1 -- Things defined outside brackets
454 -- NB: Things at level 0 are not *necessarily* imported.
455 -- eg $( \b -> ... ) here b is bound at level 0
459 -- g1 = $(map ...) is OK
460 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
462 thLevel :: ThStage -> ThLevel
465 thLevel (Brack s _ _) = thLevel s + 1
467 ---------------------------
468 -- Arrow-notation context
469 ---------------------------
472 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
473 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
478 Here, x is not in scope in e1, but it is in scope in e2. This can get
482 proc y -> (proc z -> e1) -< e2
484 Here, x and z are in scope in e1, but y is not. We implement this by
485 recording the environment when passing a proc (using newArrowScope),
486 and returning to that (using escapeArrowScope) on the left of -< and the
492 | ArrowCtxt (Env TcGblEnv TcLclEnv)
494 -- Record the current environment (outside a proc)
495 newArrowScope :: TcM a -> TcM a
498 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
500 -- Return to the stored environment (from the enclosing proc)
501 escapeArrowScope :: TcM a -> TcM a
503 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
505 ArrowCtxt env' -> env'
507 ---------------------------
509 ---------------------------
512 = AGlobal TyThing -- Used only in the return type of a lookup
514 | ATcId { -- Ids defined in this module; may not be fully zonked
516 tct_level :: ThLevel }
518 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
519 -- is currently refined. We only need the Name
520 -- for error-message purposes; it is the corresponding
521 -- Name in the domain of the envt
523 | AThing TcKind -- Used temporarily, during kind checking, for the
524 -- tycons and clases in this recursive group
526 instance Outputable TcTyThing where -- Debugging only
527 ppr (AGlobal g) = pprTyThing g
528 ppr elt@(ATcId {}) = text "Identifier" <>
529 brackets (ppr (tct_id elt) <> dcolon
530 <> ppr (varType (tct_id elt)) <> comma
531 <+> ppr (tct_level elt))
532 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
533 ppr (AThing k) = text "AThing" <+> ppr k
535 pprTcTyThingCategory :: TcTyThing -> SDoc
536 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
537 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
538 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
539 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
543 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
544 -- Monadic so that we have a chance
545 -- to deal with bound type variables just before error
546 -- message construction
548 -- Bool: True <=> this is a landmark context; do not
549 -- discard it when trimming for display
553 %************************************************************************
555 Operations over ImportAvails
557 %************************************************************************
560 -- | 'ImportAvails' summarises what was imported from where, irrespective of
561 -- whether the imported things are actually used or not. It is used:
563 -- * when processing the export list,
565 -- * when constructing usage info for the interface file,
567 -- * to identify the list of directly imported modules for initialisation
568 -- purposes and for optimised overlap checking of family instances,
570 -- * when figuring out what things are really unused
574 imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
575 -- ^ Domain is all directly-imported modules
576 -- The 'ModuleName' is what the module was imported as, e.g. in
584 -- - @True@ => import was @import Foo ()@
586 -- - @False@ => import was some other form
590 -- (a) to help construct the usage information in the interface
591 -- file; if we import somethign we need to recompile if the
592 -- export version changes
594 -- (b) to specify what child modules to initialise
596 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
597 -- because we might be importing modules of the same name from
598 -- different packages. (currently not the case, but might be in the
601 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
602 -- ^ Home-package modules needed by the module being compiled
604 -- It doesn't matter whether any of these dependencies
605 -- are actually /used/ when compiling the module; they
606 -- are listed if they are below it at all. For
607 -- example, suppose M imports A which imports X. Then
608 -- compiling M might not need to consult X.hi, but X
609 -- is still listed in M's dependencies.
611 imp_dep_pkgs :: [PackageId],
612 -- ^ Packages needed by the module being compiled, whether directly,
613 -- or via other modules in this package, or via modules imported
614 -- from other packages.
616 imp_orphs :: [Module],
617 -- ^ Orphan modules below us in the import tree (and maybe including
618 -- us for imported modules)
620 imp_finsts :: [Module]
621 -- ^ Family instance modules below us in the import tree (and maybe
622 -- including us for imported modules)
625 mkModDeps :: [(ModuleName, IsBootInterface)]
626 -> ModuleNameEnv (ModuleName, IsBootInterface)
627 mkModDeps deps = foldl add emptyUFM deps
629 add env elt@(m,_) = addToUFM env m elt
631 emptyImportAvails :: ImportAvails
632 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
633 imp_dep_mods = emptyUFM,
638 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
640 (ImportAvails { imp_mods = mods1,
641 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
642 imp_orphs = orphs1, imp_finsts = finsts1 })
643 (ImportAvails { imp_mods = mods2,
644 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
645 imp_orphs = orphs2, imp_finsts = finsts2 })
646 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
647 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
648 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
649 imp_orphs = orphs1 `unionLists` orphs2,
650 imp_finsts = finsts1 `unionLists` finsts2 }
652 plus_mod_dep (m1, boot1) (m2, boot2)
653 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
654 -- Check mod-names match
655 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
658 %************************************************************************
660 \subsection{Where from}
662 %************************************************************************
664 The @WhereFrom@ type controls where the renamer looks for an interface file
668 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
669 | ImportBySystem -- Non user import.
671 instance Outputable WhereFrom where
672 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
674 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
678 %************************************************************************
681 These are forced to be in TcRnTypes because
682 TcLclEnv mentions WantedConstraints
683 WantedConstraint mentions CtLoc
684 CtLoc mentions ErrCtxt
687 v%************************************************************************
690 data WantedConstraints
691 = WC { wc_flat :: Bag WantedEvVar -- Unsolved constraints, all wanted
692 , wc_impl :: Bag Implication
693 , wc_insol :: Bag FlavoredEvVar -- Insoluble constraints, can be
694 -- wanted, given, or derived
695 -- See Note [Insoluble constraints]
698 emptyWC :: WantedConstraints
699 emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
701 mkFlatWC :: Bag WantedEvVar -> WantedConstraints
702 mkFlatWC wevs = WC { wc_flat = wevs, wc_impl = emptyBag, wc_insol = emptyBag }
704 isEmptyWC :: WantedConstraints -> Bool
705 isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
706 = isEmptyBag f && isEmptyBag i && isEmptyBag n
708 insolubleWC :: WantedConstraints -> Bool
709 -- True if there are any insoluble constraints in the wanted bag
710 insolubleWC wc = not (isEmptyBag (wc_insol wc))
711 || anyBag ic_insol (wc_impl wc)
713 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
714 andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
715 (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
716 = WC { wc_flat = f1 `unionBags` f2
717 , wc_impl = i1 `unionBags` i2
718 , wc_insol = n1 `unionBags` n2 }
720 addFlats :: WantedConstraints -> Bag WantedEvVar -> WantedConstraints
721 addFlats wc wevs = wc { wc_flat = wc_flat wc `unionBags` wevs }
723 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
724 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
726 instance Outputable WantedConstraints where
727 ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
728 = ptext (sLit "WC") <+> braces (vcat
729 [ if isEmptyBag f then empty else
730 ptext (sLit "wc_flat =") <+> pprBag pprWantedEvVar f
731 , if isEmptyBag i then empty else
732 ptext (sLit "wc_impl =") <+> pprBag ppr i
733 , if isEmptyBag n then empty else
734 ptext (sLit "wc_insol =") <+> pprBag ppr n ])
736 pprBag :: (a -> SDoc) -> Bag a -> SDoc
737 pprBag pp b = foldrBag (($$) . pp) empty b
742 data Untouchables = NoUntouchables
746 -- A TcMetaTyvar is *touchable* iff its unique u satisfies
750 instance Outputable Untouchables where
751 ppr NoUntouchables = ptext (sLit "No untouchables")
752 ppr (TouchableRange low high) = ptext (sLit "Touchable range:") <+>
753 ppr low <+> char '-' <+> ppr high
755 isNoUntouchables :: Untouchables -> Bool
756 isNoUntouchables NoUntouchables = True
757 isNoUntouchables (TouchableRange {}) = False
759 inTouchableRange :: Untouchables -> TcTyVar -> Bool
760 inTouchableRange NoUntouchables _ = True
761 inTouchableRange (TouchableRange low high) tv
762 = uniq >= low && uniq < high
766 -- EvVar defined in module Var.lhs:
767 -- Evidence variables include all *quantifiable* constraints
769 -- implicit parameters
770 -- coercion variables
773 %************************************************************************
775 Implication constraints
777 %************************************************************************
782 ic_untch :: Untouchables, -- Untouchables: unification variables
783 -- free in the environment
784 ic_env :: TcTypeEnv, -- The type environment
785 -- Used only when generating error messages
786 -- Generally, ic_untch is a superset of tvsof(ic_env)
787 -- However, we don't zonk ic_env when zonking the Implication
788 -- Instead we do that when generating a skolem-escape error message
790 ic_skols :: TcTyVarSet, -- Introduced skolems
791 -- See Note [Skolems in an implication]
793 ic_given :: [EvVar], -- Given evidence variables
794 -- (order does not matter)
795 ic_loc :: GivenLoc, -- Binding location of the implication,
796 -- which is also the location of all the
797 -- given evidence variables
799 ic_wanted :: WantedConstraints, -- The wanted
800 ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
802 ic_binds :: EvBindsVar -- Points to the place to fill in the
803 -- abstraction and bindings
806 instance Outputable Implication where
807 ppr (Implic { ic_untch = untch, ic_skols = skols, ic_given = given
809 , ic_binds = binds, ic_loc = loc })
810 = ptext (sLit "Implic") <+> braces
811 (sep [ ptext (sLit "Untouchables = ") <+> ppr untch
812 , ptext (sLit "Skolems = ") <+> ppr skols
813 , ptext (sLit "Given = ") <+> pprEvVars given
814 , ptext (sLit "Wanted = ") <+> ppr wanted
815 , ptext (sLit "Binds = ") <+> ppr binds
816 , pprSkolInfo (ctLocOrigin loc)
817 , ppr (ctLocSpan loc) ])
820 Note [Skolems in an implication]
821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 The skolems in an implication are not there to perform a skolem escape
823 check. That happens because all the environment variables are in the
824 untouchables, and therefore cannot be unified with anything at all,
825 let alone the skolems.
827 Instead, ic_skols is used only when considering floating a constraint
828 outside the implication in TcSimplify.floatEqualities or
829 TcSimplify.approximateImplications
831 Note [Insoluble constraints]
832 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
833 Some of the errors that we get during canonicalization are best
834 reported when all constraints have been simplified as much as
835 possible. For instance, assume that during simplification the
836 following constraints arise:
838 [Wanted] F alpha ~ uf1
839 [Wanted] beta ~ uf1 beta
841 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
842 we will simply see a message:
843 'Can't construct the infinite type beta ~ uf1 beta'
844 and the user has no idea what the uf1 variable is.
846 Instead our plan is that we will NOT fail immediately, but:
847 (1) Record the "frozen" error in the ic_insols field
848 (2) Isolate the offending constraint from the rest of the inerts
849 (3) Keep on simplifying/canonicalizing
851 At the end, we will hopefully have substituted uf1 := F alpha, and we
852 will be able to report a more informative error:
853 'Can't construct the infinite type beta ~ F alpha beta'
855 %************************************************************************
857 EvVarX, WantedEvVar, FlavoredEvVar
859 %************************************************************************
862 data EvVarX a = EvVarX EvVar a
863 -- An evidence variable with accompanying info
865 type WantedEvVar = EvVarX WantedLoc -- The location where it arose
866 type FlavoredEvVar = EvVarX CtFlavor
868 instance Outputable (EvVarX a) where
869 ppr (EvVarX ev _) = pprEvVarWithType ev
870 -- If you want to see the associated info,
871 -- use a more specific printing function
873 mkEvVarX :: EvVar -> a -> EvVarX a
876 evVarOf :: EvVarX a -> EvVar
877 evVarOf (EvVarX ev _) = ev
879 evVarX :: EvVarX a -> a
880 evVarX (EvVarX _ a) = a
882 evVarOfPred :: EvVarX a -> PredType
883 evVarOfPred wev = evVarPred (evVarOf wev)
885 wantedToFlavored :: WantedEvVar -> FlavoredEvVar
886 wantedToFlavored (EvVarX v wl) = EvVarX v (Wanted wl)
888 keepWanted :: Bag FlavoredEvVar -> Bag WantedEvVar
890 = foldrBag keep_wanted emptyBag flevs
891 -- Important: use fold*r*Bag to preserve the order of the evidence variables.
893 keep_wanted :: FlavoredEvVar -> Bag WantedEvVar -> Bag WantedEvVar
894 keep_wanted (EvVarX ev (Wanted wloc)) r = consBag (EvVarX ev wloc) r
900 pprEvVars :: [EvVar] -> SDoc -- Print with their types
901 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
903 pprEvVarTheta :: [EvVar] -> SDoc
904 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
906 pprEvVarWithType :: EvVar -> SDoc
907 pprEvVarWithType v = ppr v <+> dcolon <+> pprPredTy (evVarPred v)
909 pprWantedsWithLocs :: WantedConstraints -> SDoc
910 pprWantedsWithLocs wcs
911 = vcat [ pprBag pprWantedEvVarWithLoc (wc_flat wcs)
912 , pprBag ppr (wc_impl wcs)
913 , pprBag ppr (wc_insol wcs) ]
915 pprWantedEvVarWithLoc, pprWantedEvVar :: WantedEvVar -> SDoc
916 pprWantedEvVarWithLoc (EvVarX v loc) = hang (pprEvVarWithType v)
918 pprWantedEvVar (EvVarX v _) = pprEvVarWithType v
921 %************************************************************************
925 %************************************************************************
929 = Given GivenLoc GivenKind -- We have evidence for this constraint in TcEvBinds
930 | Derived WantedLoc -- Derived's are just hints for unifications
931 | Wanted WantedLoc -- We have no evidence bindings for this constraint.
934 = GivenOrig -- Originates in some given, such as signature or pattern match
935 | GivenSolved -- Is given as result of being solved, maybe provisionally on
936 -- some other wanted constraints.
938 instance Outputable CtFlavor where
939 ppr (Given _ GivenOrig) = ptext (sLit "[G]")
940 ppr (Given _ GivenSolved) = ptext (sLit "[S]") -- Print [S] for Given/Solved's
941 ppr (Wanted {}) = ptext (sLit "[W]")
942 ppr (Derived {}) = ptext (sLit "[D]")
944 pprFlavorArising :: CtFlavor -> SDoc
945 pprFlavorArising (Derived wl) = pprArisingAt wl
946 pprFlavorArising (Wanted wl) = pprArisingAt wl
947 pprFlavorArising (Given gl _) = pprArisingAt gl
949 isWanted :: CtFlavor -> Bool
950 isWanted (Wanted {}) = True
953 isGivenOrSolved :: CtFlavor -> Bool
954 isGivenOrSolved (Given {}) = True
955 isGivenOrSolved _ = False
957 isGiven_maybe :: CtFlavor -> Maybe GivenKind
958 isGiven_maybe (Given _ gk) = Just gk
959 isGiven_maybe _ = Nothing
961 isDerived :: CtFlavor -> Bool
962 isDerived (Derived {}) = True
966 %************************************************************************
970 %************************************************************************
972 The 'CtLoc' gives information about where a constraint came from.
973 This is important for decent error message reporting because
974 dictionaries don't appear in the original source code.
978 data CtLoc orig = CtLoc orig SrcSpan [ErrCtxt]
980 type WantedLoc = CtLoc CtOrigin -- Instantiation for wanted constraints
981 type GivenLoc = CtLoc SkolemInfo -- Instantiation for given constraints
983 ctLocSpan :: CtLoc o -> SrcSpan
984 ctLocSpan (CtLoc _ s _) = s
986 ctLocOrigin :: CtLoc o -> o
987 ctLocOrigin (CtLoc o _ _) = o
989 setCtLocOrigin :: CtLoc o -> o' -> CtLoc o'
990 setCtLocOrigin (CtLoc _ s c) o = CtLoc o s c
992 pushErrCtxt :: orig -> ErrCtxt -> CtLoc orig -> CtLoc orig
993 pushErrCtxt o err (CtLoc _ s errs) = CtLoc o s (err:errs)
995 pprArising :: CtOrigin -> SDoc
996 -- Used for the main, top-level error message
997 -- We've done special processing for TypeEq and FunDep origins
998 pprArising (TypeEqOrigin {}) = empty
999 pprArising FunDepOrigin = empty
1000 pprArising orig = text "arising from" <+> ppr orig
1002 pprArisingAt :: Outputable o => CtLoc o -> SDoc
1003 pprArisingAt (CtLoc o s _) = sep [ text "arising from" <+> ppr o
1004 , text "at" <+> ppr s]
1007 %************************************************************************
1011 %************************************************************************
1014 -- SkolemInfo gives the origin of *given* constraints
1015 -- a) type variables are skolemised
1016 -- b) an implication constraint is generated
1018 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
1019 Type -- a programmer-supplied type signature
1020 -- Location of the binding site is on the TyVar
1022 -- The rest are for non-scoped skolems
1023 | ClsSkol Class -- Bound at a class decl
1024 | InstSkol -- Bound at an instance decl
1025 | DataSkol -- Bound at a data type declaration
1026 | FamInstSkol -- Bound at a family instance decl
1027 | PatSkol -- An existential type variable bound by a pattern for
1028 DataCon -- a data constructor with an existential type.
1029 (HsMatchContext Name)
1030 -- e.g. data T = forall a. Eq a => MkT a
1032 -- The pattern MkT x will allocate an existential type
1033 -- variable for 'a'.
1035 | ArrowSkol -- An arrow form (see TcArrows)
1037 | IPSkol [IPName Name] -- Binding site of an implicit parameter
1039 | RuleSkol RuleName -- The LHS of a RULE
1041 | InferSkol [(Name,TcType)]
1042 -- We have inferred a type for these (mutually-recursivive)
1043 -- polymorphic Ids, and are now checking that their RHS
1044 -- constraints are satisfied.
1046 | BracketSkol -- Template Haskell bracket
1048 | UnkSkol -- Unhelpful info (until I improve it)
1050 instance Outputable SkolemInfo where
1053 pprSkolInfo :: SkolemInfo -> SDoc
1054 -- Complete the sentence "is a rigid type variable bound by..."
1055 pprSkolInfo (SigSkol (FunSigCtxt f) ty)
1056 = hang (ptext (sLit "the type signature for"))
1057 2 (ppr f <+> dcolon <+> ppr ty)
1058 pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
1060 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter bindings for")
1061 <+> pprWithCommas ppr ips
1062 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
1063 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
1064 pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
1065 pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
1066 pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
1067 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
1068 pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
1069 pprSkolInfo (PatSkol dc mc) = sep [ ptext (sLit "a pattern with constructor")
1070 , nest 2 $ ppr dc <+> dcolon
1071 <+> ppr (dataConUserType dc) <> comma
1072 , ptext (sLit "in") <+> pprMatchContext mc ]
1073 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
1074 , vcat [ ppr name <+> dcolon <+> ppr ty
1075 | (name,ty) <- ids ]]
1078 -- For type variables the others are dealt with by pprSkolTvBinding.
1079 -- For Insts, these cases should not happen
1080 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
1084 %************************************************************************
1088 %************************************************************************
1091 -- CtOrigin gives the origin of *wanted* constraints
1093 = OccurrenceOf Name -- Occurrence of an overloaded identifier
1094 | AppOrigin -- An application of some kind
1096 | SpecPragOrigin Name -- Specialisation pragma for identifier
1098 | TypeEqOrigin EqOrigin
1100 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
1102 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
1103 | NegateOrigin -- Occurrence of syntactic negation
1105 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
1106 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
1108 | TupleOrigin -- (..,..)
1109 | ExprSigOrigin -- e :: ty
1110 | PatSigOrigin -- p :: ty
1111 | PatOrigin -- Instantiating a polytyped pattern at a constructor
1115 | ScOrigin -- Typechecking superclasses of an instance declaration
1116 | DerivOrigin -- Typechecking deriving
1117 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
1118 | DefaultOrigin -- Typechecking a default decl
1119 | DoOrigin -- Arising from a do expression
1120 | MCompOrigin -- Arising from a monad comprehension
1121 | IfOrigin -- Arising from an if statement
1122 | ProcOrigin -- Arising from a proc expression
1123 | AnnOrigin -- An annotation
1128 { uo_actual :: TcType
1129 , uo_expected :: TcType }
1131 instance Outputable CtOrigin where
1132 ppr orig = pprO orig
1134 pprO :: CtOrigin -> SDoc
1135 pprO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
1136 pprO AppOrigin = ptext (sLit "an application")
1137 pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
1138 pprO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
1139 pprO RecordUpdOrigin = ptext (sLit "a record update")
1140 pprO ExprSigOrigin = ptext (sLit "an expression type signature")
1141 pprO PatSigOrigin = ptext (sLit "a pattern type signature")
1142 pprO PatOrigin = ptext (sLit "a pattern")
1143 pprO ViewPatOrigin = ptext (sLit "a view pattern")
1144 pprO IfOrigin = ptext (sLit "an if statement")
1145 pprO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
1146 pprO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
1147 pprO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
1148 pprO SectionOrigin = ptext (sLit "an operator section")
1149 pprO TupleOrigin = ptext (sLit "a tuple")
1150 pprO NegateOrigin = ptext (sLit "a use of syntactic negation")
1151 pprO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
1152 pprO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
1153 pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
1154 pprO DefaultOrigin = ptext (sLit "a 'default' declaration")
1155 pprO DoOrigin = ptext (sLit "a do statement")
1156 pprO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
1157 pprO ProcOrigin = ptext (sLit "a proc expression")
1158 pprO (TypeEqOrigin eq) = ptext (sLit "an equality") <+> ppr eq
1159 pprO AnnOrigin = ptext (sLit "an annotation")
1160 pprO FunDepOrigin = ptext (sLit "a functional dependency")
1162 instance Outputable EqOrigin where
1163 ppr (UnifyOrigin t1 t2) = ppr t1 <+> char '~' <+> ppr t2