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(..),
17 ImportAvails(..), emptyImportAvails, plusImportAvails,
18 WhereFrom(..), mkModDeps,
21 TcTyThing(..), pprTcTyThingCategory, RefinementVisibility(..),
24 ThStage(..), topStage, topSpliceStage,
25 ThLevel, impLevel, topLevel,
28 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
31 Inst(..), InstOrigin(..), InstLoc(..),
32 pprInstLoc, pprInstArising, instLocSpan, instLocOrigin,
33 LIE, emptyLIE, unitLIE, plusLIE, consLIE, instLoc, instSpan,
34 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
37 TcId, TcIdSet, TcDictBinds,
41 #include "HsVersions.h"
43 import HsSyn hiding (LIE)
77 %************************************************************************
79 Standard monad definition for TcRn
80 All the combinators for the monad can be found in TcRnMonad
82 %************************************************************************
84 The monad itself has to be defined here, because it is mentioned by ErrCtxt
87 type TcRef a = IORef a
88 type TcId = Id -- Type may be a TcType
90 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
92 type TcRnIf a b c = IOEnv (Env a b) c
93 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
95 type IfG a = IfM () a -- Top level
96 type IfL a = IfM IfLclEnv a -- Nested
97 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
98 type RnM a = TcRn a -- Historical
99 type TcM a = TcRn a -- Historical
103 %************************************************************************
105 The main environment types
107 %************************************************************************
110 data Env gbl lcl -- Changes as we move into an expression
112 env_top :: HscEnv, -- Top-level stuff that never changes
113 -- Includes all info about imported things
115 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
116 -- Unique supply for local varibles
118 env_gbl :: gbl, -- Info about things defined at the top level
119 -- of the module being compiled
121 env_lcl :: lcl -- Nested stuff; changes as we go into
124 -- TcGblEnv describes the top-level of the module at the
125 -- point at which the typechecker is finished work.
126 -- It is this structure that is handed on to the desugarer
130 tcg_mod :: Module, -- Module being compiled
131 tcg_src :: HscSource, -- What kind of module
132 -- (regular Haskell, hs-boot, ext-core)
134 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
135 tcg_default :: Maybe [Type], -- Types used for defaulting
136 -- Nothing => no 'default' decl
138 tcg_fix_env :: FixityEnv, -- Just for things in this module
139 tcg_field_env :: RecFieldEnv, -- Just for things in this module
141 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
142 -- All TyCons and Classes (for this module) end up in here right away,
143 -- along with their derived constructors, selectors.
145 -- (Ids defined in this module start in the local envt,
146 -- though they move to the global envt during zonking)
148 tcg_type_env_var :: TcRef TypeEnv,
149 -- Used only to initialise the interface-file
150 -- typechecker in initIfaceTcRn, so that it can see stuff
151 -- bound in this module when dealing with hi-boot recursions
152 -- Updated at intervals (e.g. after dealing with types and classes)
154 tcg_inst_env :: InstEnv, -- Instance envt for *home-package*
155 -- modules; Includes the dfuns in
157 tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
159 -- Now a bunch of things about this module that are simply
160 -- accumulated, but never consulted until the end.
161 -- Nevertheless, it's convenient to accumulate them along
162 -- with the rest of the info from this module.
163 tcg_exports :: [AvailInfo], -- What is exported
164 tcg_imports :: ImportAvails, -- Information about what was imported
165 -- from where, including things bound
168 tcg_dus :: DefUses, -- What is defined in this module and what is used.
169 -- The latter is used to generate
170 -- (a) version tracking; no need to recompile if these
171 -- things have not changed version stamp
172 -- (b) unused-import info
174 tcg_keep :: TcRef NameSet, -- Locally-defined top-level names to keep alive
175 -- "Keep alive" means give them an Exported flag, so
176 -- that the simplifier does not discard them as dead
177 -- code, and so that they are exposed in the interface file
178 -- (but not to export to the user).
180 -- Some things, like dict-fun Ids and default-method Ids are
181 -- "born" with the Exported flag on, for exactly the above reason,
182 -- but some we only discover as we go. Specifically:
183 -- * The to/from functions for generic data types
184 -- * Top-level variables appearing free in the RHS of an orphan rule
185 -- * Top-level variables appearing free in a TH bracket
187 tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used
188 -- Used to generate version dependencies
189 -- This records usages, rather like tcg_dus, but it has to
190 -- be a mutable variable so it can be augmented
191 -- when we look up an instance. These uses of dfuns are
192 -- rather like the free variables of the program, but
193 -- are implicit instead of explicit.
195 tcg_th_used :: TcRef Bool, -- True <=> Template Haskell syntax used
196 -- We need this so that we can generate a dependency on the
197 -- Template Haskell package, becuase the desugarer is going to
198 -- emit loads of references to TH symbols. It's rather like
199 -- tcg_inst_uses; the reference is implicit rather than explicit,
200 -- so we have to zap a mutable variable.
202 tcg_dfun_n :: TcRef Int, -- Allows us to number off the names of DFuns
203 -- It's convenient to allocate an External Name for a DFun, with
204 -- a permanently-fixed unique, just like other top-level functions
205 -- defined in this module. But that means we need a canonical
206 -- occurrence name, distinct from all other dfuns in this module,
207 -- and this name supply serves that purpose (df1, df2, etc).
209 -- The next fields accumulate the payload of the module
210 -- The binds, rules and foreign-decl fiels are collected
211 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
213 -- The next fields accumulate the payload of the
214 -- module The binds, rules and foreign-decl fiels are
215 -- collected initially in un-zonked form and are
216 -- finally zonked in tcRnSrcDecls
218 tcg_rn_imports :: Maybe [LImportDecl Name],
219 tcg_rn_exports :: Maybe [Located (IE Name)],
220 tcg_rn_decls :: Maybe (HsGroup Name), -- renamed decls, maybe
221 -- Nothing <=> Don't retain renamed decls
223 tcg_binds :: LHsBinds Id, -- Value bindings in this module
224 tcg_deprecs :: Deprecations, -- ...Deprecations
225 tcg_insts :: [Instance], -- ...Instances
226 tcg_fam_insts :: [FamInst], -- ...Family instances
227 tcg_rules :: [LRuleDecl Id], -- ...Rules
228 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
230 tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
231 tcg_hmi :: HaddockModInfo Name, -- Haddock module information
232 tcg_hpc :: AnyHpcUsage -- True if any part of the prog uses hpc instrumentation.
235 type RecFieldEnv = NameEnv [Name] -- Maps a constructor name *in this module*
236 -- to the fields for that constructor
237 -- This is used when dealing with ".." notation in record
238 -- construction and pattern matching.
239 -- The FieldEnv deals *only* with constructors defined in
240 -- *thie* module. For imported modules, we get the same info
244 %************************************************************************
246 The interface environments
247 Used when dealing with IfaceDecls
249 %************************************************************************
254 -- The type environment for the module being compiled,
255 -- in case the interface refers back to it via a reference that
256 -- was originally a hi-boot file.
257 -- We need the module name so we can test when it's appropriate
258 -- to look in this env.
259 if_rec_types :: Maybe (Module, IfG TypeEnv)
260 -- Allows a read effect, so it can be in a mutable
261 -- variable; c.f. handling the external package type env
262 -- Nothing => interactive stuff, no loops possible
267 -- The module for the current IfaceDecl
268 -- So if we see f = \x -> x
269 -- it means M.f = \x -> x, where M is the if_mod
272 -- The field is used only for error reporting
273 -- if (say) there's a Lint error in it
275 -- Where the interface came from:
276 -- .hi file, or GHCi state, or ext core
277 -- plus which bit is currently being examined
279 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
280 if_id_env :: UniqFM Id -- Nested id binding
285 %************************************************************************
287 The local typechecker environment
289 %************************************************************************
291 The Global-Env/Local-Env story
292 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
293 During type checking, we keep in the tcg_type_env
294 * All types and classes
295 * All Ids derived from types and classes (constructors, selectors)
297 At the end of type checking, we zonk the local bindings,
298 and as we do so we add to the tcg_type_env
299 * Locally defined top-level Ids
301 Why? Because they are now Ids not TcIds. This final GlobalEnv is
302 a) fed back (via the knot) to typechecking the
303 unfoldings of interface signatures
304 b) used in the ModDetails of this module
307 data TcLclEnv -- Changes as we move inside an expression
308 -- Discarded after typecheck/rename; not passed on to desugarer
310 tcl_loc :: SrcSpan, -- Source span
311 tcl_ctxt :: ErrCtxt, -- Error context
312 tcl_errs :: TcRef Messages, -- Place to accumulate errors
314 tcl_th_ctxt :: ThStage, -- Template Haskell context
315 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
317 tcl_rdr :: LocalRdrEnv, -- Local name envt
318 -- Maintained during renaming, of course, but also during
319 -- type checking, solely so that when renaming a Template-Haskell
320 -- splice we have the right environment for the renamer.
322 -- Does *not* include global name envt; may shadow it
323 -- Includes both ordinary variables and type variables;
324 -- they are kept distinct because tyvar have a different
325 -- occurrence contructor (Name.TvOcc)
326 -- We still need the unsullied global name env so that
327 -- we can look up record field names
329 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
330 -- defined in this module
332 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
333 -- Namely, the in-scope TyVars bound in tcl_env,
334 -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
335 -- Why mutable? see notes with tcGetGlobalTyVars
337 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
341 {- Note [Given Insts]
343 Because of GADTs, we have to pass inwards the Insts provided by type signatures
344 and existential contexts. Consider
345 data T a where { T1 :: b -> b -> T [b] }
346 f :: Eq a => T a -> Bool
347 f (T1 x y) = [x]==[y]
349 The constructor T1 binds an existential variable 'b', and we need Eq [b].
350 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
355 ---------------------------
356 -- Template Haskell levels
357 ---------------------------
360 -- Indicates how many levels of brackets we are inside
362 -- Incremented when going inside a bracket,
363 -- decremented when going inside a splice
364 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
365 -- original "Template meta-programmign for Haskell" paper
367 impLevel, topLevel :: ThLevel
368 topLevel = 1 -- Things defined at top level of this module
369 impLevel = 0 -- Imported things; they can be used inside a top level splice
373 -- g1 = $(map ...) is OK
374 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
378 = Comp -- Ordinary compiling, at level topLevel
379 | Splice ThLevel -- Inside a splice
380 | Brack ThLevel -- Inside brackets;
381 (TcRef [PendingSplice]) -- accumulate pending splices here
382 (TcRef LIE) -- and type constraints here
383 topStage, topSpliceStage :: ThStage
385 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
387 ---------------------------
388 -- Arrow-notation context
389 ---------------------------
392 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
393 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
398 Here, x is not in scope in e1, but it is in scope in e2. This can get
402 proc y -> (proc z -> e1) -< e2
404 Here, x and z are in scope in e1, but y is not. We implement this by
405 recording the environment when passing a proc (using newArrowScope),
406 and returning to that (using escapeArrowScope) on the left of -< and the
412 | ArrowCtxt (Env TcGblEnv TcLclEnv)
414 -- Record the current environment (outside a proc)
415 newArrowScope :: TcM a -> TcM a
418 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
420 -- Return to the stored environment (from the enclosing proc)
421 escapeArrowScope :: TcM a -> TcM a
423 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
425 ArrowCtxt env' -> env'
427 ---------------------------
429 ---------------------------
432 = AGlobal TyThing -- Used only in the return type of a lookup
434 | ATcId { -- Ids defined in this module; may not be fully zonked
436 tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
437 -- Nothing <=> Do not apply a GADT type refinement
438 -- I am wobbly, or have no free
440 -- Just co <=> Apply any type refinement to me,
441 -- and record it in the coercion
442 tct_type :: TcType, -- Type of (coercion applied to id)
443 tct_level :: ThLevel }
445 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
446 -- is currently refined. We only need the Name
447 -- for error-message purposes
449 | AThing TcKind -- Used temporarily, during kind checking, for the
450 -- tycons and clases in this recursive group
452 data RefinementVisibility
453 = Unrefineable -- Do not apply a GADT refinement
454 -- I have no free variables
456 | Rigid HsWrapper -- Apply any refinement to me
457 -- and record it in the coercion
459 | Wobbly -- Do not apply a GADT refinement
462 | WobblyInvisible -- Wobbly type, not available inside current
465 instance Outputable TcTyThing where -- Debugging only
466 ppr (AGlobal g) = ppr g
467 ppr elt@(ATcId {}) = text "Identifier" <>
468 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
469 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
470 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
471 ppr (AThing k) = text "AThing" <+> ppr k
473 pprTcTyThingCategory :: TcTyThing -> SDoc
474 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
475 pprTcTyThingCategory (ATyVar {}) = ptext SLIT("Type variable")
476 pprTcTyThingCategory (ATcId {}) = ptext SLIT("Local identifier")
477 pprTcTyThingCategory (AThing {}) = ptext SLIT("Kinded thing")
479 instance Outputable RefinementVisibility where
480 ppr Unrefineable = ptext SLIT("unrefineable")
481 ppr (Rigid co) = ptext SLIT("rigid") <+> ppr co
482 ppr Wobbly = ptext SLIT("wobbly")
483 ppr WobblyInvisible = ptext SLIT("wobbly-invisible")
488 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
489 -- Innermost first. Monadic so that we have a chance
490 -- to deal with bound type variables just before error
491 -- message construction
495 %************************************************************************
497 Operations over ImportAvails
499 %************************************************************************
501 ImportAvails summarises what was imported from where, irrespective
502 of whether the imported things are actually used or not
503 It is used * when processing the export list
504 * when constructing usage info for the inteface file
505 * to identify the list of directly imported modules
506 for initialisation purposes and
507 for optimsed overlap checking of family instances
508 * when figuring out what things are really unused
513 imp_mods :: ModuleEnv (Module, [(ModuleName, Bool, SrcSpan)]),
514 -- Domain is all directly-imported modules
515 -- The ModuleName is what the module was imported as, e.g. in
519 -- True => import was "import Foo ()"
520 -- False => import was some other form
522 -- We need the Module in the range because we can't get
523 -- the keys of a ModuleEnv
525 -- (a) to help construct the usage information in
526 -- the interface file; if we import somethign we
527 -- need to recompile if the export version changes
528 -- (b) to specify what child modules to initialise
530 -- We need a full ModuleEnv rather than a ModuleNameEnv
531 -- here, because we might be importing modules of the
532 -- same name from different packages. (currently not the case,
533 -- but might be in the future).
535 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
536 -- Home-package modules needed by the module being compiled
538 -- It doesn't matter whether any of these dependencies
539 -- are actually *used* when compiling the module; they
540 -- are listed if they are below it at all. For
541 -- example, suppose M imports A which imports X. Then
542 -- compiling M might not need to consult X.hi, but X
543 -- is still listed in M's dependencies.
545 imp_dep_pkgs :: [PackageId],
546 -- Packages needed by the module being compiled, whether
547 -- directly, or via other modules in this package, or via
548 -- modules imported from other packages.
550 imp_orphs :: [Module],
551 -- Orphan modules below us in the import tree (and maybe
552 -- including us for imported modules)
554 imp_finsts :: [Module]
555 -- Family instance modules below us in the import tree (and
556 -- maybe including us for imported modules)
559 mkModDeps :: [(ModuleName, IsBootInterface)]
560 -> ModuleNameEnv (ModuleName, IsBootInterface)
561 mkModDeps deps = foldl add emptyUFM deps
563 add env elt@(m,_) = addToUFM env m elt
565 emptyImportAvails :: ImportAvails
566 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
567 imp_dep_mods = emptyUFM,
572 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
574 (ImportAvails { imp_mods = mods1,
575 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
576 imp_orphs = orphs1, imp_finsts = finsts1 })
577 (ImportAvails { imp_mods = mods2,
578 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
579 imp_orphs = orphs2, imp_finsts = finsts2 })
580 = ImportAvails { imp_mods = plusModuleEnv_C plus_mod mods1 mods2,
581 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
582 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
583 imp_orphs = orphs1 `unionLists` orphs2,
584 imp_finsts = finsts1 `unionLists` finsts2 }
586 plus_mod (m1, xs1) (_, xs2) = (m1, xs1 ++ xs2)
587 plus_mod_dep (m1, boot1) (m2, boot2)
588 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
589 -- Check mod-names match
590 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
593 %************************************************************************
595 \subsection{Where from}
597 %************************************************************************
599 The @WhereFrom@ type controls where the renamer looks for an interface file
603 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
604 | ImportBySystem -- Non user import.
606 instance Outputable WhereFrom where
607 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
609 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
613 %************************************************************************
615 \subsection[Inst-types]{@Inst@ types}
617 v%************************************************************************
619 An @Inst@ is either a dictionary, an instance of an overloaded
620 literal, or an instance of an overloaded value. We call the latter a
621 ``method'' even though it may not correspond to a class operation.
622 For example, we might have an instance of the @double@ function at
623 type Int, represented by
625 Method 34 doubleId [Int] origin
627 In addition to the basic Haskell variants of 'Inst's, they can now also
628 represent implication constraints 'forall tvs. (reft, given) => wanted'
629 and equality constraints 'co :: ty1 ~ ty2'.
635 tci_pred :: TcPredType,
639 | ImplicInst { -- An implication constraint
640 -- forall tvs. (reft, given) => wanted
642 tci_tyvars :: [TcTyVar], -- Quantified type variables
643 -- Includes coercion variables
644 -- mentioned in tci_reft
645 tci_reft :: Refinement,
646 tci_given :: [Inst], -- Only Dicts
647 -- (no Methods, LitInsts, ImplicInsts)
648 tci_wanted :: [Inst], -- Only Dicts and ImplicInsts
649 -- (no Methods or LitInsts)
653 -- NB: the tci_given are not necessarily rigid,
654 -- although they will be if the tci_reft is non-trivial
655 -- NB: the tci_reft is already applied to tci_given and tci_wanted
658 tci_id :: TcId, -- The Id for the Inst
660 tci_oid :: TcId, -- The overloaded function
661 -- This function will be a global, local, or ClassOpId;
662 -- inside instance decls (only) it can also be an InstId!
663 -- The id needn't be completely polymorphic.
664 -- You'll probably find its name (for documentation purposes)
665 -- inside the InstOrigin
667 tci_tys :: [TcType], -- The types to which its polymorphic tyvars
668 -- should be instantiated.
669 -- These types must saturate the Id's foralls.
671 tci_theta :: TcThetaType,
672 -- The (types of the) dictionaries to which the function
673 -- must be applied to get the method
677 -- INVARIANT 1: in (Method m f tys theta tau loc)
678 -- type of m = type of (f tys dicts(from theta))
680 -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
681 -- Reason: two methods are considered equal if the
682 -- base Id matches, and the instantiating types
683 -- match. The TcThetaType should then match too.
684 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
688 tci_lit :: HsOverLit Name, -- The literal from the occurrence site
689 -- INVARIANT: never a rebindable-syntax literal
690 -- Reason: tcSyntaxName does unification, and we
691 -- don't want to deal with that during tcSimplify,
692 -- when resolving LitInsts
694 tci_ty :: TcType, -- The type at which the literal is used
698 | EqInst { -- delayed unification of the form
700 tci_left :: TcType, -- ty1
701 tci_right :: TcType, -- ty2
702 tci_co :: Either -- co
703 TcTyVar -- a wanted equation, with a hole, to be
704 -- filled with a witness for the equality
705 -- for equation generated by the
706 -- unifier, 'ty1' is the actual and
707 -- 'ty2' the expected type
708 Coercion, -- a given equation, with a coercion
709 -- witnessing the equality
710 -- a coercion that originates from a
711 -- signature or a GADT is a CoVar, but
712 -- after normalisation of coercions,
713 -- they can be arbitrary Coercions
714 -- involving constructors and
715 -- pseudo-constructors like sym and
719 tci_name :: Name -- Debugging help only: this makes it easier to
720 -- follow where a constraint is used in a morass
721 -- of trace messages! Unlike other Insts, it has
722 -- no semantic significance whatsoever.
726 @Insts@ are ordered by their class/type info, rather than by their
727 unique. This allows the context-reduction mechanism to use standard finite
728 maps to do their stuff. It's horrible that this code is here, rather
729 than with the Avails handling stuff in TcSimplify
732 instance Ord Inst where
735 instance Eq Inst where
736 (==) i1 i2 = case i1 `cmpInst` i2 of
740 cmpInst d1@(Dict {}) d2@(Dict {}) = tci_pred d1 `tcCmpPred` tci_pred d2
741 cmpInst (Dict {}) other = LT
743 cmpInst (Method {}) (Dict {}) = GT
744 cmpInst m1@(Method {}) m2@(Method {}) = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
745 (tci_tys m1 `tcCmpTypes` tci_tys m2)
746 cmpInst (Method {}) other = LT
748 cmpInst (LitInst {}) (Dict {}) = GT
749 cmpInst (LitInst {}) (Method {}) = GT
750 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
751 (tci_ty l1 `tcCmpType` tci_ty l2)
752 cmpInst (LitInst {}) other = LT
754 -- Implication constraints are compared by *name*
755 -- not by type; that is, we make no attempt to do CSE on them
756 cmpInst (ImplicInst {}) (Dict {}) = GT
757 cmpInst (ImplicInst {}) (Method {}) = GT
758 cmpInst (ImplicInst {}) (LitInst {}) = GT
759 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
760 cmpInst (ImplicInst {}) other = LT
762 -- same for Equality constraints
763 cmpInst (EqInst {}) (Dict {}) = GT
764 cmpInst (EqInst {}) (Method {}) = GT
765 cmpInst (EqInst {}) (LitInst {}) = GT
766 cmpInst (EqInst {}) (ImplicInst {}) = GT
767 cmpInst i1@(EqInst {}) i2@(EqInst {}) = tci_name i1 `compare` tci_name i2
771 %************************************************************************
773 \subsection[Inst-collections]{LIE: a collection of Insts}
775 %************************************************************************
778 -- FIXME: Rename this. It clashes with (Located (IE ...))
781 isEmptyLIE = isEmptyBag
783 unitLIE inst = unitBag inst
784 mkLIE insts = listToBag insts
785 plusLIE lie1 lie2 = lie1 `unionBags` lie2
786 plusLIEs lies = unionManyBags lies
787 lieToList = bagToList
788 listToLIE = listToBag
790 consLIE inst lie = lie `snocBag` inst
791 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
792 -- to ensure that we tend to report the *leftmost* type-constraint error
795 -- we'd like to complain about the '1', not the '3'.
797 -- "Half-hearted" because the rest of the type checker makes no great
798 -- claims for retaining order in the constraint set. Still, this
799 -- seems to improve matters slightly. Exampes: mdofail001, tcfail015
803 %************************************************************************
805 \subsection[Inst-origin]{The @InstOrigin@ type}
807 %************************************************************************
809 The @InstOrigin@ type gives information about where a dictionary came from.
810 This is important for decent error message reporting because dictionaries
811 don't appear in the original source code. Doubtless this type will evolve...
813 It appears in TcMonad because there are a couple of error-message-generation
814 functions that deal with it.
817 -------------------------------------------
818 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
820 instLoc :: Inst -> InstLoc
821 instLoc inst = tci_loc inst
823 instSpan :: Inst -> SrcSpan
824 instSpan wanted = instLocSpan (instLoc wanted)
826 instLocSpan :: InstLoc -> SrcSpan
827 instLocSpan (InstLoc _ s _) = s
829 instLocOrigin :: InstLoc -> InstOrigin
830 instLocOrigin (InstLoc o _ _) = o
832 pprInstArising :: Inst -> SDoc
833 pprInstArising loc = ptext SLIT("arising from") <+> pprInstLoc (tci_loc loc)
835 pprInstLoc :: InstLoc -> SDoc
836 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
838 -------------------------------------------
840 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
841 -- Places that bind type variables and introduce
842 -- available constraints
844 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
846 -------------------------------------------------------
847 -- The rest are all occurrences: Insts that are 'wanted'
848 -------------------------------------------------------
849 | OccurrenceOf Name -- Occurrence of an overloaded identifier
851 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
853 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
855 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
856 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
858 | InstSigOrigin -- A dict occurrence arising from instantiating
859 -- a polymorphic type during a subsumption check
862 | InstScOrigin -- Typechecking superclasses of an instance declaration
863 | DerivOrigin -- Typechecking deriving
864 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
865 | DefaultOrigin -- Typechecking a default decl
866 | DoOrigin -- Arising from a do expression
867 | ProcOrigin -- Arising from a proc expression
868 | ImplicOrigin SDoc -- An implication constraint
869 | EqOrigin -- A type equality
871 instance Outputable InstOrigin where
872 ppr (OccurrenceOf name) = hsep [ptext SLIT("a use of"), quotes (ppr name)]
873 ppr (IPOccOrigin name) = hsep [ptext SLIT("a use of implicit parameter"), quotes (ppr name)]
874 ppr (IPBindOrigin name) = hsep [ptext SLIT("a binding for implicit parameter"), quotes (ppr name)]
875 ppr RecordUpdOrigin = ptext SLIT("a record update")
876 ppr (LiteralOrigin lit) = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
877 ppr (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
878 ppr (PArrSeqOrigin seq) = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
879 ppr InstSigOrigin = ptext SLIT("instantiating a type signature")
880 ppr InstScOrigin = ptext SLIT("the superclasses of an instance declaration")
881 ppr DerivOrigin = ptext SLIT("the 'deriving' clause of a data type declaration")
882 ppr StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
883 ppr DefaultOrigin = ptext SLIT("a 'default' declaration")
884 ppr DoOrigin = ptext SLIT("a do statement")
885 ppr ProcOrigin = ptext SLIT("a proc expression")
886 ppr (ImplicOrigin doc) = doc
887 ppr (SigOrigin info) = pprSkolInfo info
888 ppr EqOrigin = ptext SLIT("a type equality")