2 % (c) The University of Glasgow 2006
3 % (c) The GRASP Project, Glasgow University, 1992-2002
7 -- The above warning supression flag is a temporary kludge.
8 -- While working on this module you are encouraged to remove it and fix
9 -- any warnings in the module. See
10 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
14 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
17 -- The environment types
19 TcGblEnv(..), TcLclEnv(..),
20 IfGblEnv(..), IfLclEnv(..),
24 ImportAvails(..), emptyImportAvails, plusImportAvails,
25 WhereFrom(..), mkModDeps,
28 TcTyThing(..), pprTcTyThingCategory, RefinementVisibility(..),
31 ThStage(..), topStage, topSpliceStage,
32 ThLevel, impLevel, topLevel,
35 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
38 Inst(..), InstOrigin(..), InstLoc(..),
39 pprInstLoc, pprInstArising, instLocSpan, instLocOrigin,
40 LIE, emptyLIE, unitLIE, plusLIE, consLIE, instLoc, instSpan,
41 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
44 TcId, TcIdSet, TcDictBinds,
48 #include "HsVersions.h"
50 import HsSyn hiding (LIE)
84 %************************************************************************
86 Standard monad definition for TcRn
87 All the combinators for the monad can be found in TcRnMonad
89 %************************************************************************
91 The monad itself has to be defined here, because it is mentioned by ErrCtxt
94 type TcRef a = IORef a
95 type TcId = Id -- Type may be a TcType
97 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
99 type TcRnIf a b c = IOEnv (Env a b) c
100 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
102 type IfG a = IfM () a -- Top level
103 type IfL a = IfM IfLclEnv a -- Nested
104 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
105 type RnM a = TcRn a -- Historical
106 type TcM a = TcRn a -- Historical
110 %************************************************************************
112 The main environment types
114 %************************************************************************
117 data Env gbl lcl -- Changes as we move into an expression
119 env_top :: HscEnv, -- Top-level stuff that never changes
120 -- Includes all info about imported things
122 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
123 -- Unique supply for local varibles
125 env_gbl :: gbl, -- Info about things defined at the top level
126 -- of the module being compiled
128 env_lcl :: lcl -- Nested stuff; changes as we go into
131 -- TcGblEnv describes the top-level of the module at the
132 -- point at which the typechecker is finished work.
133 -- It is this structure that is handed on to the desugarer
137 tcg_mod :: Module, -- Module being compiled
138 tcg_src :: HscSource, -- What kind of module
139 -- (regular Haskell, hs-boot, ext-core)
141 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
142 tcg_default :: Maybe [Type], -- Types used for defaulting
143 -- Nothing => no 'default' decl
145 tcg_fix_env :: FixityEnv, -- Just for things in this module
146 tcg_field_env :: RecFieldEnv, -- Just for things in this module
148 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
149 -- All TyCons and Classes (for this module) end up in here right away,
150 -- along with their derived constructors, selectors.
152 -- (Ids defined in this module start in the local envt,
153 -- though they move to the global envt during zonking)
155 tcg_type_env_var :: TcRef TypeEnv,
156 -- Used only to initialise the interface-file
157 -- typechecker in initIfaceTcRn, so that it can see stuff
158 -- bound in this module when dealing with hi-boot recursions
159 -- Updated at intervals (e.g. after dealing with types and classes)
161 tcg_inst_env :: InstEnv, -- Instance envt for *home-package*
162 -- modules; Includes the dfuns in
164 tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
166 -- Now a bunch of things about this module that are simply
167 -- accumulated, but never consulted until the end.
168 -- Nevertheless, it's convenient to accumulate them along
169 -- with the rest of the info from this module.
170 tcg_exports :: [AvailInfo], -- What is exported
171 tcg_imports :: ImportAvails, -- Information about what was imported
172 -- from where, including things bound
175 tcg_dus :: DefUses, -- What is defined in this module and what is used.
176 -- The latter is used to generate
177 -- (a) version tracking; no need to recompile if these
178 -- things have not changed version stamp
179 -- (b) unused-import info
181 tcg_keep :: TcRef NameSet, -- Locally-defined top-level names to keep alive
182 -- "Keep alive" means give them an Exported flag, so
183 -- that the simplifier does not discard them as dead
184 -- code, and so that they are exposed in the interface file
185 -- (but not to export to the user).
187 -- Some things, like dict-fun Ids and default-method Ids are
188 -- "born" with the Exported flag on, for exactly the above reason,
189 -- but some we only discover as we go. Specifically:
190 -- * The to/from functions for generic data types
191 -- * Top-level variables appearing free in the RHS of an orphan rule
192 -- * Top-level variables appearing free in a TH bracket
194 tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used
195 -- Used to generate version dependencies
196 -- This records usages, rather like tcg_dus, but it has to
197 -- be a mutable variable so it can be augmented
198 -- when we look up an instance. These uses of dfuns are
199 -- rather like the free variables of the program, but
200 -- are implicit instead of explicit.
202 tcg_th_used :: TcRef Bool, -- True <=> Template Haskell syntax used
203 -- We need this so that we can generate a dependency on the
204 -- Template Haskell package, becuase the desugarer is going to
205 -- emit loads of references to TH symbols. It's rather like
206 -- tcg_inst_uses; the reference is implicit rather than explicit,
207 -- so we have to zap a mutable variable.
209 tcg_dfun_n :: TcRef Int, -- Allows us to number off the names of DFuns
210 -- It's convenient to allocate an External Name for a DFun, with
211 -- a permanently-fixed unique, just like other top-level functions
212 -- defined in this module. But that means we need a canonical
213 -- occurrence name, distinct from all other dfuns in this module,
214 -- and this name supply serves that purpose (df1, df2, etc).
216 -- The next fields accumulate the payload of the module
217 -- The binds, rules and foreign-decl fiels are collected
218 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
220 -- The next fields accumulate the payload of the
221 -- module The binds, rules and foreign-decl fiels are
222 -- collected initially in un-zonked form and are
223 -- finally zonked in tcRnSrcDecls
225 tcg_rn_imports :: Maybe [LImportDecl Name],
226 tcg_rn_exports :: Maybe [Located (IE Name)],
227 tcg_rn_decls :: Maybe (HsGroup Name), -- renamed decls, maybe
228 -- Nothing <=> Don't retain renamed decls
230 tcg_binds :: LHsBinds Id, -- Value bindings in this module
231 tcg_deprecs :: Deprecations, -- ...Deprecations
232 tcg_insts :: [Instance], -- ...Instances
233 tcg_fam_insts :: [FamInst], -- ...Family instances
234 tcg_rules :: [LRuleDecl Id], -- ...Rules
235 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
237 tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
238 tcg_hmi :: HaddockModInfo Name, -- Haddock module information
239 tcg_hpc :: AnyHpcUsage -- True if any part of the prog uses hpc instrumentation.
242 type RecFieldEnv = NameEnv [Name] -- Maps a constructor name *in this module*
243 -- to the fields for that constructor
244 -- This is used when dealing with ".." notation in record
245 -- construction and pattern matching.
246 -- The FieldEnv deals *only* with constructors defined in
247 -- *thie* module. For imported modules, we get the same info
251 %************************************************************************
253 The interface environments
254 Used when dealing with IfaceDecls
256 %************************************************************************
261 -- The type environment for the module being compiled,
262 -- in case the interface refers back to it via a reference that
263 -- was originally a hi-boot file.
264 -- We need the module name so we can test when it's appropriate
265 -- to look in this env.
266 if_rec_types :: Maybe (Module, IfG TypeEnv)
267 -- Allows a read effect, so it can be in a mutable
268 -- variable; c.f. handling the external package type env
269 -- Nothing => interactive stuff, no loops possible
274 -- The module for the current IfaceDecl
275 -- So if we see f = \x -> x
276 -- it means M.f = \x -> x, where M is the if_mod
279 -- The field is used only for error reporting
280 -- if (say) there's a Lint error in it
282 -- Where the interface came from:
283 -- .hi file, or GHCi state, or ext core
284 -- plus which bit is currently being examined
286 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
287 if_id_env :: UniqFM Id -- Nested id binding
292 %************************************************************************
294 The local typechecker environment
296 %************************************************************************
298 The Global-Env/Local-Env story
299 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
300 During type checking, we keep in the tcg_type_env
301 * All types and classes
302 * All Ids derived from types and classes (constructors, selectors)
304 At the end of type checking, we zonk the local bindings,
305 and as we do so we add to the tcg_type_env
306 * Locally defined top-level Ids
308 Why? Because they are now Ids not TcIds. This final GlobalEnv is
309 a) fed back (via the knot) to typechecking the
310 unfoldings of interface signatures
311 b) used in the ModDetails of this module
314 data TcLclEnv -- Changes as we move inside an expression
315 -- Discarded after typecheck/rename; not passed on to desugarer
317 tcl_loc :: SrcSpan, -- Source span
318 tcl_ctxt :: ErrCtxt, -- Error context
319 tcl_errs :: TcRef Messages, -- Place to accumulate errors
321 tcl_th_ctxt :: ThStage, -- Template Haskell context
322 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
324 tcl_rdr :: LocalRdrEnv, -- Local name envt
325 -- Maintained during renaming, of course, but also during
326 -- type checking, solely so that when renaming a Template-Haskell
327 -- splice we have the right environment for the renamer.
329 -- Does *not* include global name envt; may shadow it
330 -- Includes both ordinary variables and type variables;
331 -- they are kept distinct because tyvar have a different
332 -- occurrence contructor (Name.TvOcc)
333 -- We still need the unsullied global name env so that
334 -- we can look up record field names
336 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
337 -- defined in this module
339 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
340 -- Namely, the in-scope TyVars bound in tcl_env,
341 -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
342 -- Why mutable? see notes with tcGetGlobalTyVars
344 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
348 {- Note [Given Insts]
350 Because of GADTs, we have to pass inwards the Insts provided by type signatures
351 and existential contexts. Consider
352 data T a where { T1 :: b -> b -> T [b] }
353 f :: Eq a => T a -> Bool
354 f (T1 x y) = [x]==[y]
356 The constructor T1 binds an existential variable 'b', and we need Eq [b].
357 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
362 ---------------------------
363 -- Template Haskell levels
364 ---------------------------
367 -- Indicates how many levels of brackets we are inside
369 -- Incremented when going inside a bracket,
370 -- decremented when going inside a splice
371 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
372 -- original "Template meta-programming for Haskell" paper
374 impLevel, topLevel :: ThLevel
375 topLevel = 1 -- Things defined at top level of this module
376 impLevel = 0 -- Imported things; they can be used inside a top level splice
380 -- g1 = $(map ...) is OK
381 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
385 = Comp -- Ordinary compiling, at level topLevel
386 | Splice ThLevel -- Inside a splice
387 | Brack ThLevel -- Inside brackets;
388 (TcRef [PendingSplice]) -- accumulate pending splices here
389 (TcRef LIE) -- and type constraints here
390 topStage, topSpliceStage :: ThStage
392 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
394 ---------------------------
395 -- Arrow-notation context
396 ---------------------------
399 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
400 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
405 Here, x is not in scope in e1, but it is in scope in e2. This can get
409 proc y -> (proc z -> e1) -< e2
411 Here, x and z are in scope in e1, but y is not. We implement this by
412 recording the environment when passing a proc (using newArrowScope),
413 and returning to that (using escapeArrowScope) on the left of -< and the
419 | ArrowCtxt (Env TcGblEnv TcLclEnv)
421 -- Record the current environment (outside a proc)
422 newArrowScope :: TcM a -> TcM a
425 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
427 -- Return to the stored environment (from the enclosing proc)
428 escapeArrowScope :: TcM a -> TcM a
430 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
432 ArrowCtxt env' -> env'
434 ---------------------------
436 ---------------------------
439 = AGlobal TyThing -- Used only in the return type of a lookup
441 | ATcId { -- Ids defined in this module; may not be fully zonked
443 tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
444 -- Nothing <=> Do not apply a GADT type refinement
445 -- I am wobbly, or have no free
447 -- Just co <=> Apply any type refinement to me,
448 -- and record it in the coercion
449 tct_type :: TcType, -- Type of (coercion applied to id)
450 tct_level :: ThLevel }
452 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
453 -- is currently refined. We only need the Name
454 -- for error-message purposes
456 | AThing TcKind -- Used temporarily, during kind checking, for the
457 -- tycons and clases in this recursive group
459 data RefinementVisibility
460 = Unrefineable -- Do not apply a GADT refinement
461 -- I have no free variables
463 | Rigid HsWrapper -- Apply any refinement to me
464 -- and record it in the coercion
466 | Wobbly -- Do not apply a GADT refinement
469 | WobblyInvisible -- Wobbly type, not available inside current
472 instance Outputable TcTyThing where -- Debugging only
473 ppr (AGlobal g) = pprTyThing g
474 ppr elt@(ATcId {}) = text "Identifier" <>
475 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
476 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
477 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
478 ppr (AThing k) = text "AThing" <+> ppr k
480 pprTcTyThingCategory :: TcTyThing -> SDoc
481 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
482 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
483 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
484 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
486 instance Outputable RefinementVisibility where
487 ppr Unrefineable = ptext (sLit "unrefineable")
488 ppr (Rigid co) = ptext (sLit "rigid") <+> ppr co
489 ppr Wobbly = ptext (sLit "wobbly")
490 ppr WobblyInvisible = ptext (sLit "wobbly-invisible")
495 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
496 -- Innermost first. Monadic so that we have a chance
497 -- to deal with bound type variables just before error
498 -- message construction
502 %************************************************************************
504 Operations over ImportAvails
506 %************************************************************************
508 ImportAvails summarises what was imported from where, irrespective
509 of whether the imported things are actually used or not
510 It is used * when processing the export list
511 * when constructing usage info for the inteface file
512 * to identify the list of directly imported modules
513 for initialisation purposes and
514 for optimsed overlap checking of family instances
515 * when figuring out what things are really unused
520 imp_mods :: ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)]),
521 -- Domain is all directly-imported modules
522 -- The ModuleName is what the module was imported as, e.g. in
526 -- True => import was "import Foo ()"
527 -- False => import was some other form
529 -- We need the Module in the range because we can't get
530 -- the keys of a ModuleEnv
532 -- (a) to help construct the usage information in
533 -- the interface file; if we import somethign we
534 -- need to recompile if the export version changes
535 -- (b) to specify what child modules to initialise
537 -- We need a full ModuleEnv rather than a ModuleNameEnv
538 -- here, because we might be importing modules of the
539 -- same name from different packages. (currently not the case,
540 -- but might be in the future).
542 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
543 -- Home-package modules needed by the module being compiled
545 -- It doesn't matter whether any of these dependencies
546 -- are actually *used* when compiling the module; they
547 -- are listed if they are below it at all. For
548 -- example, suppose M imports A which imports X. Then
549 -- compiling M might not need to consult X.hi, but X
550 -- is still listed in M's dependencies.
552 imp_dep_pkgs :: [PackageId],
553 -- Packages needed by the module being compiled, whether
554 -- directly, or via other modules in this package, or via
555 -- modules imported from other packages.
557 imp_orphs :: [Module],
558 -- Orphan modules below us in the import tree (and maybe
559 -- including us for imported modules)
561 imp_finsts :: [Module]
562 -- Family instance modules below us in the import tree (and
563 -- maybe including us for imported modules)
566 mkModDeps :: [(ModuleName, IsBootInterface)]
567 -> ModuleNameEnv (ModuleName, IsBootInterface)
568 mkModDeps deps = foldl add emptyUFM deps
570 add env elt@(m,_) = addToUFM env m elt
572 emptyImportAvails :: ImportAvails
573 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
574 imp_dep_mods = emptyUFM,
579 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
581 (ImportAvails { imp_mods = mods1,
582 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
583 imp_orphs = orphs1, imp_finsts = finsts1 })
584 (ImportAvails { imp_mods = mods2,
585 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
586 imp_orphs = orphs2, imp_finsts = finsts2 })
587 = ImportAvails { imp_mods = plusModuleEnv_C plus_mod mods1 mods2,
588 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
589 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
590 imp_orphs = orphs1 `unionLists` orphs2,
591 imp_finsts = finsts1 `unionLists` finsts2 }
593 plus_mod (m1, xs1) (_, xs2) = (m1, xs1 ++ xs2)
594 plus_mod_dep (m1, boot1) (m2, boot2)
595 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
596 -- Check mod-names match
597 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
600 %************************************************************************
602 \subsection{Where from}
604 %************************************************************************
606 The @WhereFrom@ type controls where the renamer looks for an interface file
610 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
611 | ImportBySystem -- Non user import.
613 instance Outputable WhereFrom where
614 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
616 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
620 %************************************************************************
622 \subsection[Inst-types]{@Inst@ types}
624 v%************************************************************************
626 An @Inst@ is either a dictionary, an instance of an overloaded
627 literal, or an instance of an overloaded value. We call the latter a
628 ``method'' even though it may not correspond to a class operation.
629 For example, we might have an instance of the @double@ function at
630 type Int, represented by
632 Method 34 doubleId [Int] origin
634 In addition to the basic Haskell variants of 'Inst's, they can now also
635 represent implication constraints 'forall tvs. given => wanted'
636 and equality constraints 'co :: ty1 ~ ty2'.
638 NB: Equalities occur in two flavours:
640 (1) Dict {tci_pred = EqPred ty1 ty2}
641 (2) EqInst {tci_left = ty1, tci_right = ty2, tci_co = coe}
643 The former arises from equalities in contexts, whereas the latter is used
644 whenever the type checker introduces an equality (e.g., during deferring
647 I am not convinced that this duplication is necessary or useful! -=chak
653 tci_pred :: TcPredType,
657 | ImplicInst { -- An implication constraint
658 -- forall tvs. given => wanted
660 tci_tyvars :: [TcTyVar], -- Quantified type variables
661 tci_given :: [Inst], -- Only Dicts and EqInsts
662 -- (no Methods, LitInsts, ImplicInsts)
663 tci_wanted :: [Inst], -- Only Dicts, EqInst, and ImplicInsts
664 -- (no Methods or LitInsts)
668 -- NB: the tci_given are not necessarily rigid
671 tci_id :: TcId, -- The Id for the Inst
673 tci_oid :: TcId, -- The overloaded function
674 -- This function will be a global, local, or ClassOpId;
675 -- inside instance decls (only) it can also be an InstId!
676 -- The id needn't be completely polymorphic.
677 -- You'll probably find its name (for documentation purposes)
678 -- inside the InstOrigin
680 tci_tys :: [TcType], -- The types to which its polymorphic tyvars
681 -- should be instantiated.
682 -- These types must saturate the Id's foralls.
684 tci_theta :: TcThetaType,
685 -- The (types of the) dictionaries to which the function
686 -- must be applied to get the method
690 -- INVARIANT 1: in (Method m f tys theta tau loc)
691 -- type of m = type of (f tys dicts(from theta))
693 -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
694 -- Reason: two methods are considered equal if the
695 -- base Id matches, and the instantiating types
696 -- match. The TcThetaType should then match too.
697 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
701 tci_lit :: HsOverLit Name, -- The literal from the occurrence site
702 -- INVARIANT: never a rebindable-syntax literal
703 -- Reason: tcSyntaxName does unification, and we
704 -- don't want to deal with that during tcSimplify,
705 -- when resolving LitInsts
707 tci_ty :: TcType, -- The type at which the literal is used
711 | EqInst { -- delayed unification of the form
713 tci_left :: TcType, -- ty1 -- both types are...
714 tci_right :: TcType, -- ty2 -- ...free of boxes
715 tci_co :: Either -- co
716 TcTyVar -- - a wanted equation, with a hole, to be
717 -- filled with a witness for the equality;
718 -- for equation arising from deferring
719 -- unification, 'ty1' is the actual and
720 -- 'ty2' the expected type
721 Coercion, -- - a given equation, with a coercion
722 -- witnessing the equality;
723 -- a coercion that originates from a
724 -- signature or a GADT is a CoVar, but
725 -- after normalisation of coercions, they
726 -- can be arbitrary Coercions involving
727 -- constructors and pseudo-constructors
728 -- like sym and trans.
731 tci_name :: Name -- Debugging help only: this makes it easier to
732 -- follow where a constraint is used in a morass
733 -- of trace messages! Unlike other Insts, it has
734 -- no semantic significance whatsoever.
738 @Insts@ are ordered by their class/type info, rather than by their
739 unique. This allows the context-reduction mechanism to use standard finite
740 maps to do their stuff. It's horrible that this code is here, rather
741 than with the Avails handling stuff in TcSimplify
744 instance Ord Inst where
747 instance Eq Inst where
748 (==) i1 i2 = case i1 `cmpInst` i2 of
752 cmpInst d1@(Dict {}) d2@(Dict {}) = tci_pred d1 `tcCmpPred` tci_pred d2
753 cmpInst (Dict {}) other = LT
755 cmpInst (Method {}) (Dict {}) = GT
756 cmpInst m1@(Method {}) m2@(Method {}) = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
757 (tci_tys m1 `tcCmpTypes` tci_tys m2)
758 cmpInst (Method {}) other = LT
760 cmpInst (LitInst {}) (Dict {}) = GT
761 cmpInst (LitInst {}) (Method {}) = GT
762 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
763 (tci_ty l1 `tcCmpType` tci_ty l2)
764 cmpInst (LitInst {}) other = LT
766 -- Implication constraints are compared by *name*
767 -- not by type; that is, we make no attempt to do CSE on them
768 cmpInst (ImplicInst {}) (Dict {}) = GT
769 cmpInst (ImplicInst {}) (Method {}) = GT
770 cmpInst (ImplicInst {}) (LitInst {}) = GT
771 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
772 cmpInst (ImplicInst {}) other = LT
774 -- same for Equality constraints
775 cmpInst (EqInst {}) (Dict {}) = GT
776 cmpInst (EqInst {}) (Method {}) = GT
777 cmpInst (EqInst {}) (LitInst {}) = GT
778 cmpInst (EqInst {}) (ImplicInst {}) = GT
779 cmpInst i1@(EqInst {}) i2@(EqInst {}) = tci_name i1 `compare` tci_name i2
783 %************************************************************************
785 \subsection[Inst-collections]{LIE: a collection of Insts}
787 %************************************************************************
790 -- FIXME: Rename this. It clashes with (Located (IE ...))
793 isEmptyLIE = isEmptyBag
795 unitLIE inst = unitBag inst
796 mkLIE insts = listToBag insts
797 plusLIE lie1 lie2 = lie1 `unionBags` lie2
798 plusLIEs lies = unionManyBags lies
799 lieToList = bagToList
800 listToLIE = listToBag
802 consLIE inst lie = lie `snocBag` inst
803 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
804 -- to ensure that we tend to report the *leftmost* type-constraint error
807 -- we'd like to complain about the '1', not the '3'.
809 -- "Half-hearted" because the rest of the type checker makes no great
810 -- claims for retaining order in the constraint set. Still, this
811 -- seems to improve matters slightly. Exampes: mdofail001, tcfail015
815 %************************************************************************
817 \subsection[Inst-origin]{The @InstOrigin@ type}
819 %************************************************************************
821 The @InstOrigin@ type gives information about where a dictionary came from.
822 This is important for decent error message reporting because dictionaries
823 don't appear in the original source code. Doubtless this type will evolve...
825 It appears in TcMonad because there are a couple of error-message-generation
826 functions that deal with it.
829 -------------------------------------------
830 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
832 instLoc :: Inst -> InstLoc
833 instLoc inst = tci_loc inst
835 instSpan :: Inst -> SrcSpan
836 instSpan wanted = instLocSpan (instLoc wanted)
838 instLocSpan :: InstLoc -> SrcSpan
839 instLocSpan (InstLoc _ s _) = s
841 instLocOrigin :: InstLoc -> InstOrigin
842 instLocOrigin (InstLoc o _ _) = o
844 pprInstArising :: Inst -> SDoc
845 pprInstArising loc = ptext (sLit "arising from") <+> pprInstLoc (tci_loc loc)
847 pprInstLoc :: InstLoc -> SDoc
848 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
850 -------------------------------------------
852 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
853 -- Places that bind type variables and introduce
854 -- available constraints
856 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
858 -------------------------------------------------------
859 -- The rest are all occurrences: Insts that are 'wanted'
860 -------------------------------------------------------
861 | OccurrenceOf Name -- Occurrence of an overloaded identifier
862 | SpecPragOrigin Name -- Specialisation pragma for identifier
864 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
866 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
867 | NegateOrigin -- Occurrence of syntactic negation
869 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
870 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
871 | TupleOrigin -- (..,..)
873 | InstSigOrigin -- A dict occurrence arising from instantiating
874 -- a polymorphic type during a subsumption check
876 | ExprSigOrigin -- e :: ty
879 | InstScOrigin -- Typechecking superclasses of an instance declaration
880 | DerivOrigin -- Typechecking deriving
881 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
882 | DefaultOrigin -- Typechecking a default decl
883 | DoOrigin -- Arising from a do expression
884 | ProcOrigin -- Arising from a proc expression
885 | ImplicOrigin SDoc -- An implication constraint
886 | EqOrigin -- A type equality
888 instance Outputable InstOrigin where
889 ppr (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
890 ppr (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
891 ppr (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
892 ppr (IPBindOrigin name) = hsep [ptext (sLit "a binding for implicit parameter"), quotes (ppr name)]
893 ppr RecordUpdOrigin = ptext (sLit "a record update")
894 ppr ExprSigOrigin = ptext (sLit "an expression type signature")
895 ppr ViewPatOrigin = ptext (sLit "a view pattern")
896 ppr (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
897 ppr (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
898 ppr (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
899 ppr TupleOrigin = ptext (sLit "a tuple")
900 ppr NegateOrigin = ptext (sLit "a use of syntactic negation")
901 ppr InstScOrigin = ptext (sLit "the superclasses of an instance declaration")
902 ppr DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
903 ppr StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
904 ppr DefaultOrigin = ptext (sLit "a 'default' declaration")
905 ppr DoOrigin = ptext (sLit "a do statement")
906 ppr ProcOrigin = ptext (sLit "a proc expression")
907 ppr (ImplicOrigin doc) = doc
908 ppr (SigOrigin info) = pprSkolInfo info
909 ppr EqOrigin = ptext (sLit "a type equality")