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, topLevel,
28 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
31 Inst(..), EqInstCo, 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)
76 %************************************************************************
78 Standard monad definition for TcRn
79 All the combinators for the monad can be found in TcRnMonad
81 %************************************************************************
83 The monad itself has to be defined here, because it is mentioned by ErrCtxt
86 type TcRef a = IORef a
87 type TcId = Id -- Type may be a TcType
89 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
91 type TcRnIf a b c = IOEnv (Env a b) c
92 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
94 type IfG a = IfM () a -- Top level
95 type IfL a = IfM IfLclEnv a -- Nested
96 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
97 type RnM a = TcRn a -- Historical
98 type TcM a = TcRn a -- Historical
102 %************************************************************************
104 The main environment types
106 %************************************************************************
109 data Env gbl lcl -- Changes as we move into an expression
111 env_top :: HscEnv, -- Top-level stuff that never changes
112 -- Includes all info about imported things
114 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
115 -- Unique supply for local varibles
117 env_gbl :: gbl, -- Info about things defined at the top level
118 -- of the module being compiled
120 env_lcl :: lcl -- Nested stuff; changes as we go into
123 -- TcGblEnv describes the top-level of the module at the
124 -- point at which the typechecker is finished work.
125 -- It is this structure that is handed on to the desugarer
129 tcg_mod :: Module, -- Module being compiled
130 tcg_src :: HscSource, -- What kind of module
131 -- (regular Haskell, hs-boot, ext-core)
133 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
134 tcg_default :: Maybe [Type], -- Types used for defaulting
135 -- Nothing => no 'default' decl
137 tcg_fix_env :: FixityEnv, -- Just for things in this module
138 tcg_field_env :: RecFieldEnv, -- Just for things in this module
140 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
141 -- All TyCons and Classes (for this module) end up in here right away,
142 -- along with their derived constructors, selectors.
144 -- (Ids defined in this module start in the local envt,
145 -- though they move to the global envt during zonking)
147 tcg_type_env_var :: TcRef TypeEnv,
148 -- Used only to initialise the interface-file
149 -- typechecker in initIfaceTcRn, so that it can see stuff
150 -- bound in this module when dealing with hi-boot recursions
151 -- Updated at intervals (e.g. after dealing with types and classes)
153 tcg_inst_env :: InstEnv, -- Instance envt for *home-package*
154 -- modules; Includes the dfuns in
156 tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
158 -- Now a bunch of things about this module that are simply
159 -- accumulated, but never consulted until the end.
160 -- Nevertheless, it's convenient to accumulate them along
161 -- with the rest of the info from this module.
162 tcg_exports :: [AvailInfo], -- What is exported
163 tcg_imports :: ImportAvails, -- Information about what was imported
164 -- from where, including things bound
167 tcg_dus :: DefUses, -- What is defined in this module and what is used.
168 -- The latter is used to generate
169 -- (a) version tracking; no need to recompile if these
170 -- things have not changed version stamp
171 -- (b) unused-import info
173 tcg_keep :: TcRef NameSet, -- Locally-defined top-level names to keep alive
174 -- "Keep alive" means give them an Exported flag, so
175 -- that the simplifier does not discard them as dead
176 -- code, and so that they are exposed in the interface file
177 -- (but not to export to the user).
179 -- Some things, like dict-fun Ids and default-method Ids are
180 -- "born" with the Exported flag on, for exactly the above reason,
181 -- but some we only discover as we go. Specifically:
182 -- * The to/from functions for generic data types
183 -- * Top-level variables appearing free in the RHS of an orphan rule
184 -- * Top-level variables appearing free in a TH bracket
186 tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used
187 -- Used to generate version dependencies
188 -- This records usages, rather like tcg_dus, but it has to
189 -- be a mutable variable so it can be augmented
190 -- when we look up an instance. These uses of dfuns are
191 -- rather like the free variables of the program, but
192 -- are implicit instead of explicit.
194 tcg_th_used :: TcRef Bool, -- True <=> Template Haskell syntax used
195 -- We need this so that we can generate a dependency on the
196 -- Template Haskell package, becuase the desugarer is going to
197 -- emit loads of references to TH symbols. It's rather like
198 -- tcg_inst_uses; the reference is implicit rather than explicit,
199 -- so we have to zap a mutable variable.
201 tcg_dfun_n :: TcRef Int, -- Allows us to number off the names of DFuns
202 -- It's convenient to allocate an External Name for a DFun, with
203 -- a permanently-fixed unique, just like other top-level functions
204 -- defined in this module. But that means we need a canonical
205 -- occurrence name, distinct from all other dfuns in this module,
206 -- and this name supply serves that purpose (df1, df2, etc).
208 -- The next fields accumulate the payload of the module
209 -- The binds, rules and foreign-decl fiels are collected
210 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
212 tcg_rn_imports :: Maybe [LImportDecl Name],
213 tcg_rn_exports :: Maybe [Located (IE Name)],
214 tcg_rn_decls :: Maybe (HsGroup Name), -- renamed decls, maybe
215 -- Nothing <=> Don't retain renamed decls
217 tcg_binds :: LHsBinds Id, -- Value bindings in this module
218 tcg_warns :: Warnings, -- ...Warnings and deprecations
219 tcg_anns :: [Annotation], -- ...Annotations
220 tcg_insts :: [Instance], -- ...Instances
221 tcg_fam_insts :: [FamInst], -- ...Family instances
222 tcg_rules :: [LRuleDecl Id], -- ...Rules
223 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
225 tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
226 tcg_hmi :: HaddockModInfo Name, -- Haddock module information
227 tcg_hpc :: AnyHpcUsage -- True if any part of the prog uses hpc instrumentation.
231 = RecFields (NameEnv [Name]) -- Maps a constructor name *in this module*
232 -- to the fields for that constructor
233 NameSet -- Set of all fields declared *in this module*;
234 -- used to suppress name-shadowing complaints
235 -- when using record wild cards
236 -- E.g. let fld = e in C {..}
237 -- This is used when dealing with ".." notation in record
238 -- construction and pattern matching.
239 -- The FieldEnv deals *only* with constructors defined in *this*
240 -- module. For imported modules, we get the same info from the
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-programming 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 ThLevel -- Ordinary compiling, usually at level topLevel but annotations use a lower level
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, topAnnStage, topSpliceStage :: ThStage
384 topStage = Comp topLevel
385 topAnnStage = Comp (topLevel - 1)
386 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
388 ---------------------------
389 -- Arrow-notation context
390 ---------------------------
393 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
394 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
399 Here, x is not in scope in e1, but it is in scope in e2. This can get
403 proc y -> (proc z -> e1) -< e2
405 Here, x and z are in scope in e1, but y is not. We implement this by
406 recording the environment when passing a proc (using newArrowScope),
407 and returning to that (using escapeArrowScope) on the left of -< and the
413 | ArrowCtxt (Env TcGblEnv TcLclEnv)
415 -- Record the current environment (outside a proc)
416 newArrowScope :: TcM a -> TcM a
419 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
421 -- Return to the stored environment (from the enclosing proc)
422 escapeArrowScope :: TcM a -> TcM a
424 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
426 ArrowCtxt env' -> env'
428 ---------------------------
430 ---------------------------
433 = AGlobal TyThing -- Used only in the return type of a lookup
435 | ATcId { -- Ids defined in this module; may not be fully zonked
437 tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
438 -- Nothing <=> Do not apply a GADT type refinement
439 -- I am wobbly, or have no free
441 -- Just co <=> Apply any type refinement to me,
442 -- and record it in the coercion
443 tct_type :: TcType, -- Type of (coercion applied to id)
444 tct_level :: ThLevel }
446 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
447 -- is currently refined. We only need the Name
448 -- for error-message purposes
450 | AThing TcKind -- Used temporarily, during kind checking, for the
451 -- tycons and clases in this recursive group
453 data RefinementVisibility
454 = Unrefineable -- Do not apply a GADT refinement
455 -- I have no free variables
457 | Rigid HsWrapper -- Apply any refinement to me
458 -- and record it in the coercion
460 | Wobbly -- Do not apply a GADT refinement
463 | WobblyInvisible -- Wobbly type, not available inside current
466 instance Outputable TcTyThing where -- Debugging only
467 ppr (AGlobal g) = pprTyThing g
468 ppr elt@(ATcId {}) = text "Identifier" <>
469 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
470 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
471 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
472 ppr (AThing k) = text "AThing" <+> ppr k
474 pprTcTyThingCategory :: TcTyThing -> SDoc
475 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
476 pprTcTyThingCategory (ATyVar {}) = ptext (sLit "Type variable")
477 pprTcTyThingCategory (ATcId {}) = ptext (sLit "Local identifier")
478 pprTcTyThingCategory (AThing {}) = ptext (sLit "Kinded thing")
480 instance Outputable RefinementVisibility where
481 ppr Unrefineable = ptext (sLit "unrefineable")
482 ppr (Rigid co) = ptext (sLit "rigid") <+> ppr co
483 ppr Wobbly = ptext (sLit "wobbly")
484 ppr WobblyInvisible = ptext (sLit "wobbly-invisible")
489 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
490 -- Innermost first. Monadic so that we have a chance
491 -- to deal with bound type variables just before error
492 -- message construction
496 %************************************************************************
498 Operations over ImportAvails
500 %************************************************************************
502 ImportAvails summarises what was imported from where, irrespective
503 of whether the imported things are actually used or not
504 It is used * when processing the export list
505 * when constructing usage info for the inteface file
506 * to identify the list of directly imported modules
507 for initialisation purposes and
508 for optimsed overlap checking of family instances
509 * when figuring out what things are really unused
514 imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
515 -- Domain is all directly-imported modules
516 -- The ModuleName is what the module was imported as, e.g. in
520 -- True => import was "import Foo ()"
521 -- False => import was some other form
524 -- (a) to help construct the usage information in
525 -- the interface file; if we import somethign we
526 -- need to recompile if the export version changes
527 -- (b) to specify what child modules to initialise
529 -- We need a full ModuleEnv rather than a ModuleNameEnv
530 -- here, because we might be importing modules of the
531 -- same name from different packages. (currently not the case,
532 -- but might be in the future).
534 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
535 -- Home-package modules needed by the module being compiled
537 -- It doesn't matter whether any of these dependencies
538 -- are actually *used* when compiling the module; they
539 -- are listed if they are below it at all. For
540 -- example, suppose M imports A which imports X. Then
541 -- compiling M might not need to consult X.hi, but X
542 -- is still listed in M's dependencies.
544 imp_dep_pkgs :: [PackageId],
545 -- Packages needed by the module being compiled, whether
546 -- directly, or via other modules in this package, or via
547 -- modules imported from other packages.
549 imp_orphs :: [Module],
550 -- Orphan modules below us in the import tree (and maybe
551 -- including us for imported modules)
553 imp_finsts :: [Module]
554 -- Family instance modules below us in the import tree (and
555 -- maybe including us for imported modules)
558 mkModDeps :: [(ModuleName, IsBootInterface)]
559 -> ModuleNameEnv (ModuleName, IsBootInterface)
560 mkModDeps deps = foldl add emptyUFM deps
562 add env elt@(m,_) = addToUFM env m elt
564 emptyImportAvails :: ImportAvails
565 emptyImportAvails = ImportAvails { imp_mods = emptyModuleEnv,
566 imp_dep_mods = emptyUFM,
571 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
573 (ImportAvails { imp_mods = mods1,
574 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1,
575 imp_orphs = orphs1, imp_finsts = finsts1 })
576 (ImportAvails { imp_mods = mods2,
577 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
578 imp_orphs = orphs2, imp_finsts = finsts2 })
579 = ImportAvails { imp_mods = plusModuleEnv_C (++) mods1 mods2,
580 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
581 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
582 imp_orphs = orphs1 `unionLists` orphs2,
583 imp_finsts = finsts1 `unionLists` finsts2 }
585 plus_mod_dep (m1, boot1) (m2, boot2)
586 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
587 -- Check mod-names match
588 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
591 %************************************************************************
593 \subsection{Where from}
595 %************************************************************************
597 The @WhereFrom@ type controls where the renamer looks for an interface file
601 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
602 | ImportBySystem -- Non user import.
604 instance Outputable WhereFrom where
605 ppr (ImportByUser is_boot) | is_boot = ptext (sLit "{- SOURCE -}")
607 ppr ImportBySystem = ptext (sLit "{- SYSTEM -}")
611 %************************************************************************
613 \subsection[Inst-types]{@Inst@ types}
615 v%************************************************************************
617 An @Inst@ is either a dictionary, an instance of an overloaded
618 literal, or an instance of an overloaded value. We call the latter a
619 ``method'' even though it may not correspond to a class operation.
620 For example, we might have an instance of the @double@ function at
621 type Int, represented by
623 Method 34 doubleId [Int] origin
625 In addition to the basic Haskell variants of 'Inst's, they can now also
626 represent implication constraints 'forall tvs. given => wanted'
627 and equality constraints 'co :: ty1 ~ ty2'.
629 NB: Equalities occur in two flavours:
631 (1) Dict {tci_pred = EqPred ty1 ty2}
632 (2) EqInst {tci_left = ty1, tci_right = ty2, tci_co = coe}
634 The former arises from equalities in contexts, whereas the latter is used
635 whenever the type checker introduces an equality (e.g., during deferring
638 I am not convinced that this duplication is necessary or useful! -=chak
644 tci_pred :: TcPredType, -- Class or implicit parameter only
648 | ImplicInst { -- An implication constraint
649 -- forall tvs. given => wanted
651 tci_tyvars :: [TcTyVar], -- Quantified type variables
652 tci_given :: [Inst], -- Only Dicts and EqInsts
653 -- (no Methods, LitInsts, ImplicInsts)
654 tci_wanted :: [Inst], -- Only Dicts, EqInst, and ImplicInsts
655 -- (no Methods or LitInsts)
659 -- NB: the tci_given are not necessarily rigid
662 tci_id :: TcId, -- The Id for the Inst
664 tci_oid :: TcId, -- The overloaded function
665 -- This function will be a global, local, or ClassOpId;
666 -- inside instance decls (only) it can also be an InstId!
667 -- The id needn't be completely polymorphic.
668 -- You'll probably find its name (for documentation purposes)
669 -- inside the InstOrigin
671 tci_tys :: [TcType], -- The types to which its polymorphic tyvars
672 -- should be instantiated.
673 -- These types must saturate the Id's foralls.
675 tci_theta :: TcThetaType,
676 -- The (types of the) dictionaries to which the function
677 -- must be applied to get the method
681 -- INVARIANT 1: in (Method m f tys theta tau loc)
682 -- type of m = type of (f tys dicts(from theta))
684 -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
685 -- Reason: two methods are considered equal if the
686 -- base Id matches, and the instantiating types
687 -- match. The TcThetaType should then match too.
688 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
692 tci_lit :: HsOverLit Name, -- The literal from the occurrence site
693 -- INVARIANT: never a rebindable-syntax literal
694 -- Reason: tcSyntaxName does unification, and we
695 -- don't want to deal with that during tcSimplify,
696 -- when resolving LitInsts
698 tci_ty :: TcType, -- The type at which the literal is used
702 | EqInst { -- delayed unification of the form
704 tci_left :: TcType, -- ty1 -- both types are...
705 tci_right :: TcType, -- ty2 -- ...free of boxes
706 tci_co :: EqInstCo, -- co
709 tci_name :: Name -- Debugging help only: this makes it easier to
710 -- follow where a constraint is used in a morass
711 -- of trace messages! Unlike other Insts, it
712 -- has no semantic significance whatsoever.
715 type EqInstCo = Either -- Distinguish between given and wanted coercions
716 TcTyVar -- - a wanted equation, with a hole, to be filled
717 -- with a witness for the equality; for equation
718 -- arising from deferring unification, 'ty1' is
719 -- the actual and 'ty2' the expected type
720 Coercion -- - a given equation, with a coercion witnessing
721 -- the equality; a coercion that originates
722 -- from a signature or a GADT is a CoVar, but
723 -- after normalisation of coercions, they can
724 -- be arbitrary Coercions involving constructors
725 -- and pseudo-constructors like sym and trans.
728 @Insts@ are ordered by their class/type info, rather than by their
729 unique. This allows the context-reduction mechanism to use standard finite
730 maps to do their stuff. It's horrible that this code is here, rather
731 than with the Avails handling stuff in TcSimplify
734 instance Ord Inst where
736 -- Used *only* for AvailEnv in TcSimplify
738 instance Eq Inst where
739 (==) i1 i2 = case i1 `cmpInst` i2 of
743 cmpInst :: Inst -> Inst -> Ordering
744 cmpInst d1@(Dict {}) d2@(Dict {}) = tci_pred d1 `tcCmpPred` tci_pred d2
745 cmpInst (Dict {}) _ = LT
747 cmpInst (Method {}) (Dict {}) = GT
748 cmpInst m1@(Method {}) m2@(Method {}) = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
749 (tci_tys m1 `tcCmpTypes` tci_tys m2)
750 cmpInst (Method {}) _ = LT
752 cmpInst (LitInst {}) (Dict {}) = GT
753 cmpInst (LitInst {}) (Method {}) = GT
754 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
755 (tci_ty l1 `tcCmpType` tci_ty l2)
756 cmpInst (LitInst {}) _ = LT
758 -- Implication constraints are compared by *name*
759 -- not by type; that is, we make no attempt to do CSE on them
760 cmpInst (ImplicInst {}) (Dict {}) = GT
761 cmpInst (ImplicInst {}) (Method {}) = GT
762 cmpInst (ImplicInst {}) (LitInst {}) = GT
763 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
764 cmpInst (ImplicInst {}) _ = LT
766 -- same for Equality constraints
767 cmpInst (EqInst {}) (Dict {}) = GT
768 cmpInst (EqInst {}) (Method {}) = GT
769 cmpInst (EqInst {}) (LitInst {}) = GT
770 cmpInst (EqInst {}) (ImplicInst {}) = GT
771 cmpInst i1@(EqInst {}) i2@(EqInst {}) = (tci_left i1 `tcCmpType` tci_left i2) `thenCmp`
772 (tci_right i1 `tcCmpType` tci_right i2)
776 %************************************************************************
778 \subsection[Inst-collections]{LIE: a collection of Insts}
780 %************************************************************************
783 -- FIXME: Rename this. It clashes with (Located (IE ...))
786 isEmptyLIE :: LIE -> Bool
787 isEmptyLIE = isEmptyBag
792 unitLIE :: Inst -> LIE
793 unitLIE inst = unitBag inst
795 mkLIE :: [Inst] -> LIE
796 mkLIE insts = listToBag insts
798 plusLIE :: LIE -> LIE -> LIE
799 plusLIE lie1 lie2 = lie1 `unionBags` lie2
801 plusLIEs :: [LIE] -> LIE
802 plusLIEs lies = unionManyBags lies
804 lieToList :: LIE -> [Inst]
805 lieToList = bagToList
807 listToLIE :: [Inst] -> LIE
808 listToLIE = listToBag
810 consLIE :: Inst -> LIE -> LIE
811 consLIE inst lie = lie `snocBag` inst
812 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
813 -- to ensure that we tend to report the *leftmost* type-constraint error
816 -- we'd like to complain about the '1', not the '3'.
818 -- "Half-hearted" because the rest of the type checker makes no great
819 -- claims for retaining order in the constraint set. Still, this
820 -- seems to improve matters slightly. Exampes: mdofail001, tcfail015
824 %************************************************************************
826 \subsection[Inst-origin]{The @InstOrigin@ type}
828 %************************************************************************
830 The @InstOrigin@ type gives information about where a dictionary came from.
831 This is important for decent error message reporting because dictionaries
832 don't appear in the original source code. Doubtless this type will evolve...
834 It appears in TcMonad because there are a couple of error-message-generation
835 functions that deal with it.
838 -------------------------------------------
839 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
841 instLoc :: Inst -> InstLoc
842 instLoc inst = tci_loc inst
844 instSpan :: Inst -> SrcSpan
845 instSpan wanted = instLocSpan (instLoc wanted)
847 instLocSpan :: InstLoc -> SrcSpan
848 instLocSpan (InstLoc _ s _) = s
850 instLocOrigin :: InstLoc -> InstOrigin
851 instLocOrigin (InstLoc o _ _) = o
853 pprInstArising :: Inst -> SDoc
854 pprInstArising loc = ptext (sLit "arising from") <+> pprInstLoc (tci_loc loc)
856 pprInstLoc :: InstLoc -> SDoc
857 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
859 -------------------------------------------
861 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
862 -- Places that bind type variables and introduce
863 -- available constraints
865 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
867 -------------------------------------------------------
868 -- The rest are all occurrences: Insts that are 'wanted'
869 -------------------------------------------------------
870 | OccurrenceOf Name -- Occurrence of an overloaded identifier
871 | SpecPragOrigin Name -- Specialisation pragma for identifier
873 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
875 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
876 | NegateOrigin -- Occurrence of syntactic negation
878 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
879 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
880 | TupleOrigin -- (..,..)
882 | InstSigOrigin -- A dict occurrence arising from instantiating
883 -- a polymorphic type during a subsumption check
885 | ExprSigOrigin -- e :: ty
888 | InstScOrigin -- Typechecking superclasses of an instance declaration
889 | DerivOrigin -- Typechecking deriving
890 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
891 | DefaultOrigin -- Typechecking a default decl
892 | DoOrigin -- Arising from a do expression
893 | ProcOrigin -- Arising from a proc expression
894 | ImplicOrigin SDoc -- An implication constraint
895 | EqOrigin -- A type equality
896 | AnnOrigin -- An annotation
898 instance Outputable InstOrigin where
899 ppr (OccurrenceOf name) = hsep [ptext (sLit "a use of"), quotes (ppr name)]
900 ppr (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
901 ppr (IPOccOrigin name) = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
902 ppr (IPBindOrigin name) = hsep [ptext (sLit "a binding for implicit parameter"), quotes (ppr name)]
903 ppr RecordUpdOrigin = ptext (sLit "a record update")
904 ppr ExprSigOrigin = ptext (sLit "an expression type signature")
905 ppr ViewPatOrigin = ptext (sLit "a view pattern")
906 ppr (LiteralOrigin lit) = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
907 ppr (ArithSeqOrigin seq) = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
908 ppr (PArrSeqOrigin seq) = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
909 ppr TupleOrigin = ptext (sLit "a tuple")
910 ppr NegateOrigin = ptext (sLit "a use of syntactic negation")
911 ppr InstScOrigin = ptext (sLit "the superclasses of an instance declaration")
912 ppr DerivOrigin = ptext (sLit "the 'deriving' clause of a data type declaration")
913 ppr StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
914 ppr DefaultOrigin = ptext (sLit "a 'default' declaration")
915 ppr DoOrigin = ptext (sLit "a do statement")
916 ppr ProcOrigin = ptext (sLit "a proc expression")
917 ppr (ImplicOrigin doc) = doc
918 ppr (SigOrigin info) = pprSkolInfo info
919 ppr EqOrigin = ptext (sLit "a type equality")
920 ppr InstSigOrigin = panic "ppr InstSigOrigin"
921 ppr AnnOrigin = ptext (sLit "an annotation")