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_hetMetLevel :: [TyVar], -- The current environment classifier level (list-of-names)
381 tcl_env :: TcTypeEnv, -- The local type environment: Ids and
382 -- TyVars defined in this module
384 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
385 -- Namely, the in-scope TyVars bound in tcl_env,
386 -- plus the tyvars mentioned in the types of Ids bound
388 -- Why mutable? see notes with tcGetGlobalTyVars
390 tcl_lie :: TcRef WantedConstraints, -- Place to accumulate type constraints
393 tcl_meta :: TcRef Unique, -- The next free unique for TcMetaTyVars
394 -- Guaranteed to be allocated linearly
395 tcl_untch :: Unique -- Any TcMetaTyVar with
396 -- unique >= tcl_untch is touchable
397 -- unique < tcl_untch is untouchable
400 type TcTypeEnv = NameEnv TcTyThing
403 {- Note [Given Insts]
405 Because of GADTs, we have to pass inwards the Insts provided by type signatures
406 and existential contexts. Consider
407 data T a where { T1 :: b -> b -> T [b] }
408 f :: Eq a => T a -> Bool
409 f (T1 x y) = [x]==[y]
411 The constructor T1 binds an existential variable 'b', and we need Eq [b].
412 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
417 ---------------------------
418 -- Template Haskell stages and levels
419 ---------------------------
421 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
422 = Splice -- Top-level splicing
423 -- This code will be run *at compile time*;
424 -- the result replaces the splice
427 | Comp -- Ordinary Haskell code
430 | Brack -- Inside brackets
431 ThStage -- Binding level = level(stage) + 1
432 (TcRef [PendingSplice]) -- Accumulate pending splices here
433 (TcRef WantedConstraints) -- and type constraints here
435 topStage, topAnnStage, topSpliceStage :: ThStage
438 topSpliceStage = Splice
440 instance Outputable ThStage where
441 ppr Splice = text "Splice"
442 ppr Comp = text "Comp"
443 ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
446 -- See Note [Template Haskell levels] in TcSplice
447 -- Incremented when going inside a bracket,
448 -- decremented when going inside a splice
449 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
450 -- original "Template meta-programming for Haskell" paper
452 impLevel, outerLevel :: ThLevel
453 impLevel = 0 -- Imported things; they can be used inside a top level splice
454 outerLevel = 1 -- Things defined outside brackets
455 -- NB: Things at level 0 are not *necessarily* imported.
456 -- eg $( \b -> ... ) here b is bound at level 0
460 -- g1 = $(map ...) is OK
461 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
463 thLevel :: ThStage -> ThLevel
466 thLevel (Brack s _ _) = thLevel s + 1
468 ---------------------------
469 -- Arrow-notation context
470 ---------------------------
473 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
474 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
479 Here, x is not in scope in e1, but it is in scope in e2. This can get
483 proc y -> (proc z -> e1) -< e2
485 Here, x and z are in scope in e1, but y is not. We implement this by
486 recording the environment when passing a proc (using newArrowScope),
487 and returning to that (using escapeArrowScope) on the left of -< and the
493 | ArrowCtxt (Env TcGblEnv TcLclEnv)
495 -- Record the current environment (outside a proc)
496 newArrowScope :: TcM a -> TcM a
499 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
501 -- Return to the stored environment (from the enclosing proc)
502 escapeArrowScope :: TcM a -> TcM a
504 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
506 ArrowCtxt env' -> env'
508 ---------------------------
510 ---------------------------
513 = AGlobal TyThing -- Used only in the return type of a lookup
515 | ATcId { -- Ids defined in this module; may not be fully zonked
517 tct_level :: ThLevel,
518 tct_hetMetLevel :: [TyVar]
521 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
522 -- is currently refined. We only need the Name
523 -- for error-message purposes; it is the corresponding
524 -- Name in the domain of the envt
526 | AThing TcKind -- Used temporarily, during kind checking, for the
527 -- tycons and clases in this recursive group
529 instance Outputable TcTyThing where -- Debugging only
530 ppr (AGlobal g) = pprTyThing g
531 ppr elt@(ATcId {}) = text "Identifier" <>
532 brackets (ppr (tct_id elt) <> dcolon
533 <> ppr (varType (tct_id elt)) <> comma
534 <+> ppr (tct_level elt)
535 <+> ppr (tct_hetMetLevel elt))
536 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
537 ppr (AThing k) = text "AThing" <+> ppr k
539 pprTcTyThingCategory :: TcTyThing -> SDoc
540 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
541 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
542 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
543 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
547 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
548 -- Monadic so that we have a chance
549 -- to deal with bound type variables just before error
550 -- message construction
552 -- Bool: True <=> this is a landmark context; do not
553 -- discard it when trimming for display
557 %************************************************************************
559 Operations over ImportAvails
561 %************************************************************************
564 -- | 'ImportAvails' summarises what was imported from where, irrespective of
565 -- whether the imported things are actually used or not. It is used:
567 -- * when processing the export list,
569 -- * when constructing usage info for the interface file,
571 -- * to identify the list of directly imported modules for initialisation
572 -- purposes and for optimised overlap checking of family instances,
574 -- * when figuring out what things are really unused
578 imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
579 -- ^ Domain is all directly-imported modules
580 -- The 'ModuleName' is what the module was imported as, e.g. in
588 -- - @True@ => import was @import Foo ()@
590 -- - @False@ => import was some other form
594 -- (a) to help construct the usage information in the interface
595 -- file; if we import somethign we need to recompile if the
596 -- export version changes
598 -- (b) to specify what child modules to initialise
600 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
601 -- because we might be importing modules of the same name from
602 -- different packages. (currently not the case, but might be in the
605 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
606 -- ^ Home-package modules needed by the module being compiled
608 -- It doesn't matter whether any of these dependencies
609 -- are actually /used/ when compiling the module; they
610 -- are listed if they are below it at all. For
611 -- example, suppose M imports A which imports X. Then
612 -- compiling M might not need to consult X.hi, but X
613 -- is still listed in M's dependencies.
615 imp_dep_pkgs :: [PackageId],
616 -- ^ Packages needed by the module being compiled, whether directly,
617 -- or via other modules in this package, or via modules imported
618 -- from other packages.
620 imp_orphs :: [Module],
621 -- ^ Orphan modules below us in the import tree (and maybe including
622 -- us for imported modules)
624 imp_finsts :: [Module]
625 -- ^ Family instance modules below us in the import tree (and maybe
626 -- including us for imported modules)
629 mkModDeps :: [(ModuleName, IsBootInterface)]
630 -> ModuleNameEnv (ModuleName, IsBootInterface)
631 mkModDeps deps = foldl add emptyUFM deps
633 add env elt@(m,_) = addToUFM env m elt
635 emptyImportAvails :: ImportAvails
636 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
637 imp_dep_mods = emptyUFM,
642 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
644 (ImportAvails { imp_mods = mods1,
645 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
646 imp_orphs = orphs1, imp_finsts = finsts1 })
647 (ImportAvails { imp_mods = mods2,
648 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
649 imp_orphs = orphs2, imp_finsts = finsts2 })
650 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
651 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
652 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
653 imp_orphs = orphs1 `unionLists` orphs2,
654 imp_finsts = finsts1 `unionLists` finsts2 }
656 plus_mod_dep (m1, boot1) (m2, boot2)
657 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
658 -- Check mod-names match
659 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
662 %************************************************************************
664 \subsection{Where from}
666 %************************************************************************
668 The @WhereFrom@ type controls where the renamer looks for an interface file
672 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
673 | ImportBySystem -- Non user import.
675 instance Outputable WhereFrom where
676 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
678 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
682 %************************************************************************
685 These are forced to be in TcRnTypes because
686 TcLclEnv mentions WantedConstraints
687 WantedConstraint mentions CtLoc
688 CtLoc mentions ErrCtxt
691 v%************************************************************************
694 data WantedConstraints
695 = WC { wc_flat :: Bag WantedEvVar -- Unsolved constraints, all wanted
696 , wc_impl :: Bag Implication
697 , wc_insol :: Bag FlavoredEvVar -- Insoluble constraints, can be
698 -- wanted, given, or derived
699 -- See Note [Insoluble constraints]
702 emptyWC :: WantedConstraints
703 emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
705 mkFlatWC :: Bag WantedEvVar -> WantedConstraints
706 mkFlatWC wevs = WC { wc_flat = wevs, wc_impl = emptyBag, wc_insol = emptyBag }
708 isEmptyWC :: WantedConstraints -> Bool
709 isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
710 = isEmptyBag f && isEmptyBag i && isEmptyBag n
712 insolubleWC :: WantedConstraints -> Bool
713 -- True if there are any insoluble constraints in the wanted bag
714 insolubleWC wc = not (isEmptyBag (wc_insol wc))
715 || anyBag ic_insol (wc_impl wc)
717 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
718 andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
719 (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
720 = WC { wc_flat = f1 `unionBags` f2
721 , wc_impl = i1 `unionBags` i2
722 , wc_insol = n1 `unionBags` n2 }
724 addFlats :: WantedConstraints -> Bag WantedEvVar -> WantedConstraints
725 addFlats wc wevs = wc { wc_flat = wc_flat wc `unionBags` wevs }
727 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
728 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
730 instance Outputable WantedConstraints where
731 ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
732 = ptext (sLit "WC") <+> braces (vcat
733 [ if isEmptyBag f then empty else
734 ptext (sLit "wc_flat =") <+> pprBag pprWantedEvVar f
735 , if isEmptyBag i then empty else
736 ptext (sLit "wc_impl =") <+> pprBag ppr i
737 , if isEmptyBag n then empty else
738 ptext (sLit "wc_insol =") <+> pprBag ppr n ])
740 pprBag :: (a -> SDoc) -> Bag a -> SDoc
741 pprBag pp b = foldrBag (($$) . pp) empty b
746 data Untouchables = NoUntouchables
750 -- A TcMetaTyvar is *touchable* iff its unique u satisfies
754 instance Outputable Untouchables where
755 ppr NoUntouchables = ptext (sLit "No untouchables")
756 ppr (TouchableRange low high) = ptext (sLit "Touchable range:") <+>
757 ppr low <+> char '-' <+> ppr high
759 isNoUntouchables :: Untouchables -> Bool
760 isNoUntouchables NoUntouchables = True
761 isNoUntouchables (TouchableRange {}) = False
763 inTouchableRange :: Untouchables -> TcTyVar -> Bool
764 inTouchableRange NoUntouchables _ = True
765 inTouchableRange (TouchableRange low high) tv
766 = uniq >= low && uniq < high
770 -- EvVar defined in module Var.lhs:
771 -- Evidence variables include all *quantifiable* constraints
773 -- implicit parameters
774 -- coercion variables
777 %************************************************************************
779 Implication constraints
781 %************************************************************************
786 ic_untch :: Untouchables, -- Untouchables: unification variables
787 -- free in the environment
788 ic_env :: TcTypeEnv, -- The type environment
789 -- Used only when generating error messages
790 -- Generally, ic_untch is a superset of tvsof(ic_env)
791 -- However, we don't zonk ic_env when zonking the Implication
792 -- Instead we do that when generating a skolem-escape error message
794 ic_skols :: TcTyVarSet, -- Introduced skolems
795 -- See Note [Skolems in an implication]
797 ic_given :: [EvVar], -- Given evidence variables
798 -- (order does not matter)
799 ic_loc :: GivenLoc, -- Binding location of the implication,
800 -- which is also the location of all the
801 -- given evidence variables
803 ic_wanted :: WantedConstraints, -- The wanted
804 ic_insol :: Bool, -- True iff insolubleWC ic_wanted is true
806 ic_binds :: EvBindsVar -- Points to the place to fill in the
807 -- abstraction and bindings
810 instance Outputable Implication where
811 ppr (Implic { ic_untch = untch, ic_skols = skols, ic_given = given
813 , ic_binds = binds, ic_loc = loc })
814 = ptext (sLit "Implic") <+> braces
815 (sep [ ptext (sLit "Untouchables = ") <+> ppr untch
816 , ptext (sLit "Skolems = ") <+> ppr skols
817 , ptext (sLit "Given = ") <+> pprEvVars given
818 , ptext (sLit "Wanted = ") <+> ppr wanted
819 , ptext (sLit "Binds = ") <+> ppr binds
820 , pprSkolInfo (ctLocOrigin loc)
821 , ppr (ctLocSpan loc) ])
824 Note [Skolems in an implication]
825 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
826 The skolems in an implication are not there to perform a skolem escape
827 check. That happens because all the environment variables are in the
828 untouchables, and therefore cannot be unified with anything at all,
829 let alone the skolems.
831 Instead, ic_skols is used only when considering floating a constraint
832 outside the implication in TcSimplify.floatEqualities or
833 TcSimplify.approximateImplications
835 Note [Insoluble constraints]
836 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
837 Some of the errors that we get during canonicalization are best
838 reported when all constraints have been simplified as much as
839 possible. For instance, assume that during simplification the
840 following constraints arise:
842 [Wanted] F alpha ~ uf1
843 [Wanted] beta ~ uf1 beta
845 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
846 we will simply see a message:
847 'Can't construct the infinite type beta ~ uf1 beta'
848 and the user has no idea what the uf1 variable is.
850 Instead our plan is that we will NOT fail immediately, but:
851 (1) Record the "frozen" error in the ic_insols field
852 (2) Isolate the offending constraint from the rest of the inerts
853 (3) Keep on simplifying/canonicalizing
855 At the end, we will hopefully have substituted uf1 := F alpha, and we
856 will be able to report a more informative error:
857 'Can't construct the infinite type beta ~ F alpha beta'
859 %************************************************************************
861 EvVarX, WantedEvVar, FlavoredEvVar
863 %************************************************************************
866 data EvVarX a = EvVarX EvVar a
867 -- An evidence variable with accompanying info
869 type WantedEvVar = EvVarX WantedLoc -- The location where it arose
870 type FlavoredEvVar = EvVarX CtFlavor
872 instance Outputable (EvVarX a) where
873 ppr (EvVarX ev _) = pprEvVarWithType ev
874 -- If you want to see the associated info,
875 -- use a more specific printing function
877 mkEvVarX :: EvVar -> a -> EvVarX a
880 evVarOf :: EvVarX a -> EvVar
881 evVarOf (EvVarX ev _) = ev
883 evVarX :: EvVarX a -> a
884 evVarX (EvVarX _ a) = a
886 evVarOfPred :: EvVarX a -> PredType
887 evVarOfPred wev = evVarPred (evVarOf wev)
889 wantedToFlavored :: WantedEvVar -> FlavoredEvVar
890 wantedToFlavored (EvVarX v wl) = EvVarX v (Wanted wl)
892 keepWanted :: Bag FlavoredEvVar -> Bag WantedEvVar
894 = foldrBag keep_wanted emptyBag flevs
895 -- Important: use fold*r*Bag to preserve the order of the evidence variables.
897 keep_wanted :: FlavoredEvVar -> Bag WantedEvVar -> Bag WantedEvVar
898 keep_wanted (EvVarX ev (Wanted wloc)) r = consBag (EvVarX ev wloc) r
904 pprEvVars :: [EvVar] -> SDoc -- Print with their types
905 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
907 pprEvVarTheta :: [EvVar] -> SDoc
908 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
910 pprEvVarWithType :: EvVar -> SDoc
911 pprEvVarWithType v = ppr v <+> dcolon <+> pprPredTy (evVarPred v)
913 pprWantedsWithLocs :: WantedConstraints -> SDoc
914 pprWantedsWithLocs wcs
915 = vcat [ pprBag pprWantedEvVarWithLoc (wc_flat wcs)
916 , pprBag ppr (wc_impl wcs)
917 , pprBag ppr (wc_insol wcs) ]
919 pprWantedEvVarWithLoc, pprWantedEvVar :: WantedEvVar -> SDoc
920 pprWantedEvVarWithLoc (EvVarX v loc) = hang (pprEvVarWithType v)
922 pprWantedEvVar (EvVarX v _) = pprEvVarWithType v
925 %************************************************************************
929 %************************************************************************
933 = Given GivenLoc GivenKind -- We have evidence for this constraint in TcEvBinds
934 | Derived WantedLoc -- Derived's are just hints for unifications
935 | Wanted WantedLoc -- We have no evidence bindings for this constraint.
938 = GivenOrig -- Originates in some given, such as signature or pattern match
939 | GivenSolved -- Is given as result of being solved, maybe provisionally on
940 -- some other wanted constraints.
942 instance Outputable CtFlavor where
943 ppr (Given _ GivenOrig) = ptext (sLit "[G]")
944 ppr (Given _ GivenSolved) = ptext (sLit "[S]") -- Print [S] for Given/Solved's
945 ppr (Wanted {}) = ptext (sLit "[W]")
946 ppr (Derived {}) = ptext (sLit "[D]")
948 pprFlavorArising :: CtFlavor -> SDoc
949 pprFlavorArising (Derived wl) = pprArisingAt wl
950 pprFlavorArising (Wanted wl) = pprArisingAt wl
951 pprFlavorArising (Given gl _) = pprArisingAt gl
953 isWanted :: CtFlavor -> Bool
954 isWanted (Wanted {}) = True
957 isGivenOrSolved :: CtFlavor -> Bool
958 isGivenOrSolved (Given {}) = True
959 isGivenOrSolved _ = False
961 isGiven_maybe :: CtFlavor -> Maybe GivenKind
962 isGiven_maybe (Given _ gk) = Just gk
963 isGiven_maybe _ = Nothing
965 isDerived :: CtFlavor -> Bool
966 isDerived (Derived {}) = True
970 %************************************************************************
974 %************************************************************************
976 The 'CtLoc' gives information about where a constraint came from.
977 This is important for decent error message reporting because
978 dictionaries don't appear in the original source code.
982 data CtLoc orig = CtLoc orig SrcSpan [ErrCtxt]
984 type WantedLoc = CtLoc CtOrigin -- Instantiation for wanted constraints
985 type GivenLoc = CtLoc SkolemInfo -- Instantiation for given constraints
987 ctLocSpan :: CtLoc o -> SrcSpan
988 ctLocSpan (CtLoc _ s _) = s
990 ctLocOrigin :: CtLoc o -> o
991 ctLocOrigin (CtLoc o _ _) = o
993 setCtLocOrigin :: CtLoc o -> o' -> CtLoc o'
994 setCtLocOrigin (CtLoc _ s c) o = CtLoc o s c
996 pushErrCtxt :: orig -> ErrCtxt -> CtLoc orig -> CtLoc orig
997 pushErrCtxt o err (CtLoc _ s errs) = CtLoc o s (err:errs)
999 pprArising :: CtOrigin -> SDoc
1000 -- Used for the main, top-level error message
1001 -- We've done special processing for TypeEq and FunDep origins
1002 pprArising (TypeEqOrigin {}) = empty
1003 pprArising FunDepOrigin = empty
1004 pprArising orig = text "arising from" <+> ppr orig
1006 pprArisingAt :: Outputable o => CtLoc o -> SDoc
1007 pprArisingAt (CtLoc o s _) = sep [ text "arising from" <+> ppr o
1008 , text "at" <+> ppr s]
1011 %************************************************************************
1015 %************************************************************************
1018 -- SkolemInfo gives the origin of *given* constraints
1019 -- a) type variables are skolemised
1020 -- b) an implication constraint is generated
1022 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
1023 Type -- a programmer-supplied type signature
1024 -- Location of the binding site is on the TyVar
1026 -- The rest are for non-scoped skolems
1027 | ClsSkol Class -- Bound at a class decl
1028 | InstSkol -- Bound at an instance decl
1029 | DataSkol -- Bound at a data type declaration
1030 | FamInstSkol -- Bound at a family instance decl
1031 | PatSkol -- An existential type variable bound by a pattern for
1032 DataCon -- a data constructor with an existential type.
1033 (HsMatchContext Name)
1034 -- e.g. data T = forall a. Eq a => MkT a
1036 -- The pattern MkT x will allocate an existential type
1037 -- variable for 'a'.
1039 | ArrowSkol -- An arrow form (see TcArrows)
1041 | IPSkol [IPName Name] -- Binding site of an implicit parameter
1043 | RuleSkol RuleName -- The LHS of a RULE
1045 | InferSkol [(Name,TcType)]
1046 -- We have inferred a type for these (mutually-recursivive)
1047 -- polymorphic Ids, and are now checking that their RHS
1048 -- constraints are satisfied.
1050 | BracketSkol -- Template Haskell bracket
1052 | UnkSkol -- Unhelpful info (until I improve it)
1054 instance Outputable SkolemInfo where
1057 pprSkolInfo :: SkolemInfo -> SDoc
1058 -- Complete the sentence "is a rigid type variable bound by..."
1059 pprSkolInfo (SigSkol (FunSigCtxt f) ty)
1060 = hang (ptext (sLit "the type signature for"))
1061 2 (ppr f <+> dcolon <+> ppr ty)
1062 pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
1064 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter bindings for")
1065 <+> pprWithCommas ppr ips
1066 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
1067 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
1068 pprSkolInfo DataSkol = ptext (sLit "the data type declaration")
1069 pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
1070 pprSkolInfo BracketSkol = ptext (sLit "a Template Haskell bracket")
1071 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
1072 pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
1073 pprSkolInfo (PatSkol dc mc) = sep [ ptext (sLit "a pattern with constructor")
1074 , nest 2 $ ppr dc <+> dcolon
1075 <+> ppr (dataConUserType dc) <> comma
1076 , ptext (sLit "in") <+> pprMatchContext mc ]
1077 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
1078 , vcat [ ppr name <+> dcolon <+> ppr ty
1079 | (name,ty) <- ids ]]
1082 -- For type variables the others are dealt with by pprSkolTvBinding.
1083 -- For Insts, these cases should not happen
1084 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
1088 %************************************************************************
1092 %************************************************************************
1095 -- CtOrigin gives the origin of *wanted* constraints
1097 = OccurrenceOf Name -- Occurrence of an overloaded identifier
1098 | AppOrigin -- An application of some kind
1100 | SpecPragOrigin Name -- Specialisation pragma for identifier
1102 | TypeEqOrigin EqOrigin
1104 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
1106 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
1107 | NegateOrigin -- Occurrence of syntactic negation
1109 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
1110 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
1112 | TupleOrigin -- (..,..)
1113 | ExprSigOrigin -- e :: ty
1114 | PatSigOrigin -- p :: ty
1115 | PatOrigin -- Instantiating a polytyped pattern at a constructor
1119 | ScOrigin -- Typechecking superclasses of an instance declaration
1120 | DerivOrigin -- Typechecking deriving
1121 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
1122 | DefaultOrigin -- Typechecking a default decl
1123 | DoOrigin -- Arising from a do expression
1124 | MCompOrigin -- Arising from a monad comprehension
1125 | IfOrigin -- Arising from an if statement
1126 | ProcOrigin -- Arising from a proc expression
1127 | AnnOrigin -- An annotation
1132 { uo_actual :: TcType
1133 , uo_expected :: TcType }
1135 instance Outputable CtOrigin where
1136 ppr orig = pprO orig
1138 pprO :: CtOrigin -> SDoc
1139 pprO (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
1140 pprO AppOrigin = ptext (sLit "an application")
1141 pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
1142 pprO (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
1143 pprO RecordUpdOrigin = ptext (sLit "a record update")
1144 pprO ExprSigOrigin = ptext (sLit "an expression type signature")
1145 pprO PatSigOrigin = ptext (sLit "a pattern type signature")
1146 pprO PatOrigin = ptext (sLit "a pattern")
1147 pprO ViewPatOrigin = ptext (sLit "a view pattern")
1148 pprO IfOrigin = ptext (sLit "an if statement")
1149 pprO (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
1150 pprO (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
1151 pprO (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
1152 pprO SectionOrigin = ptext (sLit "an operator section")
1153 pprO TupleOrigin = ptext (sLit "a tuple")
1154 pprO NegateOrigin = ptext (sLit "a use of syntactic negation")
1155 pprO ScOrigin = ptext (sLit "the superclasses of an instance declaration")
1156 pprO DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
1157 pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
1158 pprO DefaultOrigin = ptext (sLit "a 'default' declaration")
1159 pprO DoOrigin = ptext (sLit "a do statement")
1160 pprO MCompOrigin = ptext (sLit "a statement in a monad comprehension")
1161 pprO ProcOrigin = ptext (sLit "a proc expression")
1162 pprO (TypeEqOrigin eq) = ptext (sLit "an equality") <+> ppr eq
1163 pprO AnnOrigin = ptext (sLit "an annotation")
1164 pprO FunDepOrigin = ptext (sLit "a functional dependency")
1166 instance Outputable EqOrigin where
1167 ppr (UnifyOrigin t1 t2) = ppr t1 <+> char '~' <+> ppr t2