2 % (c) The GRASP Project, Glasgow University, 1992-2002
6 TcRn, TcM, RnM, -- The monad is opaque outside this module
8 -- Standard monadic operations
9 thenM, thenM_, returnM, failM,
11 -- Non-standard operations
12 runTcRn, fixM, tryM, ioToTcRn,
13 newMutVar, readMutVar, writeMutVar,
14 getEnv, setEnv, updEnv, unsafeInterleaveM, zapEnv,
16 -- The environment types
17 Env(..), TopEnv(..), TcGblEnv(..),
18 TcLclEnv(..), RnLclEnv(..),
21 RnMode(..), isInterfaceMode, isCmdLineMode,
22 EntityUsage, emptyUsages, ErrCtxt,
23 ImportAvails(..), emptyImportAvails, plusImportAvails,
24 plusAvail, pruneAvails,
25 AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv,
26 mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
33 Stage(..), topStage, topSpliceStage,
34 Level, impLevel, topLevel,
37 Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, instLocSrcLoc,
38 LIE, emptyLIE, unitLIE, plusLIE, consLIE,
39 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
45 #include "HsVersions.h"
47 import HsSyn ( PendingSplice, HsOverLit, MonoBinds, RuleDecl, ForeignDecl )
48 import RnHsSyn ( RenamedHsExpr, RenamedPat, RenamedArithSeqInfo )
49 import HscTypes ( GhciMode, ExternalPackageState, HomePackageTable,
50 NameCache, GlobalRdrEnv, LocalRdrEnv, FixityEnv,
51 TypeEnv, TyThing, Avails, GenAvailInfo(..), AvailInfo,
52 availName, IsBootInterface, Deprecations,
53 ExternalPackageState(..), emptyExternalPackageState )
54 import Packages ( PackageName )
55 import TcType ( TcTyVarSet, TcType, TcTauType, TcThetaType,
56 TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes )
57 import InstEnv ( DFunId, InstEnv )
60 import NameSet ( NameSet, emptyNameSet )
62 import Class ( Class )
63 import Var ( Id, TyVar )
64 import VarEnv ( TidyEnv )
66 import SrcLoc ( SrcLoc )
67 import VarSet ( IdSet )
68 import ErrUtils ( Messages, Message )
69 import CmdLineOpts ( DynFlags )
70 import UniqSupply ( UniqSupply )
71 import BasicTypes ( IPName )
72 import Util ( thenCmp )
75 import DATA_IOREF ( IORef, newIORef, readIORef, writeIORef )
76 import UNSAFE_IO ( unsafeInterleaveIO )
77 import FIX_IO ( fixIO )
78 import EXCEPTION ( Exception(..) )
79 import IO ( isUserError )
80 import Maybe ( mapMaybe )
81 import ListSetOps ( unionLists )
82 import Panic ( tryJust )
87 type TcRef a = IORef a
88 type TcId = Id -- Type may be a TcType
92 %************************************************************************
94 Standard monad definition for TcRn
95 All the combinators for the monad can be found in TcRnMonad
97 %************************************************************************
99 The monad itself has to be defined here,
100 because it is mentioned by ErrCtxt
103 newtype TcRn m a = TcRn (Env m -> IO a)
106 type TcM a = TcRn TcLclEnv a
107 type RnM a = TcRn RnLclEnv a
109 returnM :: a -> TcRn m a
110 returnM a = TcRn (\ env -> return a)
112 thenM :: TcRn m a -> (a -> TcRn m b) -> TcRn m b
113 thenM (TcRn m) f = TcRn (\ env -> do { r <- m env ;
116 thenM_ :: TcRn m a -> TcRn m b -> TcRn m b
117 thenM_ (TcRn m) f = TcRn (\ env -> do { m env ; unTcRn f env })
120 failM = TcRn (\ env -> ioError (userError "TcRn failure"))
122 instance Monad (TcRn m) where
126 fail s = failM -- Ignore the string
130 %************************************************************************
132 Fundmantal combinators specific to the monad
134 %************************************************************************
139 runTcRn :: Env m -> TcRn m a -> IO a
140 runTcRn env (TcRn m) = m env
143 The fixpoint combinator
146 {-# NOINLINE fixM #-}
147 -- Aargh! Not inlining fixTc alleviates a space leak problem.
148 -- Normally fixTc is used with a lazy tuple match: if the optimiser is
149 -- shown the definition of fixTc, it occasionally transforms the code
150 -- in such a way that the code generator doesn't spot the selector
153 fixM :: (a -> TcRn m a) -> TcRn m a
154 fixM f = TcRn (\ env -> fixIO (\ r -> unTcRn (f r) env))
160 tryM :: TcRn m r -> TcRn m (Either Exception r)
161 -- Reflect exception into TcRn monad
162 tryM (TcRn thing) = TcRn (\ env -> tryJust tc_errors (thing env))
164 #if __GLASGOW_HASKELL__ > 504 || __GLASGOW_HASKELL__ < 500
165 tc_errors e@(IOException ioe) | isUserError ioe = Just e
166 #elif __GLASGOW_HASKELL__ == 502
167 tc_errors (UserError _) = Just e
169 tc_errors e@(IOException ioe) | isUserError e = Just e
171 tc_errors _other = Nothing
172 -- type checker failures show up as UserErrors only
178 unsafeInterleaveM :: TcRn m a -> TcRn m a
179 unsafeInterleaveM (TcRn m) = TcRn (\ env -> unsafeInterleaveIO (m env))
184 Performing arbitrary I/O, plus the read/write var (for efficiency)
187 ioToTcRn :: IO a -> TcRn m a
188 ioToTcRn io = TcRn (\ env -> io)
190 newMutVar :: a -> TcRn m (TcRef a)
191 newMutVar val = TcRn (\ env -> newIORef val)
193 writeMutVar :: TcRef a -> a -> TcRn m ()
194 writeMutVar var val = TcRn (\ env -> writeIORef var val)
196 readMutVar :: TcRef a -> TcRn m a
197 readMutVar var = TcRn (\ env -> readIORef var)
200 Getting the environment
203 getEnv :: TcRn m (Env m)
204 {-# INLINE getEnv #-}
205 getEnv = TcRn (\ env -> return env)
207 setEnv :: Env n -> TcRn n a -> TcRn m a
208 {-# INLINE setEnv #-}
209 setEnv new_env (TcRn m) = TcRn (\ env -> m new_env)
211 updEnv :: (Env m -> Env n) -> TcRn n a -> TcRn m a
212 {-# INLINE updEnv #-}
213 updEnv upd (TcRn m) = TcRn (\ env -> m (upd env))
217 zapEnv :: TcRn m a -> TcRn m a
218 zapEnv act = TcRn $ \env@Env{ env_top=top, env_gbl=gbl, env_lcl=lcl } ->
228 eps_snap <- readIORef eps
229 ref <- newIORef $! emptyExternalPackageState{ eps_PTE = eps_PTE eps_snap }
240 type_env = tcg_type_env gbl
244 tcg_type_env = type_env
251 -- leave the rest empty
254 case act of { TcRn f -> f env' }
258 %************************************************************************
260 The main environment types
262 %************************************************************************
265 data Env a -- Changes as we move into an expression
267 env_top :: TopEnv, -- Top-level stuff that never changes
268 -- Mainly a bunch of updatable refs
269 -- Includes all info about imported things
270 env_gbl :: TcGblEnv, -- Info about things defined at the top leve
271 -- of the module being compiled
273 env_lcl :: a, -- Different for the type checker
276 env_loc :: SrcLoc -- Source location
279 data TopEnv -- Built once at top level then does not change
280 -- Concerns imported stuff
281 -- Exceptions: error recovery points, meta computation points
283 top_mode :: GhciMode,
284 top_dflags :: DynFlags,
286 -- Stuff about imports
287 top_eps :: TcRef ExternalPackageState,
288 -- PIT, ImportedModuleInfo
289 -- DeclsMap, IfaceRules, IfaceInsts, InstGates
290 -- TypeEnv, InstEnv, RuleBase
291 -- Mutable, because we demand-load declarations that extend the state
293 top_hpt :: HomePackageTable,
294 -- The home package table that we've accumulated while
295 -- compiling the home package,
296 -- *excluding* the module we are compiling right now.
297 -- (In one-shot mode the current module is the only
298 -- home-package module, so tc_hpt is empty. All other
299 -- modules count as "external-package" modules.)
300 -- tc_hpt is not mutable because we only demand-load
301 -- external packages; the home package is eagerly
302 -- loaded by the compilation manager.
304 -- The global name supply
305 top_nc :: TcRef NameCache, -- Maps original names to Names
306 top_us :: TcRef UniqSupply, -- Unique supply for this module
307 top_errs :: TcRef Messages
310 -- TcGblEnv describes the top-level of the module at the
311 -- point at which the typechecker is finished work.
312 -- It is this structure that is handed on to the desugarer
316 tcg_mod :: Module, -- Module being compiled
317 tcg_usages :: TcRef EntityUsage, -- What version of what entities
318 -- have been used from other home-pkg modules
319 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
320 tcg_fix_env :: FixityEnv, -- Ditto
321 tcg_default :: [Type], -- Types used for defaulting
323 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
324 -- All TyCons and Classes (for this module) end up in here right away,
325 -- along with their derived constructors, selectors.
327 -- (Ids defined in this module start in the local envt,
328 -- though they move to the global envt during zonking)
330 tcg_inst_env :: TcRef InstEnv, -- Global instance env: a combination of
331 -- tc_pcs, tc_hpt, *and* tc_insts
332 -- This field is mutable so that it can be updated inside a
333 -- Template Haskell splice, which might suck in some new
334 -- instance declarations. This is a slightly different strategy
335 -- than for the type envt, where we look up first in tcg_type_env
336 -- and then in the mutable EPS, because the InstEnv for this module
337 -- is constructed (in principle at least) only from the modules
338 -- 'below' this one, so it's this-module-specific
340 -- On the other hand, a declaration quote [d| ... |] may introduce
341 -- some new instance declarations that we *don't* want to persist
342 -- outside the quote, so we tiresomely need to revert the InstEnv
343 -- after finishing the quote (see TcSplice.tcBracket)
345 -- Now a bunch of things about this module that are simply
346 -- accumulated, but never consulted until the end.
347 -- Nevertheless, it's convenient to accumulate them along
348 -- with the rest of the info from this module.
349 tcg_exports :: Avails, -- What is exported
350 tcg_imports :: ImportAvails, -- Information about what was imported
351 -- from where, including things bound
354 -- The next fields accumulate the payload of the module
355 -- The binds, rules and foreign-decl fiels are collected
356 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
357 tcg_binds :: MonoBinds Id, -- Value bindings in this module
358 tcg_deprecs :: Deprecations, -- ...Deprecations
359 tcg_insts :: [DFunId], -- ...Instances
360 tcg_rules :: [RuleDecl Id], -- ...Rules
361 tcg_fords :: [ForeignDecl Id] -- ...Foreign import & exports
366 %************************************************************************
368 The local typechecker environment
370 %************************************************************************
372 The Global-Env/Local-Env story
373 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
374 During type checking, we keep in the tcg_type_env
375 * All types and classes
376 * All Ids derived from types and classes (constructors, selectors)
378 At the end of type checking, we zonk the local bindings,
379 and as we do so we add to the tcg_type_env
380 * Locally defined top-level Ids
382 Why? Because they are now Ids not TcIds. This final GlobalEnv is
383 a) fed back (via the knot) to typechecking the
384 unfoldings of interface signatures
385 b) used in the ModDetails of this module
390 tcl_ctxt :: ErrCtxt, -- Error context
392 tcl_level :: Stage, -- Template Haskell context
394 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
395 -- defined in this module
397 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
398 -- Namely, the in-scope TyVars bound in tcl_lenv,
399 -- plus the tyvars mentioned in the types of
400 -- Ids bound in tcl_lenv
401 -- Why mutable? see notes with tcGetGlobalTyVars
403 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
409 = Comp -- Ordinary compiling, at level topLevel
410 | Splice Level -- Inside a splice
411 | Brack Level -- Inside brackets;
412 (TcRef [PendingSplice]) -- accumulate pending splices here
413 (TcRef LIE) -- and type constraints here
414 topStage, topSpliceStage :: Stage
416 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
419 impLevel, topLevel :: Level
420 topLevel = 1 -- Things defined at top level of this module
421 impLevel = 0 -- Imported things; they can be used inside a top level splice
425 -- g1 = $(map ...) is OK
426 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
429 = AGlobal TyThing -- Used only in the return type of a lookup
430 | ATcId TcId Level -- Ids defined in this module; may not be fully zonked
431 | ATyVar TyVar -- Type variables
432 | AThing TcKind -- Used temporarily, during kind checking
433 -- Here's an example of how the AThing guy is used
434 -- Suppose we are checking (forall a. T a Int):
435 -- 1. We first bind (a -> AThink kv), where kv is a kind variable.
436 -- 2. Then we kind-check the (T a Int) part.
437 -- 3. Then we zonk the kind variable.
438 -- 4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
440 instance Outputable TcTyThing where -- Debugging only
441 ppr (AGlobal g) = text "AGlobal" <+> ppr g
442 ppr (ATcId g l) = text "ATcId" <+> ppr g <+> ppr l
443 ppr (ATyVar t) = text "ATyVar" <+> ppr t
444 ppr (AThing k) = text "AThing" <+> ppr k
448 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
449 -- Innermost first. Monadic so that we have a chance
450 -- to deal with bound type variables just before error
451 -- message construction
455 %************************************************************************
457 The local renamer environment
459 %************************************************************************
465 rn_lenv :: LocalRdrEnv -- Local name envt
466 -- Does *not* include global name envt; may shadow it
467 -- Includes both ordinary variables and type variables;
468 -- they are kept distinct because tyvar have a different
469 -- occurrence contructor (Name.TvOcc)
470 -- We still need the unsullied global name env so that
471 -- we can look up record field names
474 data RnMode = SourceMode -- Renaming source code
475 | InterfaceMode Module -- Renaming interface declarations from M
476 | CmdLineMode -- Renaming a command-line expression
478 isInterfaceMode (InterfaceMode _) = True
479 isInterfaceMode _ = False
481 isCmdLineMode CmdLineMode = True
482 isCmdLineMode _ = False
486 %************************************************************************
490 %************************************************************************
492 EntityUsage tells what things are actually need in order to compile this
493 module. It is used for generating the usage-version field of the ModIface.
495 Note that we do not record version info for entities from
496 other (non-home) packages. If the package changes, GHC doesn't help.
499 type EntityUsage = NameSet
500 -- The Names are all the (a) home-package
501 -- (b) "big" (i.e. no data cons, class ops)
502 -- (c) non-locally-defined
504 -- names that have been slurped in so far.
505 -- This is used to generate the "usage" information for this module.
507 emptyUsages :: EntityUsage
508 emptyUsages = emptyNameSet
512 %************************************************************************
514 Operations over ImportAvails
516 %************************************************************************
518 ImportAvails summarises what was imported from where, irrespective
519 of whether the imported htings are actually used or not
520 It is used * when processing the export list
521 * when constructing usage info for the inteface file
522 * to identify the list of directly imported modules
523 for initialisation purposes
524 * when figuring out what things are really unused
530 -- All the things that are available from the import
531 -- Its domain is all the "main" things;
532 -- i.e. *excluding* class ops and constructors
533 -- (which appear inside their parent AvailTC)
535 imp_qual :: ModuleEnv AvailEnv,
536 -- Used to figure out "module M" export specifiers
537 -- (see 1.4 Report Section 5.1.1). Ultimately, we want to find
538 -- everything that is unambiguously in scope as 'M.x'
539 -- and where plain 'x' is (perhaps ambiguously) in scope.
540 -- So the starting point is all things that are in scope as 'M.x',
541 -- which is what this field tells us.
543 -- Domain is the *module qualifier* for imports.
544 -- e.g. import List as Foo
545 -- would add a binding Foo |-> ...stuff from List...
547 -- We keep the stuff as an AvailEnv so that it's easy to
548 -- combine stuff coming from different (unqualified)
549 -- imports of the same module
551 imp_mods :: ModuleEnv (Module, Bool),
552 -- Domain is all directly-imported modules
553 -- Bool is True if there was an unrestricted import
554 -- (i.e. not a selective list)
555 -- We need the Module in the range because we can't get
556 -- the keys of a ModuleEnv
558 -- (a) to help construct the usage information in
559 -- the interface file; if we import everything we
560 -- need to recompile if the module version changes
561 -- (b) to specify what child modules to initialise
563 imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
564 -- Home-package modules needed by the module being compiled
566 -- It doesn't matter whether any of these dependencies are actually
567 -- *used* when compiling the module; they are listed if they are below
568 -- it at all. For example, suppose M imports A which imports X. Then
569 -- compiling M might not need to consult X.hi, but X is still listed
570 -- in M's dependencies.
572 imp_dep_pkgs :: [PackageName],
573 -- Packages needed by the module being compiled, whether
574 -- directly, or via other modules in this package, or via
575 -- modules imported from other packages.
577 imp_orphs :: [ModuleName]
578 -- Orphan modules below us in the import tree
581 emptyImportAvails :: ImportAvails
582 emptyImportAvails = ImportAvails { imp_env = emptyAvailEnv,
583 imp_qual = emptyModuleEnv,
584 imp_mods = emptyModuleEnv,
585 imp_dep_mods = emptyModuleEnv,
589 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
591 (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
592 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
593 (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
594 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
595 = ImportAvails { imp_env = env1 `plusAvailEnv` env2,
596 imp_qual = plusModuleEnv_C plusAvailEnv unqual1 unqual2,
597 imp_mods = mods1 `plusModuleEnv` mods2,
598 imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,
599 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
600 imp_orphs = orphs1 `unionLists` orphs2 }
602 plus_mod_dep (m1, boot1) (m2, boot2)
603 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
604 -- Check mod-names match
605 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
608 %************************************************************************
610 Avails, AvailEnv, etc
612 v%************************************************************************
615 plusAvail (Avail n1) (Avail n2) = Avail n1
616 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
619 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
622 -------------------------
623 pruneAvails :: (Name -> Bool) -- Keep if this is True
626 pruneAvails keep avails
627 = mapMaybe del avails
629 del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
630 del (Avail n) | keep n = Just (Avail n)
631 | otherwise = Nothing
632 del (AvailTC n ns) | null ns' = Nothing
633 | otherwise = Just (AvailTC n ns')
638 ---------------------------------------
640 ---------------------------------------
643 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
645 emptyAvailEnv :: AvailEnv
646 emptyAvailEnv = emptyNameEnv
648 unitAvailEnv :: AvailInfo -> AvailEnv
649 unitAvailEnv a = unitNameEnv (availName a) a
651 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
652 plusAvailEnv = plusNameEnv_C plusAvail
654 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
655 lookupAvailEnv_maybe = lookupNameEnv
657 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
658 lookupAvailEnv env n = case lookupNameEnv env n of
660 Nothing -> pprPanic "lookupAvailEnv" (ppr n)
662 availEnvElts = nameEnvElts
664 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
665 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
667 mkAvailEnv :: [AvailInfo] -> AvailEnv
668 -- 'avails' may have several items with the same availName
669 -- E.g import Ix( Ix(..), index )
670 -- will give Ix(Ix,index,range) and Ix(index)
671 -- We want to combine these; addAvail does that
672 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
675 %************************************************************************
677 \subsection{Where from}
679 %************************************************************************
681 The @WhereFrom@ type controls where the renamer looks for an interface file
685 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
687 | ImportForUsage IsBootInterface -- Import when chasing usage info from an interaface file
688 -- Failure in this case is not an error
690 | ImportBySystem -- Non user import.
692 instance Outputable WhereFrom where
693 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
695 ppr (ImportForUsage is_boot) | is_boot = ptext SLIT("{- USAGE SOURCE -}")
696 | otherwise = ptext SLIT("{- USAGE -}")
697 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
701 %************************************************************************
703 \subsection[Inst-types]{@Inst@ types}
705 v%************************************************************************
707 An @Inst@ is either a dictionary, an instance of an overloaded
708 literal, or an instance of an overloaded value. We call the latter a
709 ``method'' even though it may not correspond to a class operation.
710 For example, we might have an instance of the @double@ function at
711 type Int, represented by
713 Method 34 doubleId [Int] origin
725 TcId -- The overloaded function
726 -- This function will be a global, local, or ClassOpId;
727 -- inside instance decls (only) it can also be an InstId!
728 -- The id needn't be completely polymorphic.
729 -- You'll probably find its name (for documentation purposes)
730 -- inside the InstOrigin
732 [TcType] -- The types to which its polymorphic tyvars
733 -- should be instantiated.
734 -- These types must saturate the Id's foralls.
736 TcThetaType -- The (types of the) dictionaries to which the function
737 -- must be applied to get the method
739 TcTauType -- The tau-type of the method
743 -- INVARIANT 1: in (Method u f tys theta tau loc)
744 -- type of (f tys dicts(from theta)) = tau
746 -- INVARIANT 2: tau must not be of form (Pred -> Tau)
747 -- Reason: two methods are considerd equal if the
748 -- base Id matches, and the instantiating types
749 -- match. The TcThetaType should then match too.
750 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
754 HsOverLit -- The literal from the occurrence site
755 -- INVARIANT: never a rebindable-syntax literal
756 -- Reason: tcSyntaxName does unification, and we
757 -- don't want to deal with that during tcSimplify
758 TcType -- The type at which the literal is used
762 @Insts@ are ordered by their class/type info, rather than by their
763 unique. This allows the context-reduction mechanism to use standard finite
764 maps to do their stuff.
767 instance Ord Inst where
770 instance Eq Inst where
771 (==) i1 i2 = case i1 `cmpInst` i2 of
775 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
776 cmpInst (Dict _ _ _) other = LT
778 cmpInst (Method _ _ _ _ _ _) (Dict _ _ _) = GT
779 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
780 cmpInst (Method _ _ _ _ _ _) other = LT
782 cmpInst (LitInst _ _ _ _) (Dict _ _ _) = GT
783 cmpInst (LitInst _ _ _ _) (Method _ _ _ _ _ _) = GT
784 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
788 %************************************************************************
790 \subsection[Inst-collections]{LIE: a collection of Insts}
792 %************************************************************************
797 isEmptyLIE = isEmptyBag
799 unitLIE inst = unitBag inst
800 mkLIE insts = listToBag insts
801 plusLIE lie1 lie2 = lie1 `unionBags` lie2
802 consLIE inst lie = inst `consBag` lie
803 plusLIEs lies = unionManyBags lies
804 lieToList = bagToList
805 listToLIE = listToBag
809 %************************************************************************
811 \subsection[Inst-origin]{The @InstOrigin@ type}
813 %************************************************************************
815 The @InstOrigin@ type gives information about where a dictionary came from.
816 This is important for decent error message reporting because dictionaries
817 don't appear in the original source code. Doubtless this type will evolve...
819 It appears in TcMonad because there are a couple of error-message-generation
820 functions that deal with it.
823 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
825 instLocSrcLoc :: InstLoc -> SrcLoc
826 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
829 = OccurrenceOf Name -- Occurrence of an overloaded identifier
831 | IPOcc (IPName Name) -- Occurrence of an implicit parameter
832 | IPBind (IPName Name) -- Binding site of an implicit parameter
836 | DataDeclOrigin -- Typechecking a data declaration
838 | InstanceDeclOrigin -- Typechecking an instance decl
840 | LiteralOrigin HsOverLit -- Occurrence of a literal
842 | PatOrigin RenamedPat
844 | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
845 | PArrSeqOrigin RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
847 | SignatureOrigin -- A dict created from a type signature
848 | Rank2Origin -- A dict created when typechecking the argument
849 -- of a rank-2 typed function
851 | DoOrigin -- The monad for a do expression
853 | ClassDeclOrigin -- Manufactured during a class decl
855 | InstanceSpecOrigin Class -- in a SPECIALIZE instance pragma
858 -- When specialising instances the instance info attached to
859 -- each class is not yet ready, so we record it inside the
860 -- origin information. This is a bit of a hack, but it works
861 -- fine. (Patrick is to blame [WDP].)
863 | ValSpecOrigin Name -- in a SPECIALIZE pragma for a value
865 -- Argument or result of a ccall
866 -- Dictionaries with this origin aren't actually mentioned in the
867 -- translated term, and so need not be bound. Nor should they
868 -- be abstracted over.
870 | CCallOrigin String -- CCall label
871 (Maybe RenamedHsExpr) -- Nothing if it's the result
872 -- Just arg, for an argument
874 | LitLitOrigin String -- the litlit
876 | UnknownOrigin -- Help! I give up...
880 pprInstLoc :: InstLoc -> SDoc
881 pprInstLoc (InstLoc orig locn ctxt)
882 = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
884 pp_orig (OccurrenceOf name)
885 = hsep [ptext SLIT("use of"), quotes (ppr name)]
887 = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
888 pp_orig (IPBind name)
889 = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
890 pp_orig RecordUpdOrigin
891 = ptext SLIT("a record update")
892 pp_orig DataDeclOrigin
893 = ptext SLIT("the data type declaration")
894 pp_orig InstanceDeclOrigin
895 = ptext SLIT("the instance declaration")
896 pp_orig (LiteralOrigin lit)
897 = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
898 pp_orig (PatOrigin pat)
899 = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
900 pp_orig (ArithSeqOrigin seq)
901 = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
902 pp_orig (PArrSeqOrigin seq)
903 = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
904 pp_orig (SignatureOrigin)
905 = ptext SLIT("a type signature")
906 pp_orig (Rank2Origin)
907 = ptext SLIT("a function with an overloaded argument type")
909 = ptext SLIT("a do statement")
910 pp_orig (ClassDeclOrigin)
911 = ptext SLIT("a class declaration")
912 pp_orig (InstanceSpecOrigin clas ty)
913 = hsep [text "a SPECIALIZE instance pragma; class",
914 quotes (ppr clas), text "type:", ppr ty]
915 pp_orig (ValSpecOrigin name)
916 = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
917 pp_orig (CCallOrigin clabel Nothing{-ccall result-})
918 = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
919 pp_orig (CCallOrigin clabel (Just arg_expr))
920 = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma,
921 text "namely", quotes (ppr arg_expr)]
922 pp_orig (LitLitOrigin s)
923 = hsep [ptext SLIT("the ``literal-literal''"), quotes (text s)]
924 pp_orig (UnknownOrigin)
925 = ptext SLIT("...oops -- I don't know where the overloading came from!")