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 TcTyThing(..), pprTcTyThingCategory, RefinementVisibility(..),
24 ThStage(..), topStage, topAnnStage, topSpliceStage,
25 ThLevel, impLevel, outerLevel, thLevel,
28 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
31 Inst(..), EqInstCo, InstOrigin(..), InstLoc(..),
32 pprInstLoc, pprInstArising, instLocSpan, instLocOrigin, setInstLoc,
33 LIE, emptyLIE, unitLIE, plusLIE, consLIE, instLoc, instSpan,
34 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
37 TcId, TcIdSet, TcDictBinds, TcTyVarBind(..), TcTyVarBinds
41 #include "HsVersions.h"
43 import HsSyn hiding (LIE)
75 %************************************************************************
77 Standard monad definition for TcRn
78 All the combinators for the monad can be found in TcRnMonad
80 %************************************************************************
82 The monad itself has to be defined here, because it is mentioned by ErrCtxt
85 type TcRef a = IORef a
86 type TcId = Id -- Type may be a TcType
88 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
90 type TcRnIf a b c = IOEnv (Env a b) c
91 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
93 type IfG a = IfM () a -- Top level
94 type IfL a = IfM IfLclEnv a -- Nested
95 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
96 type RnM a = TcRn a -- Historical
97 type TcM a = TcRn a -- Historical
100 Representation of type bindings to uninstantiated meta variables used during
104 data TcTyVarBind = TcTyVarBind TcTyVar TcType
106 type TcTyVarBinds = Bag TcTyVarBind
108 instance Outputable TcTyVarBind where
109 ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
113 %************************************************************************
115 The main environment types
117 %************************************************************************
120 data Env gbl lcl -- Changes as we move into an expression
122 env_top :: HscEnv, -- Top-level stuff that never changes
123 -- Includes all info about imported things
125 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
126 -- Unique supply for local varibles
128 env_gbl :: gbl, -- Info about things defined at the top level
129 -- of the module being compiled
131 env_lcl :: lcl -- Nested stuff; changes as we go into
134 -- TcGblEnv describes the top-level of the module at the
135 -- point at which the typechecker is finished work.
136 -- It is this structure that is handed on to the desugarer
140 tcg_mod :: Module, -- ^ Module being compiled
141 tcg_src :: HscSource,
142 -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
144 tcg_rdr_env :: GlobalRdrEnv, -- ^ Top level envt; used during renaming
145 tcg_default :: Maybe [Type],
146 -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
148 tcg_fix_env :: FixityEnv, -- ^ Just for things in this module
149 tcg_field_env :: RecFieldEnv, -- ^ Just for things in this module
151 tcg_type_env :: TypeEnv,
152 -- ^ Global type env for the module we are compiling now. All
153 -- TyCons and Classes (for this module) end up in here right away,
154 -- along with their derived constructors, selectors.
156 -- (Ids defined in this module start in the local envt, though they
157 -- move to the global envt during zonking)
159 tcg_type_env_var :: TcRef TypeEnv,
160 -- Used only to initialise the interface-file
161 -- typechecker in initIfaceTcRn, so that it can see stuff
162 -- bound in this module when dealing with hi-boot recursions
163 -- Updated at intervals (e.g. after dealing with types and classes)
165 tcg_inst_env :: InstEnv,
166 -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
168 tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
170 -- Now a bunch of things about this module that are simply
171 -- accumulated, but never consulted until the end.
172 -- Nevertheless, it's convenient to accumulate them along
173 -- with the rest of the info from this module.
174 tcg_exports :: [AvailInfo], -- ^ What is exported
175 tcg_imports :: ImportAvails,
176 -- ^ Information about what was imported from where, including
177 -- things bound in this module.
180 -- ^ What is defined in this module and what is used.
181 -- The latter is used to generate
183 -- (a) version tracking; no need to recompile if these things have
184 -- not changed version stamp
186 -- (b) unused-import info
188 tcg_keep :: TcRef NameSet,
189 -- ^ Locally-defined top-level names to keep alive.
191 -- "Keep alive" means give them an Exported flag, so that the
192 -- simplifier does not discard them as dead code, and so that they
193 -- are exposed in the interface file (but not to export to the
196 -- Some things, like dict-fun Ids and default-method Ids are "born"
197 -- with the Exported flag on, for exactly the above reason, but some
198 -- we only discover as we go. Specifically:
200 -- * The to/from functions for generic data types
202 -- * Top-level variables appearing free in the RHS of an orphan
205 -- * Top-level variables appearing free in a TH bracket
207 tcg_inst_uses :: TcRef NameSet,
208 -- ^ Home-package Dfuns actually used.
210 -- Used to generate version dependencies This records usages, rather
211 -- like tcg_dus, but it has to be a mutable variable so it can be
212 -- augmented when we look up an instance. These uses of dfuns are
213 -- rather like the free variables of the program, but are implicit
214 -- instead of explicit.
216 tcg_th_used :: TcRef Bool,
217 -- ^ @True@ <=> Template Haskell syntax used.
219 -- We need this so that we can generate a dependency on the Template
220 -- Haskell package, becuase the desugarer is going to emit loads of
221 -- references to TH symbols. It's rather like tcg_inst_uses; the
222 -- reference is implicit rather than explicit, so we have to zap a
225 tcg_dfun_n :: TcRef OccSet,
226 -- ^ Allows us to choose unique DFun names.
228 -- The next fields accumulate the payload of the module
229 -- The binds, rules and foreign-decl fiels are collected
230 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
232 tcg_rn_exports :: Maybe [Located (IE Name)],
233 tcg_rn_imports :: [LImportDecl Name],
234 -- Keep the renamed imports regardless. They are not
235 -- voluminous and are needed if you want to report unused imports
236 tcg_used_rdrnames :: TcRef (Set RdrName),
237 tcg_rn_decls :: Maybe (HsGroup Name),
238 -- ^ Renamed decls, maybe. @Nothing@ <=> Don't retain renamed
241 tcg_binds :: LHsBinds Id, -- Value bindings in this module
242 tcg_warns :: Warnings, -- ...Warnings and deprecations
243 tcg_anns :: [Annotation], -- ...Annotations
244 tcg_insts :: [Instance], -- ...Instances
245 tcg_fam_insts :: [FamInst], -- ...Family instances
246 tcg_rules :: [LRuleDecl Id], -- ...Rules
247 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
249 tcg_doc_hdr :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
250 tcg_hpc :: AnyHpcUsage -- ^ @True@ if any part of the prog uses hpc
255 = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
256 -- to the fields for that constructor
257 NameSet -- Set of all fields declared *in this module*;
258 -- used to suppress name-shadowing complaints
259 -- when using record wild cards
260 -- E.g. let fld = e in C {..}
261 -- This is used when dealing with ".." notation in record
262 -- construction and pattern matching.
263 -- The FieldEnv deals *only* with constructors defined in *this*
264 -- module. For imported modules, we get the same info from the
268 %************************************************************************
270 The interface environments
271 Used when dealing with IfaceDecls
273 %************************************************************************
278 -- The type environment for the module being compiled,
279 -- in case the interface refers back to it via a reference that
280 -- was originally a hi-boot file.
281 -- We need the module name so we can test when it's appropriate
282 -- to look in this env.
283 if_rec_types :: Maybe (Module, IfG TypeEnv)
284 -- Allows a read effect, so it can be in a mutable
285 -- variable; c.f. handling the external package type env
286 -- Nothing => interactive stuff, no loops possible
291 -- The module for the current IfaceDecl
292 -- So if we see f = \x -> x
293 -- it means M.f = \x -> x, where M is the if_mod
296 -- The field is used only for error reporting
297 -- if (say) there's a Lint error in it
299 -- Where the interface came from:
300 -- .hi file, or GHCi state, or ext core
301 -- plus which bit is currently being examined
303 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
304 if_id_env :: UniqFM Id -- Nested id binding
309 %************************************************************************
311 The local typechecker environment
313 %************************************************************************
315 The Global-Env/Local-Env story
316 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
317 During type checking, we keep in the tcg_type_env
318 * All types and classes
319 * All Ids derived from types and classes (constructors, selectors)
321 At the end of type checking, we zonk the local bindings,
322 and as we do so we add to the tcg_type_env
323 * Locally defined top-level Ids
325 Why? Because they are now Ids not TcIds. This final GlobalEnv is
326 a) fed back (via the knot) to typechecking the
327 unfoldings of interface signatures
328 b) used in the ModDetails of this module
331 data TcLclEnv -- Changes as we move inside an expression
332 -- Discarded after typecheck/rename; not passed on to desugarer
334 tcl_loc :: SrcSpan, -- Source span
335 tcl_ctxt :: [ErrCtxt], -- Error context, innermost on top
336 tcl_errs :: TcRef Messages, -- Place to accumulate errors
338 tcl_th_ctxt :: ThStage, -- Template Haskell context
339 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
341 tcl_rdr :: LocalRdrEnv, -- Local name envt
342 -- Maintained during renaming, of course, but also during
343 -- type checking, solely so that when renaming a Template-Haskell
344 -- splice we have the right environment for the renamer.
346 -- Does *not* include global name envt; may shadow it
347 -- Includes both ordinary variables and type variables;
348 -- they are kept distinct because tyvar have a different
349 -- occurrence contructor (Name.TvOcc)
350 -- We still need the unsullied global name env so that
351 -- we can look up record field names
353 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and
354 -- TyVars defined in this module
356 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
357 -- Namely, the in-scope TyVars bound in tcl_env,
358 -- plus the tyvars mentioned in the types of Ids bound
360 -- Why mutable? see notes with tcGetGlobalTyVars
362 tcl_lie :: TcRef LIE, -- Place to accumulate type constraints
364 tcl_tybinds :: TcRef TcTyVarBinds -- Meta and coercion type variable
365 -- bindings accumulated during
366 -- constraint solving
370 {- Note [Given Insts]
372 Because of GADTs, we have to pass inwards the Insts provided by type signatures
373 and existential contexts. Consider
374 data T a where { T1 :: b -> b -> T [b] }
375 f :: Eq a => T a -> Bool
376 f (T1 x y) = [x]==[y]
378 The constructor T1 binds an existential variable 'b', and we need Eq [b].
379 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
384 ---------------------------
385 -- Template Haskell stages and levels
386 ---------------------------
388 data ThStage -- See Note [Template Haskell state diagram] in TcSplice
389 = Splice -- Top-level splicing
390 -- This code will be run *at compile time*;
391 -- the result replaces the splice
394 | Comp -- Ordinary Haskell code
397 | Brack -- Inside brackets
398 ThStage -- Binding level = level(stage) + 1
399 (TcRef [PendingSplice]) -- Accumulate pending splices here
400 (TcRef LIE) -- and type constraints here
402 topStage, topAnnStage, topSpliceStage :: ThStage
405 topSpliceStage = Splice
407 instance Outputable ThStage where
408 ppr Splice = text "Splice"
409 ppr Comp = text "Comp"
410 ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
413 -- See Note [Template Haskell levels] in TcSplice
414 -- Incremented when going inside a bracket,
415 -- decremented when going inside a splice
416 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
417 -- original "Template meta-programming for Haskell" paper
419 impLevel, outerLevel :: ThLevel
420 impLevel = 0 -- Imported things; they can be used inside a top level splice
421 outerLevel = 1 -- Things defined outside brackets
422 -- NB: Things at level 0 are not *necessarily* imported.
423 -- eg $( \b -> ... ) here b is bound at level 0
427 -- g1 = $(map ...) is OK
428 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
430 thLevel :: ThStage -> ThLevel
433 thLevel (Brack s _ _) = thLevel s + 1
435 ---------------------------
436 -- Arrow-notation context
437 ---------------------------
440 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
441 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
446 Here, x is not in scope in e1, but it is in scope in e2. This can get
450 proc y -> (proc z -> e1) -< e2
452 Here, x and z are in scope in e1, but y is not. We implement this by
453 recording the environment when passing a proc (using newArrowScope),
454 and returning to that (using escapeArrowScope) on the left of -< and the
460 | ArrowCtxt (Env TcGblEnv TcLclEnv)
462 -- Record the current environment (outside a proc)
463 newArrowScope :: TcM a -> TcM a
466 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
468 -- Return to the stored environment (from the enclosing proc)
469 escapeArrowScope :: TcM a -> TcM a
471 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
473 ArrowCtxt env' -> env'
475 ---------------------------
477 ---------------------------
480 = AGlobal TyThing -- Used only in the return type of a lookup
482 | ATcId { -- Ids defined in this module; may not be fully zonked
484 tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
485 -- Nothing <=> Do not apply a GADT type refinement
486 -- I am wobbly, or have no free
488 -- Just co <=> Apply any type refinement to me,
489 -- and record it in the coercion
490 tct_type :: TcType, -- Type of (coercion applied to id)
491 tct_level :: ThLevel }
493 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
494 -- is currently refined. We only need the Name
495 -- for error-message purposes
497 | AThing TcKind -- Used temporarily, during kind checking, for the
498 -- tycons and clases in this recursive group
500 data RefinementVisibility
501 = Unrefineable -- Do not apply a GADT refinement
502 -- I have no free variables
504 | Rigid HsWrapper -- Apply any refinement to me
505 -- and record it in the coercion
507 | Wobbly -- Do not apply a GADT refinement
510 | WobblyInvisible -- Wobbly type, not available inside current
513 instance Outputable TcTyThing where -- Debugging only
514 ppr (AGlobal g) = pprTyThing g
515 ppr elt@(ATcId {}) = text "Identifier" <>
516 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
517 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
518 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
519 ppr (AThing k) = text "AThing" <+> ppr k
521 pprTcTyThingCategory :: TcTyThing -> SDoc
522 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
523 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
524 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
525 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
527 instance Outputable RefinementVisibility where
528 ppr Unrefineable = ptext (sLit "unrefineable")
529 ppr (Rigid co) = ptext (sLit "rigid") <+> ppr co
530 ppr Wobbly = ptext (sLit "wobbly")
531 ppr WobblyInvisible = ptext (sLit "wobbly-invisible")
536 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
537 -- Monadic so that we have a chance
538 -- to deal with bound type variables just before error
539 -- message construction
541 -- Bool: True <=> this is a landmark context; do not
542 -- discard it when trimming for display
546 %************************************************************************
548 Operations over ImportAvails
550 %************************************************************************
553 -- | 'ImportAvails' summarises what was imported from where, irrespective of
554 -- whether the imported things are actually used or not. It is used:
556 -- * when processing the export list,
558 -- * when constructing usage info for the interface file,
560 -- * to identify the list of directly imported modules for initialisation
561 -- purposes and for optimised overlap checking of family instances,
563 -- * when figuring out what things are really unused
567 imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
568 -- ^ Domain is all directly-imported modules
569 -- The 'ModuleName' is what the module was imported as, e.g. in
577 -- - @True@ => import was @import Foo ()@
579 -- - @False@ => import was some other form
583 -- (a) to help construct the usage information in the interface
584 -- file; if we import somethign we need to recompile if the
585 -- export version changes
587 -- (b) to specify what child modules to initialise
589 -- We need a full ModuleEnv rather than a ModuleNameEnv here,
590 -- because we might be importing modules of the same name from
591 -- different packages. (currently not the case, but might be in the
594 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
595 -- ^ Home-package modules needed by the module being compiled
597 -- It doesn't matter whether any of these dependencies
598 -- are actually /used/ when compiling the module; they
599 -- are listed if they are below it at all. For
600 -- example, suppose M imports A which imports X. Then
601 -- compiling M might not need to consult X.hi, but X
602 -- is still listed in M's dependencies.
604 imp_dep_pkgs :: [PackageId],
605 -- ^ Packages needed by the module being compiled, whether directly,
606 -- or via other modules in this package, or via modules imported
607 -- from other packages.
609 imp_orphs :: [Module],
610 -- ^ Orphan modules below us in the import tree (and maybe including
611 -- us for imported modules)
613 imp_finsts :: [Module]
614 -- ^ Family instance modules below us in the import tree (and maybe
615 -- including us for imported modules)
618 mkModDeps :: [(ModuleName, IsBootInterface)]
619 -> ModuleNameEnv (ModuleName, IsBootInterface)
620 mkModDeps deps = foldl add emptyUFM deps
622 add env elt@(m,_) = addToUFM env m elt
624 emptyImportAvails :: ImportAvails
625 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
626 imp_dep_mods = emptyUFM,
631 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
633 (ImportAvails { imp_mods = mods1,
634 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
635 imp_orphs = orphs1, imp_finsts = finsts1 })
636 (ImportAvails { imp_mods = mods2,
637 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
638 imp_orphs = orphs2, imp_finsts = finsts2 })
639 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
640 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
641 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
642 imp_orphs = orphs1 `unionLists` orphs2,
643 imp_finsts = finsts1 `unionLists` finsts2 }
645 plus_mod_dep (m1, boot1) (m2, boot2)
646 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
647 -- Check mod-names match
648 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
651 %************************************************************************
653 \subsection{Where from}
655 %************************************************************************
657 The @WhereFrom@ type controls where the renamer looks for an interface file
661 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
662 | ImportBySystem -- Non user import.
664 instance Outputable WhereFrom where
665 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
667 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
671 %************************************************************************
673 \subsection[Inst-types]{@Inst@ types}
675 v%************************************************************************
677 An @Inst@ is either a dictionary, an instance of an overloaded
678 literal, or an instance of an overloaded value. We call the latter a
679 ``method'' even though it may not correspond to a class operation.
680 For example, we might have an instance of the @double@ function at
681 type Int, represented by
683 Method 34 doubleId [Int] origin
685 In addition to the basic Haskell variants of 'Inst's, they can now also
686 represent implication constraints 'forall tvs. given => wanted'
687 and equality constraints 'co :: ty1 ~ ty2'.
689 NB: Equalities occur in two flavours:
691 (1) Dict {tci_pred = EqPred ty1 ty2}
692 (2) EqInst {tci_left = ty1, tci_right = ty2, tci_co = coe}
694 The former arises from equalities in contexts, whereas the latter is used
695 whenever the type checker introduces an equality (e.g., during deferring
698 I am not convinced that this duplication is necessary or useful! -=chak
704 tci_pred :: TcPredType, -- Class or implicit parameter only
708 | ImplicInst { -- An implication constraint
709 -- forall tvs. given => wanted
711 tci_tyvars :: [TcTyVar], -- Quantified type variables
712 tci_given :: [Inst], -- Only Dicts and EqInsts
713 -- (no Methods, LitInsts, ImplicInsts)
714 tci_wanted :: [Inst], -- Only Dicts, EqInst, and ImplicInsts
715 -- (no Methods or LitInsts)
719 -- NB: the tci_given are not necessarily rigid
722 tci_id :: TcId, -- The Id for the Inst
724 tci_oid :: TcId, -- The overloaded function
725 -- This function will be a global, local, or ClassOpId;
726 -- inside instance decls (only) it can also be an InstId!
727 -- The id needn't be completely polymorphic.
728 -- You'll probably find its name (for documentation purposes)
729 -- inside the InstOrigin
731 tci_tys :: [TcType], -- The types to which its polymorphic tyvars
732 -- should be instantiated.
733 -- These types must saturate the Id's foralls.
735 tci_theta :: TcThetaType,
736 -- The (types of the) dictionaries to which the function
737 -- must be applied to get the method
741 -- INVARIANT 1: in (Method m f tys theta tau loc)
742 -- type of m = type of (f tys dicts(from theta))
744 -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
745 -- Reason: two methods are considered equal if the
746 -- base Id matches, and the instantiating types
747 -- match. The TcThetaType should then match too.
748 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
752 tci_lit :: HsOverLit Name, -- The literal from the occurrence site
753 -- INVARIANT: never a rebindable-syntax literal
754 -- Reason: tcSyntaxName does unification, and we
755 -- don't want to deal with that during tcSimplify,
756 -- when resolving LitInsts
758 tci_ty :: TcType, -- The type at which the literal is used
762 | EqInst { -- delayed unification of the form
764 tci_left :: TcType, -- ty1 -- both types are...
765 tci_right :: TcType, -- ty2 -- ...free of boxes
766 tci_co :: EqInstCo, -- co
769 tci_name :: Name -- Debugging help only: this makes it easier to
770 -- follow where a constraint is used in a morass
771 -- of trace messages! Unlike other Insts, it
772 -- has no semantic significance whatsoever.
775 type EqInstCo = Either -- Distinguish between given and wanted coercions
776 TcTyVar -- - a wanted equation, with a hole, to be filled
777 -- with a witness for the equality; for equation
778 -- arising from deferring unification, 'ty1' is
779 -- the actual and 'ty2' the expected type
780 Coercion -- - a given equation, with a coercion witnessing
781 -- the equality; a coercion that originates
782 -- from a signature or a GADT is a CoVar, but
783 -- after normalisation of coercions, they can
784 -- be arbitrary Coercions involving constructors
785 -- and pseudo-constructors like sym and trans.
788 @Insts@ are ordered by their class/type info, rather than by their
789 unique. This allows the context-reduction mechanism to use standard finite
790 maps to do their stuff. It's horrible that this code is here, rather
791 than with the Avails handling stuff in TcSimplify
794 instance Ord Inst where
796 -- Used *only* for AvailEnv in TcSimplify
798 instance Eq Inst where
799 (==) i1 i2 = case i1 `cmpInst` i2 of
803 cmpInst :: Inst -> Inst -> Ordering
804 cmpInst d1@(Dict {}) d2@(Dict {}) = tci_pred d1 `tcCmpPred` tci_pred d2
805 cmpInst (Dict {}) _ = LT
807 cmpInst (Method {}) (Dict {}) = GT
808 cmpInst m1@(Method {}) m2@(Method {}) = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
809 (tci_tys m1 `tcCmpTypes` tci_tys m2)
810 cmpInst (Method {}) _ = LT
812 cmpInst (LitInst {}) (Dict {}) = GT
813 cmpInst (LitInst {}) (Method {}) = GT
814 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
815 (tci_ty l1 `tcCmpType` tci_ty l2)
816 cmpInst (LitInst {}) _ = LT
818 -- Implication constraints are compared by *name*
819 -- not by type; that is, we make no attempt to do CSE on them
820 cmpInst (ImplicInst {}) (Dict {}) = GT
821 cmpInst (ImplicInst {}) (Method {}) = GT
822 cmpInst (ImplicInst {}) (LitInst {}) = GT
823 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
824 cmpInst (ImplicInst {}) _ = LT
826 -- same for Equality constraints
827 cmpInst (EqInst {}) (Dict {}) = GT
828 cmpInst (EqInst {}) (Method {}) = GT
829 cmpInst (EqInst {}) (LitInst {}) = GT
830 cmpInst (EqInst {}) (ImplicInst {}) = GT
831 cmpInst i1@(EqInst {}) i2@(EqInst {}) = (tci_left i1 `tcCmpType` tci_left i2) `thenCmp`
832 (tci_right i1 `tcCmpType` tci_right i2)
836 %************************************************************************
838 \subsection[Inst-collections]{LIE: a collection of Insts}
840 %************************************************************************
843 -- FIXME: Rename this. It clashes with (Located (IE ...))
846 isEmptyLIE :: LIE -> Bool
847 isEmptyLIE = isEmptyBag
852 unitLIE :: Inst -> LIE
853 unitLIE inst = unitBag inst
855 mkLIE :: [Inst] -> LIE
856 mkLIE insts = listToBag insts
858 plusLIE :: LIE -> LIE -> LIE
859 plusLIE lie1 lie2 = lie1 `unionBags` lie2
861 plusLIEs :: [LIE] -> LIE
862 plusLIEs lies = unionManyBags lies
864 lieToList :: LIE -> [Inst]
865 lieToList = bagToList
867 listToLIE :: [Inst] -> LIE
868 listToLIE = listToBag
870 consLIE :: Inst -> LIE -> LIE
871 consLIE inst lie = lie `snocBag` inst
872 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
873 -- to ensure that we tend to report the *leftmost* type-constraint error
876 -- we'd like to complain about the '1', not the '3'.
878 -- "Half-hearted" because the rest of the type checker makes no great
879 -- claims for retaining order in the constraint set. Still, this
880 -- seems to improve matters slightly. Exampes: mdofail001, tcfail015
884 %************************************************************************
886 \subsection[Inst-origin]{The @InstOrigin@ type}
888 %************************************************************************
890 The @InstOrigin@ type gives information about where a dictionary came from.
891 This is important for decent error message reporting because dictionaries
892 don't appear in the original source code. Doubtless this type will evolve...
894 It appears in TcMonad because there are a couple of error-message-generation
895 functions that deal with it.
898 -------------------------------------------
899 data InstLoc = InstLoc InstOrigin SrcSpan [ErrCtxt]
901 instLoc :: Inst -> InstLoc
902 instLoc inst = tci_loc inst
904 setInstLoc :: Inst -> InstLoc -> Inst
905 setInstLoc inst new_loc = inst { tci_loc = new_loc }
907 instSpan :: Inst -> SrcSpan
908 instSpan wanted = instLocSpan (instLoc wanted)
910 instLocSpan :: InstLoc -> SrcSpan
911 instLocSpan (InstLoc _ s _) = s
913 instLocOrigin :: InstLoc -> InstOrigin
914 instLocOrigin (InstLoc o _ _) = o
916 pprInstArising :: Inst -> SDoc
917 pprInstArising loc = ptext (sLit "arising from") <+> pprInstLoc (tci_loc loc)
919 pprInstLoc :: InstLoc -> SDoc
920 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
922 -------------------------------------------
924 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
925 -- Places that bind type variables and introduce
926 -- available constraints
928 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
930 -------------------------------------------------------
931 -- The rest are all occurrences: Insts that are 'wanted'
932 -------------------------------------------------------
933 | OccurrenceOf Name -- Occurrence of an overloaded identifier
934 | SpecPragOrigin Name -- Specialisation pragma for identifier
936 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
938 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
939 | NegateOrigin -- Occurrence of syntactic negation
941 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
942 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
943 | TupleOrigin -- (..,..)
945 | InstSigOrigin -- A dict occurrence arising from instantiating
946 -- a polymorphic type during a subsumption check
948 | ExprSigOrigin -- e :: ty
952 | InstScOrigin -- Typechecking superclasses of an instance declaration
954 | NoScOrigin -- A very special hack; see TcSimplify,
955 -- Note [Recursive instances and superclases]
958 | DerivOrigin -- Typechecking deriving
959 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
960 | DefaultOrigin -- Typechecking a default decl
961 | DoOrigin -- Arising from a do expression
962 | ProcOrigin -- Arising from a proc expression
963 | ImplicOrigin SDoc -- An implication constraint
964 | EqOrigin -- A type equality
965 | AnnOrigin -- An annotation
967 instance Outputable InstOrigin where
968 ppr (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
969 ppr (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
970 ppr (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
971 ppr (IPBindOrigin name) = hsep [ptext (sLit "a binding for implicit parameter"), quotes (ppr name)]
972 ppr RecordUpdOrigin = ptext (sLit "a record update")
973 ppr ExprSigOrigin = ptext (sLit "an expression type signature")
974 ppr ViewPatOrigin = ptext (sLit "a view pattern")
975 ppr (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
976 ppr (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
977 ppr (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
978 ppr TupleOrigin = ptext (sLit "a tuple")
979 ppr NegateOrigin = ptext (sLit "a use of syntactic negation")
980 ppr InstScOrigin = ptext (sLit "the superclasses of an instance declaration")
981 ppr NoScOrigin = ptext (sLit "an instance declaration")
982 ppr DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
983 ppr StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
984 ppr DefaultOrigin = ptext (sLit "a 'default' declaration")
985 ppr DoOrigin = ptext (sLit "a do statement")
986 ppr ProcOrigin = ptext (sLit "a proc expression")
987 ppr (ImplicOrigin doc) = doc
988 ppr (SigOrigin info) = pprSkolInfo info
989 ppr EqOrigin = ptext (sLit "a type equality")
990 ppr InstSigOrigin = panic "ppr InstSigOrigin"
991 ppr AnnOrigin = ptext (sLit "an annotation")