2 % (c) The GRASP Project, Glasgow University, 1992-2002
6 TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
9 -- The environment types
11 TcGblEnv(..), TcLclEnv(..),
12 IfGblEnv(..), IfLclEnv(..),
16 ImportAvails(..), emptyImportAvails, plusImportAvails,
17 plusAvail, pruneAvails,
18 AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv,
19 mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
20 WhereFrom(..), mkModDeps,
23 TcTyThing(..), pprTcTyThingCategory,
26 ThStage(..), topStage, topSpliceStage,
27 ThLevel, impLevel, topLevel,
30 ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
33 Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc,
34 instLocSrcLoc, instLocSrcSpan,
35 LIE, emptyLIE, unitLIE, plusLIE, consLIE,
36 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
39 TcId, TcIdSet, TcDictBinds
42 #include "HsVersions.h"
44 import HsSyn ( PendingSplice, HsOverLit, LRuleDecl, LForeignDecl,
45 ArithSeqInfo, DictBinds, LHsBinds, LImportDecl, HsGroup,
46 HsWrapper, IE, HsDoc, HaddockModInfo )
47 import HscTypes ( FixityEnv,
48 HscEnv, TypeEnv, TyThing,
49 GenAvailInfo(..), AvailInfo, HscSource(..),
50 availName, IsBootInterface, Deprecations )
51 import Packages ( PackageId )
52 import Type ( Type, pprTyThingCategory )
53 import TcType ( TcTyVarSet, TcType, TcThetaType, SkolemInfo,
54 TcPredType, TcKind, tcCmpPred, tcCmpType,
55 tcCmpTypes, pprSkolInfo )
56 import InstEnv ( Instance, InstEnv )
57 import FamInstEnv ( FamInst, FamInstEnv )
59 import RdrName ( GlobalRdrEnv, LocalRdrEnv )
62 import NameSet ( NameSet, unionNameSets, DefUses )
63 import Var ( Id, TyVar )
64 import VarEnv ( TidyEnv )
67 import SrcLoc ( SrcSpan, SrcLoc, Located, srcSpanStart )
68 import VarSet ( IdSet )
69 import ErrUtils ( Messages, Message )
70 import UniqSupply ( UniqSupply )
71 import BasicTypes ( IPName )
72 import Util ( thenCmp )
75 import Maybe ( mapMaybe )
76 import ListSetOps ( unionLists )
80 %************************************************************************
82 Standard monad definition for TcRn
83 All the combinators for the monad can be found in TcRnMonad
85 %************************************************************************
87 The monad itself has to be defined here, because it is mentioned by ErrCtxt
90 type TcRef a = IORef a
91 type TcId = Id -- Type may be a TcType
93 type TcDictBinds = DictBinds TcId -- Bag of dictionary bindings
95 type TcRnIf a b c = IOEnv (Env a b) c
96 type IfM lcl a = TcRnIf IfGblEnv lcl a -- Iface stuff
98 type IfG a = IfM () a -- Top level
99 type IfL a = IfM IfLclEnv a -- Nested
100 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
101 type RnM a = TcRn a -- Historical
102 type TcM a = TcRn a -- Historical
106 %************************************************************************
108 The main environment types
110 %************************************************************************
113 data Env gbl lcl -- Changes as we move into an expression
115 env_top :: HscEnv, -- Top-level stuff that never changes
116 -- Includes all info about imported things
118 env_us :: {-# UNPACK #-} !(IORef UniqSupply),
119 -- Unique supply for local varibles
121 env_gbl :: gbl, -- Info about things defined at the top level
122 -- of the module being compiled
124 env_lcl :: lcl -- Nested stuff; changes as we go into
128 -- TcGblEnv describes the top-level of the module at the
129 -- point at which the typechecker is finished work.
130 -- It is this structure that is handed on to the desugarer
134 tcg_mod :: Module, -- Module being compiled
135 tcg_src :: HscSource, -- What kind of module
136 -- (regular Haskell, hs-boot, ext-core)
138 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
139 tcg_default :: Maybe [Type], -- Types used for defaulting
140 -- Nothing => no 'default' decl
142 tcg_fix_env :: FixityEnv, -- Just for things in this module
144 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
145 -- All TyCons and Classes (for this module) end up in here right away,
146 -- along with their derived constructors, selectors.
148 -- (Ids defined in this module start in the local envt,
149 -- though they move to the global envt during zonking)
151 tcg_type_env_var :: TcRef TypeEnv,
152 -- Used only to initialise the interface-file
153 -- typechecker in initIfaceTcRn, so that it can see stuff
154 -- bound in this module when dealing with hi-boot recursions
155 -- Updated at intervals (e.g. after dealing with types and classes)
157 tcg_inst_env :: InstEnv, -- Instance envt for *home-package*
158 -- modules; Includes the dfuns in
160 tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
162 -- Now a bunch of things about this module that are simply
163 -- accumulated, but never consulted until the end.
164 -- Nevertheless, it's convenient to accumulate them along
165 -- with the rest of the info from this module.
166 tcg_exports :: NameSet, -- What is exported
167 tcg_imports :: ImportAvails, -- Information about what was imported
168 -- from where, including things bound
171 tcg_dus :: DefUses, -- What is defined in this module and what is used.
172 -- The latter is used to generate
173 -- (a) version tracking; no need to recompile if these
174 -- things have not changed version stamp
175 -- (b) unused-import info
177 tcg_keep :: TcRef NameSet, -- Locally-defined top-level names to keep alive
178 -- "Keep alive" means give them an Exported flag, so
179 -- that the simplifier does not discard them as dead
180 -- code, and so that they are exposed in the interface file
181 -- (but not to export to the user).
183 -- Some things, like dict-fun Ids and default-method Ids are
184 -- "born" with the Exported flag on, for exactly the above reason,
185 -- but some we only discover as we go. Specifically:
186 -- * The to/from functions for generic data types
187 -- * Top-level variables appearing free in the RHS of an orphan rule
188 -- * Top-level variables appearing free in a TH bracket
190 tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used
191 -- Used to generate version dependencies
192 -- This records usages, rather like tcg_dus, but it has to
193 -- be a mutable variable so it can be augmented
194 -- when we look up an instance. These uses of dfuns are
195 -- rather like the free variables of the program, but
196 -- are implicit instead of explicit.
198 tcg_th_used :: TcRef Bool, -- True <=> Template Haskell syntax used
199 -- We need this so that we can generate a dependency on the
200 -- Template Haskell package, becuase the desugarer is going to
201 -- emit loads of references to TH symbols. It's rather like
202 -- tcg_inst_uses; the reference is implicit rather than explicit,
203 -- so we have to zap a mutable variable.
205 tcg_dfun_n :: TcRef Int, -- Allows us to number off the names of DFuns
206 -- It's convenient to allocate an External Name for a DFun, with
207 -- a permanently-fixed unique, just like other top-level functions
208 -- defined in this module. But that means we need a canonical
209 -- occurrence name, distinct from all other dfuns in this module,
210 -- and this name supply serves that purpose (df1, df2, etc).
212 -- The next fields accumulate the payload of the module
213 -- The binds, rules and foreign-decl fiels are collected
214 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
216 -- The next fields accumulate the payload of the
217 -- module The binds, rules and foreign-decl fiels are
218 -- collected initially in un-zonked form and are
219 -- finally zonked in tcRnSrcDecls
221 tcg_rn_imports :: Maybe [LImportDecl Name],
222 tcg_rn_exports :: Maybe [Located (IE Name)],
223 tcg_rn_decls :: Maybe (HsGroup Name), -- renamed decls, maybe
224 -- Nothing <=> Don't retain renamed decls
226 tcg_binds :: LHsBinds Id, -- Value bindings in this module
227 tcg_deprecs :: Deprecations, -- ...Deprecations
228 tcg_insts :: [Instance], -- ...Instances
229 tcg_fam_insts :: [FamInst], -- ...Family instances
230 tcg_rules :: [LRuleDecl Id], -- ...Rules
231 tcg_fords :: [LForeignDecl Id], -- ...Foreign import & exports
233 tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
234 tcg_hmi :: HaddockModInfo Name -- Haddock module information
238 %************************************************************************
240 The interface environments
241 Used when dealing with IfaceDecls
243 %************************************************************************
248 -- The type environment for the module being compiled,
249 -- in case the interface refers back to it via a reference that
250 -- was originally a hi-boot file.
251 -- We need the module name so we can test when it's appropriate
252 -- to look in this env.
253 if_rec_types :: Maybe (Module, IfG TypeEnv)
254 -- Allows a read effect, so it can be in a mutable
255 -- variable; c.f. handling the external package type env
256 -- Nothing => interactive stuff, no loops possible
261 -- The module for the current IfaceDecl
262 -- So if we see f = \x -> x
263 -- it means M.f = \x -> x, where M is the if_mod
266 -- The field is used only for error reporting
267 -- if (say) there's a Lint error in it
269 -- Where the interface came from:
270 -- .hi file, or GHCi state, or ext core
271 -- plus which bit is currently being examined
273 if_tv_env :: UniqFM TyVar, -- Nested tyvar bindings
274 if_id_env :: UniqFM Id -- Nested id binding
279 %************************************************************************
281 The local typechecker environment
283 %************************************************************************
285 The Global-Env/Local-Env story
286 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
287 During type checking, we keep in the tcg_type_env
288 * All types and classes
289 * All Ids derived from types and classes (constructors, selectors)
291 At the end of type checking, we zonk the local bindings,
292 and as we do so we add to the tcg_type_env
293 * Locally defined top-level Ids
295 Why? Because they are now Ids not TcIds. This final GlobalEnv is
296 a) fed back (via the knot) to typechecking the
297 unfoldings of interface signatures
298 b) used in the ModDetails of this module
301 data TcLclEnv -- Changes as we move inside an expression
302 -- Discarded after typecheck/rename; not passed on to desugarer
304 tcl_loc :: SrcSpan, -- Source span
305 tcl_ctxt :: ErrCtxt, -- Error context
306 tcl_errs :: TcRef Messages, -- Place to accumulate errors
308 tcl_th_ctxt :: ThStage, -- Template Haskell context
309 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
311 tcl_rdr :: LocalRdrEnv, -- Local name envt
312 -- Maintained during renaming, of course, but also during
313 -- type checking, solely so that when renaming a Template-Haskell
314 -- splice we have the right environment for the renamer.
316 -- Does *not* include global name envt; may shadow it
317 -- Includes both ordinary variables and type variables;
318 -- they are kept distinct because tyvar have a different
319 -- occurrence contructor (Name.TvOcc)
320 -- We still need the unsullied global name env so that
321 -- we can look up record field names
323 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
324 -- defined in this module
326 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
327 -- Namely, the in-scope TyVars bound in tcl_env,
328 -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
329 -- Why mutable? see notes with tcGetGlobalTyVars
331 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
335 {- Note [Given Insts]
337 Because of GADTs, we have to pass inwards the Insts provided by type signatures
338 and existential contexts. Consider
339 data T a where { T1 :: b -> b -> T [b] }
340 f :: Eq a => T a -> Bool
341 f (T1 x y) = [x]==[y]
343 The constructor T1 binds an existential variable 'b', and we need Eq [b].
344 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we
349 ---------------------------
350 -- Template Haskell levels
351 ---------------------------
354 -- Indicates how many levels of brackets we are inside
356 -- Incremented when going inside a bracket,
357 -- decremented when going inside a splice
358 -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
359 -- original "Template meta-programmign for Haskell" paper
361 impLevel, topLevel :: ThLevel
362 topLevel = 1 -- Things defined at top level of this module
363 impLevel = 0 -- Imported things; they can be used inside a top level splice
367 -- g1 = $(map ...) is OK
368 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
372 = Comp -- Ordinary compiling, at level topLevel
373 | Splice ThLevel -- Inside a splice
374 | Brack ThLevel -- Inside brackets;
375 (TcRef [PendingSplice]) -- accumulate pending splices here
376 (TcRef LIE) -- and type constraints here
377 topStage, topSpliceStage :: ThStage
379 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
381 ---------------------------
382 -- Arrow-notation context
383 ---------------------------
386 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
387 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
392 Here, x is not in scope in e1, but it is in scope in e2. This can get
396 proc y -> (proc z -> e1) -< e2
398 Here, x and z are in scope in e1, but y is not. We implement this by
399 recording the environment when passing a proc (using newArrowScope),
400 and returning to that (using escapeArrowScope) on the left of -< and the
406 | ArrowCtxt (Env TcGblEnv TcLclEnv)
408 -- Record the current environment (outside a proc)
409 newArrowScope :: TcM a -> TcM a
412 env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
414 -- Return to the stored environment (from the enclosing proc)
415 escapeArrowScope :: TcM a -> TcM a
417 = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
419 ArrowCtxt env' -> env'
421 ---------------------------
423 ---------------------------
426 = AGlobal TyThing -- Used only in the return type of a lookup
428 | ATcId { -- Ids defined in this module; may not be fully zonked
430 tct_co :: Maybe HsWrapper, -- Nothing <=> Do not apply a GADT type refinement
431 -- I am wobbly, or have no free
433 -- Just co <=> Apply any type refinement to me,
434 -- and record it in the coercion
435 tct_type :: TcType, -- Type of (coercion applied to id)
436 tct_level :: ThLevel }
438 | ATyVar Name TcType -- The type to which the lexically scoped type vaiable
439 -- is currently refined. We only need the Name
440 -- for error-message purposes
442 | AThing TcKind -- Used temporarily, during kind checking, for the
443 -- tycons and clases in this recursive group
445 instance Outputable TcTyThing where -- Debugging only
446 ppr (AGlobal g) = ppr g
447 ppr elt@(ATcId {}) = text "Identifier" <>
448 ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
449 <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
450 ppr (ATyVar tv _) = text "Type variable" <+> quotes (ppr tv)
451 ppr (AThing k) = text "AThing" <+> ppr k
453 pprTcTyThingCategory :: TcTyThing -> SDoc
454 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
455 pprTcTyThingCategory (ATyVar {}) = ptext SLIT("Type variable")
456 pprTcTyThingCategory (ATcId {}) = ptext SLIT("Local identifier")
457 pprTcTyThingCategory (AThing {}) = ptext SLIT("Kinded thing")
461 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
462 -- Innermost first. Monadic so that we have a chance
463 -- to deal with bound type variables just before error
464 -- message construction
468 %************************************************************************
470 Operations over ImportAvails
472 %************************************************************************
474 ImportAvails summarises what was imported from where, irrespective
475 of whether the imported things are actually used or not
476 It is used * when processing the export list
477 * when constructing usage info for the inteface file
478 * to identify the list of directly imported modules
479 for initialisation purposes
480 * when figuring out what things are really unused
485 imp_env :: ModuleNameEnv NameSet,
486 -- All the things imported, classified by
487 -- the *module qualifier* for its import
488 -- e.g. import List as Foo
489 -- would add a binding Foo |-> ...stuff from List...
492 -- We need to classify them like this so that we can figure out
493 -- "module M" export specifiers in an export list
494 -- (see 1.4 Report Section 5.1.1). Ultimately, we want to find
495 -- everything that is unambiguously in scope as 'M.x'
496 -- and where plain 'x' is (perhaps ambiguously) in scope.
497 -- So the starting point is all things that are in scope as 'M.x',
498 -- which is what this field tells us.
500 imp_mods :: ModuleEnv (Module, Bool, SrcSpan),
501 -- Domain is all directly-imported modules
503 -- True => import was "import Foo ()"
504 -- False => import was some other form
506 -- We need the Module in the range because we can't get
507 -- the keys of a ModuleEnv
509 -- (a) to help construct the usage information in
510 -- the interface file; if we import somethign we
511 -- need to recompile if the export version changes
512 -- (b) to specify what child modules to initialise
514 imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
515 -- Home-package modules needed by the module being compiled
517 -- It doesn't matter whether any of these dependencies
518 -- are actually *used* when compiling the module; they
519 -- are listed if they are below it at all. For
520 -- example, suppose M imports A which imports X. Then
521 -- compiling M might not need to consult X.hi, but X
522 -- is still listed in M's dependencies.
524 imp_dep_pkgs :: [PackageId],
525 -- Packages needed by the module being compiled, whether
526 -- directly, or via other modules in this package, or via
527 -- modules imported from other packages.
529 imp_orphs :: [Module]
530 -- Orphan modules below us in the import tree
533 mkModDeps :: [(ModuleName, IsBootInterface)]
534 -> ModuleNameEnv (ModuleName, IsBootInterface)
535 mkModDeps deps = foldl add emptyUFM deps
537 add env elt@(m,_) = addToUFM env m elt
539 emptyImportAvails :: ImportAvails
540 emptyImportAvails = ImportAvails { imp_env = emptyUFM,
541 imp_mods = emptyModuleEnv,
542 imp_dep_mods = emptyUFM,
546 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
548 (ImportAvails { imp_env = env1, imp_mods = mods1,
549 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
550 (ImportAvails { imp_env = env2, imp_mods = mods2,
551 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
552 = ImportAvails { imp_env = plusUFM_C unionNameSets env1 env2,
553 imp_mods = mods1 `plusModuleEnv` mods2,
554 imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2,
555 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
556 imp_orphs = orphs1 `unionLists` orphs2 }
558 plus_mod_dep (m1, boot1) (m2, boot2)
559 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
560 -- Check mod-names match
561 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
564 %************************************************************************
566 Avails, AvailEnv, etc
568 v%************************************************************************
571 plusAvail (Avail n1) (Avail n2) = Avail n1
572 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
575 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
578 -------------------------
579 pruneAvails :: (Name -> Bool) -- Keep if this is True
582 pruneAvails keep avails
583 = mapMaybe del avails
585 del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
586 del (Avail n) | keep n = Just (Avail n)
587 | otherwise = Nothing
588 del (AvailTC n ns) | null ns' = Nothing
589 | otherwise = Just (AvailTC n ns')
594 ---------------------------------------
596 ---------------------------------------
599 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
601 emptyAvailEnv :: AvailEnv
602 emptyAvailEnv = emptyNameEnv
604 unitAvailEnv :: AvailInfo -> AvailEnv
605 unitAvailEnv a = unitNameEnv (availName a) a
607 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
608 plusAvailEnv = plusNameEnv_C plusAvail
610 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
611 lookupAvailEnv_maybe = lookupNameEnv
613 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
614 lookupAvailEnv env n = case lookupNameEnv env n of
616 Nothing -> pprPanic "lookupAvailEnv" (ppr n)
618 availEnvElts = nameEnvElts
620 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
621 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
623 mkAvailEnv :: [AvailInfo] -> AvailEnv
624 -- 'avails' may have several items with the same availName
625 -- E.g import Ix( Ix(..), index )
626 -- will give Ix(Ix,index,range) and Ix(index)
627 -- We want to combine these; addAvail does that
628 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
631 %************************************************************************
633 \subsection{Where from}
635 %************************************************************************
637 The @WhereFrom@ type controls where the renamer looks for an interface file
641 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
642 | ImportBySystem -- Non user import.
644 instance Outputable WhereFrom where
645 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
647 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
651 %************************************************************************
653 \subsection[Inst-types]{@Inst@ types}
655 v%************************************************************************
657 An @Inst@ is either a dictionary, an instance of an overloaded
658 literal, or an instance of an overloaded value. We call the latter a
659 ``method'' even though it may not correspond to a class operation.
660 For example, we might have an instance of the @double@ function at
661 type Int, represented by
663 Method 34 doubleId [Int] origin
675 TcId -- The overloaded function
676 -- This function will be a global, local, or ClassOpId;
677 -- inside instance decls (only) it can also be an InstId!
678 -- The id needn't be completely polymorphic.
679 -- You'll probably find its name (for documentation purposes)
680 -- inside the InstOrigin
682 [TcType] -- The types to which its polymorphic tyvars
683 -- should be instantiated.
684 -- These types must saturate the Id's foralls.
686 TcThetaType -- The (types of the) dictionaries to which the function
687 -- must be applied to get the method
691 -- INVARIANT 1: in (Method u f tys theta tau loc)
692 -- type of (f tys dicts(from theta)) = tau
694 -- INVARIANT 2: tau must not be of form (Pred -> Tau)
695 -- Reason: two methods are considered equal if the
696 -- base Id matches, and the instantiating types
697 -- match. The TcThetaType should then match too.
698 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
702 (HsOverLit Name) -- The literal from the occurrence site
703 -- INVARIANT: never a rebindable-syntax literal
704 -- Reason: tcSyntaxName does unification, and we
705 -- don't want to deal with that during tcSimplify,
706 -- when resolving LitInsts
707 TcType -- The type at which the literal is used
711 @Insts@ are ordered by their class/type info, rather than by their
712 unique. This allows the context-reduction mechanism to use standard finite
713 maps to do their stuff.
716 instance Ord Inst where
719 instance Eq Inst where
720 (==) i1 i2 = case i1 `cmpInst` i2 of
724 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
725 cmpInst (Dict _ _ _) other = LT
727 cmpInst (Method _ _ _ _ _) (Dict _ _ _) = GT
728 cmpInst (Method _ id1 tys1 _ _) (Method _ id2 tys2 _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
729 cmpInst (Method _ _ _ _ _) other = LT
731 cmpInst (LitInst _ _ _ _) (Dict _ _ _) = GT
732 cmpInst (LitInst _ _ _ _) (Method _ _ _ _ _) = GT
733 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
737 %************************************************************************
739 \subsection[Inst-collections]{LIE: a collection of Insts}
741 %************************************************************************
744 -- FIXME: Rename this. It clashes with (Located (IE ...))
747 isEmptyLIE = isEmptyBag
749 unitLIE inst = unitBag inst
750 mkLIE insts = listToBag insts
751 plusLIE lie1 lie2 = lie1 `unionBags` lie2
752 consLIE inst lie = inst `consBag` lie
753 plusLIEs lies = unionManyBags lies
754 lieToList = bagToList
755 listToLIE = listToBag
759 %************************************************************************
761 \subsection[Inst-origin]{The @InstOrigin@ type}
763 %************************************************************************
765 The @InstOrigin@ type gives information about where a dictionary came from.
766 This is important for decent error message reporting because dictionaries
767 don't appear in the original source code. Doubtless this type will evolve...
769 It appears in TcMonad because there are a couple of error-message-generation
770 functions that deal with it.
773 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
775 instLocSrcLoc :: InstLoc -> SrcLoc
776 instLocSrcLoc (InstLoc _ src_span _) = srcSpanStart src_span
778 instLocSrcSpan :: InstLoc -> SrcSpan
779 instLocSrcSpan (InstLoc _ src_span _) = src_span
782 = SigOrigin SkolemInfo -- Pattern, class decl, inst decl etc;
783 -- Places that bind type variables and introduce
784 -- available constraints
786 | IPBindOrigin (IPName Name) -- Binding site of an implicit parameter
788 -------------------------------------------------------
789 -- The rest are all occurrences: Insts that are 'wanted'
790 -------------------------------------------------------
791 | OccurrenceOf Name -- Occurrence of an overloaded identifier
793 | IPOccOrigin (IPName Name) -- Occurrence of an implicit parameter
795 | LiteralOrigin (HsOverLit Name) -- Occurrence of a literal
797 | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
798 | PArrSeqOrigin (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
800 | InstSigOrigin -- A dict occurrence arising from instantiating
801 -- a polymorphic type during a subsumption check
804 | InstScOrigin -- Typechecking superclasses of an instance declaration
805 | DerivOrigin -- Typechecking deriving
806 | StandAloneDerivOrigin -- Typechecking stand-alone deriving
807 | DefaultOrigin -- Typechecking a default decl
808 | DoOrigin -- Arising from a do expression
809 | ProcOrigin -- Arising from a proc expression
813 pprInstLoc :: InstLoc -> SDoc
814 pprInstLoc (InstLoc orig locn _)
815 = sep [text "arising from" <+> pp_orig orig,
816 text "at" <+> ppr locn]
818 pp_orig (OccurrenceOf name) = hsep [ptext SLIT("use of"), quotes (ppr name)]
819 pp_orig (IPOccOrigin name) = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
820 pp_orig (IPBindOrigin name) = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
821 pp_orig RecordUpdOrigin = ptext SLIT("a record update")
822 pp_orig (LiteralOrigin lit) = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
823 pp_orig (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
824 pp_orig (PArrSeqOrigin seq) = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
825 pp_orig InstSigOrigin = ptext SLIT("instantiating a type signature")
826 pp_orig InstScOrigin = ptext SLIT("the superclasses of an instance declaration")
827 pp_orig DerivOrigin = ptext SLIT("the 'deriving' clause of a data type declaration")
828 pp_orig StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
829 pp_orig DefaultOrigin = ptext SLIT("a 'default' declaration")
830 pp_orig DoOrigin = ptext SLIT("a do statement")
831 pp_orig ProcOrigin = ptext SLIT("a proc expression")
832 pp_orig (SigOrigin info) = pprSkolInfo info