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)
83 %************************************************************************
85 Standard monad definition for TcRn
86 All the combinators for the monad can be found in TcRnMonad
88 %************************************************************************
90 The monad itself has to be defined here, because it is mentioned by ErrCtxt
93 type TcRef a = IORef a
94 type TcId = Id -- Type may be a TcType
96 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
98 type TcRnIf a b c = IOEnv (Env a b) c
99 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
101 type IfG a = IfM () a -- Top level
102 type IfL a = IfM IfLclEnv a -- Nested
103 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
104 type RnM a = TcRn a -- Historical
105 type TcM a = TcRn a -- Historical
109 %************************************************************************
111 The main environment types
113 %************************************************************************
116 data Env gbl lcl -- Changes as we move into an expression
118 env_top :: HscEnv, -- Top-level stuff that never changes
119 -- Includes all info about imported things
121 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
122 -- Unique supply for local varibles
124 env_gbl :: gbl, -- Info about things defined at the top level
125 -- of the module being compiled
127 env_lcl :: lcl -- Nested stuff; changes as we go into
130 -- TcGblEnv describes the top-level of the module at the
131 -- point at which the typechecker is finished work.
132 -- It is this structure that is handed on to the desugarer
136 tcg_mod :: Module, -- Module being compiled
137 tcg_src :: HscSource, -- What kind of module
138 -- (regular Haskell, hs-boot, ext-core)
140 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
141 tcg_default :: Maybe [Type], -- Types used for defaulting
142 -- Nothing => no 'default' decl
144 tcg_fix_env :: FixityEnv, -- Just for things in this module
145 tcg_field_env :: RecFieldEnv, -- Just for things in this module
147 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
148 -- All TyCons and Classes (for this module) end up in here right away,
149 -- along with their derived constructors, selectors.
151 -- (Ids defined in this module start in the local envt,
152 -- though they move to the global envt during zonking)
154 tcg_type_env_var :: TcRef TypeEnv,
155 -- Used only to initialise the interface-file
156 -- typechecker in initIfaceTcRn, so that it can see stuff
157 -- bound in this module when dealing with hi-boot recursions
158 -- Updated at intervals (e.g. after dealing with types and classes)
160 tcg_inst_env :: InstEnv, -- Instance envt for *home-package*
161 -- modules; Includes the dfuns in
163 tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
165 -- Now a bunch of things about this module that are simply
166 -- accumulated, but never consulted until the end.
167 -- Nevertheless, it's convenient to accumulate them along
168 -- with the rest of the info from this module.
169 tcg_exports :: [AvailInfo], -- What is exported
170 tcg_imports :: ImportAvails, -- Information about what was imported
171 -- from where, including things bound
174 tcg_dus :: DefUses, -- What is defined in this module and what is used.
175 -- The latter is used to generate
176 -- (a) version tracking; no need to recompile if these
177 -- things have not changed version stamp
178 -- (b) unused-import info
180 tcg_keep :: TcRef NameSet, -- Locally-defined top-level names to keep alive
181 -- "Keep alive" means give them an Exported flag, so
182 -- that the simplifier does not discard them as dead
183 -- code, and so that they are exposed in the interface file
184 -- (but not to export to the user).
186 -- Some things, like dict-fun Ids and default-method Ids are
187 -- "born" with the Exported flag on, for exactly the above reason,
188 -- but some we only discover as we go. Specifically:
189 -- * The to/from functions for generic data types
190 -- * Top-level variables appearing free in the RHS of an orphan rule
191 -- * Top-level variables appearing free in a TH bracket
193 tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used
194 -- Used to generate version dependencies
195 -- This records usages, rather like tcg_dus, but it has to
196 -- be a mutable variable so it can be augmented
197 -- when we look up an instance. These uses of dfuns are
198 -- rather like the free variables of the program, but
199 -- are implicit instead of explicit.
201 tcg_th_used :: TcRef Bool, -- True <=> Template Haskell syntax used
202 -- We need this so that we can generate a dependency on the
203 -- Template Haskell package, becuase the desugarer is going to
204 -- emit loads of references to TH symbols. It's rather like
205 -- tcg_inst_uses; the reference is implicit rather than explicit,
206 -- so we have to zap a mutable variable.
208 tcg_dfun_n :: TcRef Int, -- Allows us to number off the names of DFuns
209 -- It's convenient to allocate an External Name for a DFun, with
210 -- a permanently-fixed unique, just like other top-level functions
211 -- defined in this module. But that means we need a canonical
212 -- occurrence name, distinct from all other dfuns in this module,
213 -- and this name supply serves that purpose (df1, df2, etc).
215 -- The next fields accumulate the payload of the module
216 -- The binds, rules and foreign-decl fiels are collected
217 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
219 -- The next fields accumulate the payload of the
220 -- module The binds, rules and foreign-decl fiels are
221 -- collected initially in un-zonked form and are
222 -- finally zonked in tcRnSrcDecls
224 tcg_rn_imports :: Maybe [LImportDecl Name],
225 tcg_rn_exports :: Maybe [Located (IE Name)],
226 tcg_rn_decls :: Maybe (HsGroup Name), -- renamed decls, maybe
227 -- Nothing <=> Don't retain renamed decls
229 tcg_binds :: LHsBinds Id, -- Value bindings in this module
230 tcg_deprecs :: Deprecations, -- ...Deprecations
231 tcg_insts :: [Instance], -- ...Instances
232 tcg_fam_insts :: [FamInst], -- ...Family instances
233 tcg_rules :: [LRuleDecl Id], -- ...Rules
234 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
236 tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
237 tcg_hmi :: HaddockModInfo Name, -- Haddock module information
238 tcg_hpc :: AnyHpcUsage -- True if any part of the prog uses hpc instrumentation.
241 type RecFieldEnv = NameEnv [Name] -- Maps a constructor name *in this module*
242 -- to the fields for that constructor
243 -- This is used when dealing with ".." notation in record
244 -- construction and pattern matching.
245 -- The FieldEnv deals *only* with constructors defined in
246 -- *thie* module. For imported modules, we get the same info
250 %************************************************************************
252 The interface environments
253 Used when dealing with IfaceDecls
255 %************************************************************************
260 -- The type environment for the module being compiled,
261 -- in case the interface refers back to it via a reference that
262 -- was originally a hi-boot file.
263 -- We need the module name so we can test when it's appropriate
264 -- to look in this env.
265 if_rec_types :: Maybe (Module, IfG TypeEnv)
266 -- Allows a read effect, so it can be in a mutable
267 -- variable; c.f. handling the external package type env
268 -- Nothing => interactive stuff, no loops possible
273 -- The module for the current IfaceDecl
274 -- So if we see f = \x -> x
275 -- it means M.f = \x -> x, where M is the if_mod
278 -- The field is used only for error reporting
279 -- if (say) there's a Lint error in it
281 -- Where the interface came from:
282 -- .hi file, or GHCi state, or ext core
283 -- plus which bit is currently being examined
285 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
286 if_id_env :: UniqFM Id -- Nested id binding
291 %************************************************************************
293 The local typechecker environment
295 %************************************************************************
297 The Global-Env/Local-Env story
298 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
299 During type checking, we keep in the tcg_type_env
300 * All types and classes
301 * All Ids derived from types and classes (constructors, selectors)
303 At the end of type checking, we zonk the local bindings,
304 and as we do so we add to the tcg_type_env
305 * Locally defined top-level Ids
307 Why? Because they are now Ids not TcIds. This final GlobalEnv is
308 a) fed back (via the knot) to typechecking the
309 unfoldings of interface signatures
310 b) used in the ModDetails of this module
313 data TcLclEnv -- Changes as we move inside an expression
314 -- Discarded after typecheck/rename; not passed on to desugarer
316 tcl_loc :: SrcSpan, -- Source span
317 tcl_ctxt :: ErrCtxt, -- Error context
318 tcl_errs :: TcRef Messages, -- Place to accumulate errors
320 tcl_th_ctxt :: ThStage, -- Template Haskell context
321 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
323 tcl_rdr :: LocalRdrEnv, -- Local name envt
324 -- Maintained during renaming, of course, but also during
325 -- type checking, solely so that when renaming a Template-Haskell
326 -- splice we have the right environment for the renamer.
328 -- Does *not* include global name envt; may shadow it
329 -- Includes both ordinary variables and type variables;
330 -- they are kept distinct because tyvar have a different
331 -- occurrence contructor (Name.TvOcc)
332 -- We still need the unsullied global name env so that
333 -- we can look up record field names
335 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
336 -- defined in this module
338 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
339 -- Namely, the in-scope TyVars bound in tcl_env,
340 -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
341 -- Why mutable? see notes with tcGetGlobalTyVars
343 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
347 {- Note [Given Insts]
349 Because of GADTs, we have to pass inwards the Insts provided by type signatures
350 and existential contexts. Consider
351 data T a where { T1 :: b -> b -> T [b] }
352 f :: Eq a => T a -> Bool
353 f (T1 x y) = [x]==[y]
355 The constructor T1 binds an existential variable 'b', and we need Eq [b].
356 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
361 ---------------------------
362 -- Template Haskell levels
363 ---------------------------
366 -- Indicates how many levels of brackets we are inside
368 -- Incremented when going inside a bracket,
369 -- decremented when going inside a splice
370 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
371 -- original "Template meta-programming for Haskell" paper
373 impLevel, topLevel :: ThLevel
374 topLevel = 1 -- Things defined at top level of this module
375 impLevel = 0 -- Imported things; they can be used inside a top level splice
379 -- g1 = $(map ...) is OK
380 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
384 = Comp -- Ordinary compiling, at level topLevel
385 | Splice ThLevel -- Inside a splice
386 | Brack ThLevel -- Inside brackets;
387 (TcRef [PendingSplice]) -- accumulate pending splices here
388 (TcRef LIE) -- and type constraints here
389 topStage, topSpliceStage :: ThStage
391 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
393 ---------------------------
394 -- Arrow-notation context
395 ---------------------------
398 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
399 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
404 Here, x is not in scope in e1, but it is in scope in e2. This can get
408 proc y -> (proc z -> e1) -< e2
410 Here, x and z are in scope in e1, but y is not. We implement this by
411 recording the environment when passing a proc (using newArrowScope),
412 and returning to that (using escapeArrowScope) on the left of -< and the
418 | ArrowCtxt (Env TcGblEnv TcLclEnv)
420 -- Record the current environment (outside a proc)
421 newArrowScope :: TcM a -> TcM a
424 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
426 -- Return to the stored environment (from the enclosing proc)
427 escapeArrowScope :: TcM a -> TcM a
429 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
431 ArrowCtxt env' -> env'
433 ---------------------------
435 ---------------------------
438 = AGlobal TyThing -- Used only in the return type of a lookup
440 | ATcId { -- Ids defined in this module; may not be fully zonked
442 tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
443 -- Nothing <=> Do not apply a GADT type refinement
444 -- I am wobbly, or have no free
446 -- Just co <=> Apply any type refinement to me,
447 -- and record it in the coercion
448 tct_type :: TcType, -- Type of (coercion applied to id)
449 tct_level :: ThLevel }
451 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
452 -- is currently refined. We only need the Name
453 -- for error-message purposes
455 | AThing TcKind -- Used temporarily, during kind checking, for the
456 -- tycons and clases in this recursive group
458 data RefinementVisibility
459 = Unrefineable -- Do not apply a GADT refinement
460 -- I have no free variables
462 | Rigid HsWrapper -- Apply any refinement to me
463 -- and record it in the coercion
465 | Wobbly -- Do not apply a GADT refinement
468 | WobblyInvisible -- Wobbly type, not available inside current
471 instance Outputable TcTyThing where -- Debugging only
472 ppr (AGlobal g) = pprTyThing g
473 ppr elt@(ATcId {}) = text "Identifier" <>
474 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
475 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
476 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
477 ppr (AThing k) = text "AThing" <+> ppr k
479 pprTcTyThingCategory :: TcTyThing -> SDoc
480 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
481 pprTcTyThingCategory (ATyVar {}) = ptext SLIT("Type variable")
482 pprTcTyThingCategory (ATcId {}) = ptext SLIT("Local identifier")
483 pprTcTyThingCategory (AThing {}) = ptext SLIT("Kinded thing")
485 instance Outputable RefinementVisibility where
486 ppr Unrefineable = ptext SLIT("unrefineable")
487 ppr (Rigid co) = ptext SLIT("rigid") <+> ppr co
488 ppr Wobbly = ptext SLIT("wobbly")
489 ppr WobblyInvisible = ptext SLIT("wobbly-invisible")
494 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
495 -- Innermost first. Monadic so that we have a chance
496 -- to deal with bound type variables just before error
497 -- message construction
501 %************************************************************************
503 Operations over ImportAvails
505 %************************************************************************
507 ImportAvails summarises what was imported from where, irrespective
508 of whether the imported things are actually used or not
509 It is used * when processing the export list
510 * when constructing usage info for the inteface file
511 * to identify the list of directly imported modules
512 for initialisation purposes and
513 for optimsed overlap checking of family instances
514 * when figuring out what things are really unused
519 imp_mods :: ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)]),
520 -- Domain is all directly-imported modules
521 -- The ModuleName is what the module was imported as, e.g. in
525 -- True => import was "import Foo ()"
526 -- False => import was some other form
528 -- We need the Module in the range because we can't get
529 -- the keys of a ModuleEnv
531 -- (a) to help construct the usage information in
532 -- the interface file; if we import somethign we
533 -- need to recompile if the export version changes
534 -- (b) to specify what child modules to initialise
536 -- We need a full ModuleEnv rather than a ModuleNameEnv
537 -- here, because we might be importing modules of the
538 -- same name from different packages. (currently not the case,
539 -- but might be in the future).
541 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
542 -- Home-package modules needed by the module being compiled
544 -- It doesn't matter whether any of these dependencies
545 -- are actually *used* when compiling the module; they
546 -- are listed if they are below it at all. For
547 -- example, suppose M imports A which imports X. Then
548 -- compiling M might not need to consult X.hi, but X
549 -- is still listed in M's dependencies.
551 imp_dep_pkgs :: [PackageId],
552 -- Packages needed by the module being compiled, whether
553 -- directly, or via other modules in this package, or via
554 -- modules imported from other packages.
556 imp_orphs :: [Module],
557 -- Orphan modules below us in the import tree (and maybe
558 -- including us for imported modules)
560 imp_finsts :: [Module]
561 -- Family instance modules below us in the import tree (and
562 -- maybe including us for imported modules)
565 mkModDeps :: [(ModuleName, IsBootInterface)]
566 -> ModuleNameEnv (ModuleName, IsBootInterface)
567 mkModDeps deps = foldl add emptyUFM deps
569 add env elt@(m,_) = addToUFM env m elt
571 emptyImportAvails :: ImportAvails
572 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
573 imp_dep_mods = emptyUFM,
578 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
580 (ImportAvails { imp_mods = mods1,
581 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
582 imp_orphs = orphs1, imp_finsts = finsts1 })
583 (ImportAvails { imp_mods = mods2,
584 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
585 imp_orphs = orphs2, imp_finsts = finsts2 })
586 = ImportAvails { imp_mods = plusModuleEnv_C plus_mod mods1 mods2,
587 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
588 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
589 imp_orphs = orphs1 `unionLists` orphs2,
590 imp_finsts = finsts1 `unionLists` finsts2 }
592 plus_mod (m1, xs1) (_, xs2) = (m1, xs1 ++ xs2)
593 plus_mod_dep (m1, boot1) (m2, boot2)
594 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
595 -- Check mod-names match
596 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
599 %************************************************************************
601 \subsection{Where from}
603 %************************************************************************
605 The @WhereFrom@ type controls where the renamer looks for an interface file
609 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
610 | ImportBySystem -- Non user import.
612 instance Outputable WhereFrom where
613 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
615 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
619 %************************************************************************
621 \subsection[Inst-types]{@Inst@ types}
623 v%************************************************************************
625 An @Inst@ is either a dictionary, an instance of an overloaded
626 literal, or an instance of an overloaded value. We call the latter a
627 ``method'' even though it may not correspond to a class operation.
628 For example, we might have an instance of the @double@ function at
629 type Int, represented by
631 Method 34 doubleId [Int] origin
633 In addition to the basic Haskell variants of 'Inst's, they can now also
634 represent implication constraints 'forall tvs. given => wanted'
635 and equality constraints 'co :: ty1 ~ ty2'.
637 NB: Equalities occur in two flavours:
639 (1) Dict {tci_pred = EqPred ty1 ty2}
640 (2) EqInst {tci_left = ty1, tci_right = ty2, tci_co = coe}
642 The former arises from equalities in contexts, whereas the latter is used
643 whenever the type checker introduces an equality (e.g., during deferring
646 I am not convinced that this duplication is necessary or useful! -=chak
652 tci_pred :: TcPredType,
656 | ImplicInst { -- An implication constraint
657 -- forall tvs. given => wanted
659 tci_tyvars :: [TcTyVar], -- Quantified type variables
660 tci_given :: [Inst], -- Only Dicts and EqInsts
661 -- (no Methods, LitInsts, ImplicInsts)
662 tci_wanted :: [Inst], -- Only Dicts, EqInst, and ImplicInsts
663 -- (no Methods or LitInsts)
667 -- NB: the tci_given are not necessarily rigid
670 tci_id :: TcId, -- The Id for the Inst
672 tci_oid :: TcId, -- The overloaded function
673 -- This function will be a global, local, or ClassOpId;
674 -- inside instance decls (only) it can also be an InstId!
675 -- The id needn't be completely polymorphic.
676 -- You'll probably find its name (for documentation purposes)
677 -- inside the InstOrigin
679 tci_tys :: [TcType], -- The types to which its polymorphic tyvars
680 -- should be instantiated.
681 -- These types must saturate the Id's foralls.
683 tci_theta :: TcThetaType,
684 -- The (types of the) dictionaries to which the function
685 -- must be applied to get the method
689 -- INVARIANT 1: in (Method m f tys theta tau loc)
690 -- type of m = type of (f tys dicts(from theta))
692 -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
693 -- Reason: two methods are considered equal if the
694 -- base Id matches, and the instantiating types
695 -- match. The TcThetaType should then match too.
696 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
700 tci_lit :: HsOverLit Name, -- The literal from the occurrence site
701 -- INVARIANT: never a rebindable-syntax literal
702 -- Reason: tcSyntaxName does unification, and we
703 -- don't want to deal with that during tcSimplify,
704 -- when resolving LitInsts
706 tci_ty :: TcType, -- The type at which the literal is used
710 | EqInst { -- delayed unification of the form
712 tci_left :: TcType, -- ty1 -- both types are...
713 tci_right :: TcType, -- ty2 -- ...free of boxes
714 tci_co :: Either -- co
715 TcTyVar -- - a wanted equation, with a hole, to be
716 -- filled with a witness for the equality;
717 -- for equation arising from deferring
718 -- unification, 'ty1' is the actual and
719 -- 'ty2' the expected type
720 Coercion, -- - a given equation, with a coercion
721 -- witnessing the equality;
722 -- a coercion that originates from a
723 -- signature or a GADT is a CoVar, but
724 -- after normalisation of coercions, they
725 -- can be arbitrary Coercions involving
726 -- constructors and pseudo-constructors
727 -- like sym and trans.
730 tci_name :: Name -- Debugging help only: this makes it easier to
731 -- follow where a constraint is used in a morass
732 -- of trace messages! Unlike other Insts, it has
733 -- no semantic significance whatsoever.
737 @Insts@ are ordered by their class/type info, rather than by their
738 unique. This allows the context-reduction mechanism to use standard finite
739 maps to do their stuff. It's horrible that this code is here, rather
740 than with the Avails handling stuff in TcSimplify
743 instance Ord Inst where
746 instance Eq Inst where
747 (==) i1 i2 = case i1 `cmpInst` i2 of
751 cmpInst d1@(Dict {}) d2@(Dict {}) = tci_pred d1 `tcCmpPred` tci_pred d2
752 cmpInst (Dict {}) other = LT
754 cmpInst (Method {}) (Dict {}) = GT
755 cmpInst m1@(Method {}) m2@(Method {}) = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
756 (tci_tys m1 `tcCmpTypes` tci_tys m2)
757 cmpInst (Method {}) other = LT
759 cmpInst (LitInst {}) (Dict {}) = GT
760 cmpInst (LitInst {}) (Method {}) = GT
761 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
762 (tci_ty l1 `tcCmpType` tci_ty l2)
763 cmpInst (LitInst {}) other = LT
765 -- Implication constraints are compared by *name*
766 -- not by type; that is, we make no attempt to do CSE on them
767 cmpInst (ImplicInst {}) (Dict {}) = GT
768 cmpInst (ImplicInst {}) (Method {}) = GT
769 cmpInst (ImplicInst {}) (LitInst {}) = GT
770 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
771 cmpInst (ImplicInst {}) other = LT
773 -- same for Equality constraints
774 cmpInst (EqInst {}) (Dict {}) = GT
775 cmpInst (EqInst {}) (Method {}) = GT
776 cmpInst (EqInst {}) (LitInst {}) = GT
777 cmpInst (EqInst {}) (ImplicInst {}) = GT
778 cmpInst i1@(EqInst {}) i2@(EqInst {}) = tci_name i1 `compare` tci_name i2
782 %************************************************************************
784 \subsection[Inst-collections]{LIE: a collection of Insts}
786 %************************************************************************
789 -- FIXME: Rename this. It clashes with (Located (IE ...))
792 isEmptyLIE = isEmptyBag
794 unitLIE inst = unitBag inst
795 mkLIE insts = listToBag insts
796 plusLIE lie1 lie2 = lie1 `unionBags` lie2
797 plusLIEs lies = unionManyBags lies
798 lieToList = bagToList
799 listToLIE = listToBag
801 consLIE inst lie = lie `snocBag` inst
802 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
803 -- to ensure that we tend to report the *leftmost* type-constraint error
806 -- we'd like to complain about the '1', not the '3'.
808 -- "Half-hearted" because the rest of the type checker makes no great
809 -- claims for retaining order in the constraint set. Still, this
810 -- seems to improve matters slightly. Exampes: mdofail001, tcfail015
814 %************************************************************************
816 \subsection[Inst-origin]{The @InstOrigin@ type}
818 %************************************************************************
820 The @InstOrigin@ type gives information about where a dictionary came from.
821 This is important for decent error message reporting because dictionaries
822 don't appear in the original source code. Doubtless this type will evolve...
824 It appears in TcMonad because there are a couple of error-message-generation
825 functions that deal with it.
828 -------------------------------------------
829 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
831 instLoc :: Inst -> InstLoc
832 instLoc inst = tci_loc inst
834 instSpan :: Inst -> SrcSpan
835 instSpan wanted = instLocSpan (instLoc wanted)
837 instLocSpan :: InstLoc -> SrcSpan
838 instLocSpan (InstLoc _ s _) = s
840 instLocOrigin :: InstLoc -> InstOrigin
841 instLocOrigin (InstLoc o _ _) = o
843 pprInstArising :: Inst -> SDoc
844 pprInstArising loc = ptext SLIT("arising from") <+> pprInstLoc (tci_loc loc)
846 pprInstLoc :: InstLoc -> SDoc
847 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
849 -------------------------------------------
851 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
852 -- Places that bind type variables and introduce
853 -- available constraints
855 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
857 -------------------------------------------------------
858 -- The rest are all occurrences: Insts that are 'wanted'
859 -------------------------------------------------------
860 | OccurrenceOf Name -- Occurrence of an overloaded identifier
861 | SpecPragOrigin Name -- Specialisation pragma for identifier
863 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
865 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
866 | NegateOrigin -- Occurrence of syntactic negation
868 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
869 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
870 | TupleOrigin -- (..,..)
872 | InstSigOrigin -- A dict occurrence arising from instantiating
873 -- a polymorphic type during a subsumption check
875 | ExprSigOrigin -- e :: ty
878 | InstScOrigin -- Typechecking superclasses of an instance declaration
879 | DerivOrigin -- Typechecking deriving
880 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
881 | DefaultOrigin -- Typechecking a default decl
882 | DoOrigin -- Arising from a do expression
883 | ProcOrigin -- Arising from a proc expression
884 | ImplicOrigin SDoc -- An implication constraint
885 | EqOrigin -- A type equality
887 instance Outputable InstOrigin where
888 ppr (OccurrenceOf name) = hsep [ptext SLIT("a use of"), quotes (ppr name)]
889 ppr (SpecPragOrigin name) = hsep [ptext SLIT("a specialisation pragma for"), quotes (ppr name)]
890 ppr (IPOccOrigin name) = hsep [ptext SLIT("a use of implicit parameter"), quotes (ppr name)]
891 ppr (IPBindOrigin name) = hsep [ptext SLIT("a binding for implicit parameter"), quotes (ppr name)]
892 ppr RecordUpdOrigin = ptext SLIT("a record update")
893 ppr ExprSigOrigin = ptext SLIT("an expression type signature")
894 ppr ViewPatOrigin = ptext SLIT("a view pattern")
895 ppr (LiteralOrigin lit) = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
896 ppr (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
897 ppr (PArrSeqOrigin seq) = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
898 ppr TupleOrigin = ptext SLIT("a tuple")
899 ppr NegateOrigin = ptext SLIT("a use of syntactic negation")
900 ppr InstScOrigin = ptext SLIT("the superclasses of an instance declaration")
901 ppr DerivOrigin = ptext SLIT("the 'deriving' clause of a data type declaration")
902 ppr StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
903 ppr DefaultOrigin = ptext SLIT("a 'default' declaration")
904 ppr DoOrigin = ptext SLIT("a do statement")
905 ppr ProcOrigin = ptext SLIT("a proc expression")
906 ppr (ImplicOrigin doc) = doc
907 ppr (SigOrigin info) = pprSkolInfo info
908 ppr EqOrigin = ptext SLIT("a type equality")