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 ThStage(..), topStage, topSpliceStage,
34 ThLevel, impLevel, topLevel,
37 ArrowCtxt(..), topArrowCtxt, ProcLevel, topProcLevel,
40 Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, instLocSrcLoc,
41 LIE, emptyLIE, unitLIE, plusLIE, consLIE,
42 plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
48 #include "HsVersions.h"
50 import HsSyn ( PendingSplice, HsOverLit, MonoBinds, RuleDecl, ForeignDecl )
51 import RnHsSyn ( RenamedHsExpr, RenamedPat, RenamedArithSeqInfo )
52 import HscTypes ( GhciMode, ExternalPackageState, HomePackageTable,
53 NameCache, GlobalRdrEnv, LocalRdrEnv, FixityEnv,
54 TypeEnv, TyThing, Avails, GenAvailInfo(..), AvailInfo,
55 availName, IsBootInterface, Deprecations,
56 ExternalPackageState(..), emptyExternalPackageState )
57 import Packages ( PackageName )
58 import TcType ( TcTyVarSet, TcType, TcTauType, TcThetaType,
59 TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes )
60 import InstEnv ( DFunId, InstEnv )
63 import NameSet ( NameSet, emptyNameSet )
65 import Class ( Class )
66 import Var ( Id, TyVar )
67 import VarEnv ( TidyEnv )
69 import SrcLoc ( SrcLoc )
70 import VarSet ( IdSet )
71 import ErrUtils ( Messages, Message )
72 import CmdLineOpts ( DynFlags )
73 import UniqSupply ( UniqSupply )
74 import BasicTypes ( IPName )
75 import Util ( thenCmp )
78 import DATA_IOREF ( IORef, newIORef, readIORef, writeIORef )
79 import UNSAFE_IO ( unsafeInterleaveIO )
80 import FIX_IO ( fixIO )
81 import EXCEPTION ( Exception(..) )
82 import IO ( isUserError )
83 import Maybe ( mapMaybe )
84 import ListSetOps ( unionLists )
85 import Panic ( tryJust )
90 type TcRef a = IORef a
91 type TcId = Id -- Type may be a TcType
95 %************************************************************************
97 Standard monad definition for TcRn
98 All the combinators for the monad can be found in TcRnMonad
100 %************************************************************************
102 The monad itself has to be defined here,
103 because it is mentioned by ErrCtxt
106 newtype TcRn m a = TcRn (Env m -> IO a)
109 type TcM a = TcRn TcLclEnv a
110 type RnM a = TcRn RnLclEnv a
112 returnM :: a -> TcRn m a
113 returnM a = TcRn (\ env -> return a)
115 thenM :: TcRn m a -> (a -> TcRn m b) -> TcRn m b
116 thenM (TcRn m) f = TcRn (\ env -> do { r <- m env ;
119 thenM_ :: TcRn m a -> TcRn m b -> TcRn m b
120 thenM_ (TcRn m) f = TcRn (\ env -> do { m env ; unTcRn f env })
123 failM = TcRn (\ env -> ioError (userError "TcRn failure"))
125 instance Monad (TcRn m) where
129 fail s = failM -- Ignore the string
133 %************************************************************************
135 Fundmantal combinators specific to the monad
137 %************************************************************************
142 runTcRn :: Env m -> TcRn m a -> IO a
143 runTcRn env (TcRn m) = m env
146 The fixpoint combinator
149 {-# NOINLINE fixM #-}
150 -- Aargh! Not inlining fixTc alleviates a space leak problem.
151 -- Normally fixTc is used with a lazy tuple match: if the optimiser is
152 -- shown the definition of fixTc, it occasionally transforms the code
153 -- in such a way that the code generator doesn't spot the selector
156 fixM :: (a -> TcRn m a) -> TcRn m a
157 fixM f = TcRn (\ env -> fixIO (\ r -> unTcRn (f r) env))
163 tryM :: TcRn m r -> TcRn m (Either Exception r)
164 -- Reflect exception into TcRn monad
165 tryM (TcRn thing) = TcRn (\ env -> tryJust tc_errors (thing env))
167 #if __GLASGOW_HASKELL__ > 504 || __GLASGOW_HASKELL__ < 500
168 tc_errors e@(IOException ioe) | isUserError ioe = Just e
169 #elif __GLASGOW_HASKELL__ == 502
170 tc_errors e@(UserError _) = Just e
172 tc_errors e@(IOException ioe) | isUserError e = Just e
174 tc_errors _other = Nothing
175 -- type checker failures show up as UserErrors only
181 unsafeInterleaveM :: TcRn m a -> TcRn m a
182 unsafeInterleaveM (TcRn m) = TcRn (\ env -> unsafeInterleaveIO (m env))
187 Performing arbitrary I/O, plus the read/write var (for efficiency)
190 ioToTcRn :: IO a -> TcRn m a
191 ioToTcRn io = TcRn (\ env -> io)
193 newMutVar :: a -> TcRn m (TcRef a)
194 newMutVar val = TcRn (\ env -> newIORef val)
196 writeMutVar :: TcRef a -> a -> TcRn m ()
197 writeMutVar var val = TcRn (\ env -> writeIORef var val)
199 readMutVar :: TcRef a -> TcRn m a
200 readMutVar var = TcRn (\ env -> readIORef var)
203 Getting the environment
206 getEnv :: TcRn m (Env m)
207 {-# INLINE getEnv #-}
208 getEnv = TcRn (\ env -> return env)
210 setEnv :: Env n -> TcRn n a -> TcRn m a
211 {-# INLINE setEnv #-}
212 setEnv new_env (TcRn m) = TcRn (\ env -> m new_env)
214 updEnv :: (Env m -> Env n) -> TcRn n a -> TcRn m a
215 {-# INLINE updEnv #-}
216 updEnv upd (TcRn m) = TcRn (\ env -> m (upd env))
220 zapEnv :: TcRn m a -> TcRn m a
221 zapEnv act = TcRn $ \env@Env{ env_top=top, env_gbl=gbl, env_lcl=lcl } ->
231 eps_snap <- readIORef eps
232 ref <- newIORef $! emptyExternalPackageState{ eps_PTE = eps_PTE eps_snap }
243 type_env = tcg_type_env gbl
247 tcg_type_env = type_env
254 -- leave the rest empty
257 case act of { TcRn f -> f env' }
261 %************************************************************************
263 The main environment types
265 %************************************************************************
268 data Env a -- Changes as we move into an expression
270 env_top :: TopEnv, -- Top-level stuff that never changes
271 -- Mainly a bunch of updatable refs
272 -- Includes all info about imported things
273 env_gbl :: TcGblEnv, -- Info about things defined at the top leve
274 -- of the module being compiled
276 env_lcl :: a, -- Different for the type checker
279 env_loc :: SrcLoc -- Source location
282 data TopEnv -- Built once at top level then does not change
283 -- Concerns imported stuff
284 -- Exceptions: error recovery points, meta computation points
286 top_mode :: GhciMode,
287 top_dflags :: DynFlags,
289 -- Stuff about imports
290 top_eps :: TcRef ExternalPackageState,
291 -- PIT, ImportedModuleInfo
292 -- DeclsMap, IfaceRules, IfaceInsts, InstGates
293 -- TypeEnv, InstEnv, RuleBase
294 -- Mutable, because we demand-load declarations that extend the state
296 top_hpt :: HomePackageTable,
297 -- The home package table that we've accumulated while
298 -- compiling the home package,
299 -- *excluding* the module we are compiling right now.
300 -- (In one-shot mode the current module is the only
301 -- home-package module, so tc_hpt is empty. All other
302 -- modules count as "external-package" modules.)
303 -- tc_hpt is not mutable because we only demand-load
304 -- external packages; the home package is eagerly
305 -- loaded by the compilation manager.
307 -- The global name supply
308 top_nc :: TcRef NameCache, -- Maps original names to Names
309 top_us :: TcRef UniqSupply, -- Unique supply for this module
310 top_errs :: TcRef Messages
313 -- TcGblEnv describes the top-level of the module at the
314 -- point at which the typechecker is finished work.
315 -- It is this structure that is handed on to the desugarer
319 tcg_mod :: Module, -- Module being compiled
320 tcg_usages :: TcRef EntityUsage, -- What version of what entities
321 -- have been used from other home-pkg modules
322 tcg_rdr_env :: GlobalRdrEnv, -- Top level envt; used during renaming
323 tcg_fix_env :: FixityEnv, -- Ditto
324 tcg_default :: [Type], -- Types used for defaulting
326 tcg_type_env :: TypeEnv, -- Global type env for the module we are compiling now
327 -- All TyCons and Classes (for this module) end up in here right away,
328 -- along with their derived constructors, selectors.
330 -- (Ids defined in this module start in the local envt,
331 -- though they move to the global envt during zonking)
333 tcg_inst_env :: TcRef InstEnv, -- Global instance env: a combination of
334 -- tc_pcs, tc_hpt, *and* tc_insts
335 -- This field is mutable so that it can be updated inside a
336 -- Template Haskell splice, which might suck in some new
337 -- instance declarations. This is a slightly different strategy
338 -- than for the type envt, where we look up first in tcg_type_env
339 -- and then in the mutable EPS, because the InstEnv for this module
340 -- is constructed (in principle at least) only from the modules
341 -- 'below' this one, so it's this-module-specific
343 -- On the other hand, a declaration quote [d| ... |] may introduce
344 -- some new instance declarations that we *don't* want to persist
345 -- outside the quote, so we tiresomely need to revert the InstEnv
346 -- after finishing the quote (see TcSplice.tcBracket)
348 -- Now a bunch of things about this module that are simply
349 -- accumulated, but never consulted until the end.
350 -- Nevertheless, it's convenient to accumulate them along
351 -- with the rest of the info from this module.
352 tcg_exports :: Avails, -- What is exported
353 tcg_imports :: ImportAvails, -- Information about what was imported
354 -- from where, including things bound
357 -- The next fields accumulate the payload of the module
358 -- The binds, rules and foreign-decl fiels are collected
359 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
360 tcg_binds :: MonoBinds Id, -- Value bindings in this module
361 tcg_deprecs :: Deprecations, -- ...Deprecations
362 tcg_insts :: [DFunId], -- ...Instances
363 tcg_rules :: [RuleDecl Id], -- ...Rules
364 tcg_fords :: [ForeignDecl Id] -- ...Foreign import & exports
369 %************************************************************************
371 The local typechecker environment
373 %************************************************************************
375 The Global-Env/Local-Env story
376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
377 During type checking, we keep in the tcg_type_env
378 * All types and classes
379 * All Ids derived from types and classes (constructors, selectors)
381 At the end of type checking, we zonk the local bindings,
382 and as we do so we add to the tcg_type_env
383 * Locally defined top-level Ids
385 Why? Because they are now Ids not TcIds. This final GlobalEnv is
386 a) fed back (via the knot) to typechecking the
387 unfoldings of interface signatures
388 b) used in the ModDetails of this module
393 tcl_ctxt :: ErrCtxt, -- Error context
395 tcl_th_ctxt :: ThStage, -- Template Haskell context
396 tcl_arrow_ctxt :: ArrowCtxt, -- Arrow-notation context
398 tcl_env :: NameEnv TcTyThing, -- The local type environment: Ids and TyVars
399 -- defined in this module
401 tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
402 -- Namely, the in-scope TyVars bound in tcl_lenv,
403 -- plus the tyvars mentioned in the types of
404 -- Ids bound in tcl_lenv
405 -- Why mutable? see notes with tcGetGlobalTyVars
407 tcl_lie :: TcRef LIE -- Place to accumulate type constraints
410 ---------------------------
411 -- Template Haskell levels
412 ---------------------------
414 type ThLevel = Int -- Always >= 0
417 = Comp -- Ordinary compiling, at level topLevel
418 | Splice ThLevel -- Inside a splice
419 | Brack ThLevel -- Inside brackets;
420 (TcRef [PendingSplice]) -- accumulate pending splices here
421 (TcRef LIE) -- and type constraints here
422 topStage, topSpliceStage :: ThStage
424 topSpliceStage = Splice (topLevel - 1) -- Stage for the body of a top-level splice
427 impLevel, topLevel :: ThLevel
428 topLevel = 1 -- Things defined at top level of this module
429 impLevel = 0 -- Imported things; they can be used inside a top level splice
433 -- g1 = $(map ...) is OK
434 -- g2 = $(f ...) is not OK; because we havn't compiled f yet
437 ---------------------------
438 -- Arrow-notation stages
439 ---------------------------
441 -- In arrow notation, a variable bound by a proc (or enclosed let/kappa)
442 -- is not in scope to the left of an arrow tail (-<). For example
444 -- proc x -> (e1 -< e2)
446 -- Here, x is not in scope in e1, but it is in scope in e2. This can get
447 -- a bit complicated:
450 -- prox y -> (proc z -> e1) -< e2
452 -- Here, x and z are in scope in e1, but y is not. Here's how we track this:
453 -- a) Assign an "proc level" to each proc, being the number of
454 -- lexically-enclosing procs + 1.
455 -- b) Assign to each local variable the proc-level of its lexically
457 -- c) Keep a list of out-of-scope procs. When moving to the left of
458 -- an arrow-tail, add the proc-level of the immediately enclosing
460 -- d) When looking up a variable, complain if its proc-level is in
463 type ProcLevel = Int -- Always >= 0
464 topProcLevel = 0 -- Not inside any proc
466 data ArrowCtxt = ArrCtxt { proc_level :: ProcLevel, -- Current level
467 proc_banned :: [ProcLevel] } -- Out of scope proc-levels
469 topArrowCtxt = ArrCtxt { proc_level = topProcLevel, proc_banned = [] }
471 ---------------------------
473 ---------------------------
476 = AGlobal TyThing -- Used only in the return type of a lookup
477 | ATcId TcId ThLevel ProcLevel -- Ids defined in this module; may not be fully zonked
478 | ATyVar TyVar -- Type variables
479 | AThing TcKind -- Used temporarily, during kind checking
480 -- Here's an example of how the AThing guy is used
481 -- Suppose we are checking (forall a. T a Int):
482 -- 1. We first bind (a -> AThink kv), where kv is a kind variable.
483 -- 2. Then we kind-check the (T a Int) part.
484 -- 3. Then we zonk the kind variable.
485 -- 4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
487 instance Outputable TcTyThing where -- Debugging only
488 ppr (AGlobal g) = text "AGlobal" <+> ppr g
489 ppr (ATcId g tl pl) = text "ATcId" <+> ppr g <+> ppr tl <+> ppr pl
490 ppr (ATyVar t) = text "ATyVar" <+> ppr t
491 ppr (AThing k) = text "AThing" <+> ppr k
495 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]
496 -- Innermost first. Monadic so that we have a chance
497 -- to deal with bound type variables just before error
498 -- message construction
502 %************************************************************************
504 The local renamer environment
506 %************************************************************************
512 rn_lenv :: LocalRdrEnv -- Local name envt
513 -- Does *not* include global name envt; may shadow it
514 -- Includes both ordinary variables and type variables;
515 -- they are kept distinct because tyvar have a different
516 -- occurrence contructor (Name.TvOcc)
517 -- We still need the unsullied global name env so that
518 -- we can look up record field names
521 data RnMode = SourceMode -- Renaming source code
522 | InterfaceMode Module -- Renaming interface declarations from M
523 | CmdLineMode -- Renaming a command-line expression
525 isInterfaceMode (InterfaceMode _) = True
526 isInterfaceMode _ = False
528 isCmdLineMode CmdLineMode = True
529 isCmdLineMode _ = False
533 %************************************************************************
537 %************************************************************************
539 EntityUsage tells what things are actually need in order to compile this
540 module. It is used for generating the usage-version field of the ModIface.
542 Note that we do not record version info for entities from
543 other (non-home) packages. If the package changes, GHC doesn't help.
546 type EntityUsage = NameSet
547 -- The Names are all the (a) home-package
548 -- (b) "big" (i.e. no data cons, class ops)
549 -- (c) non-locally-defined
551 -- names that have been slurped in so far.
552 -- This is used to generate the "usage" information for this module.
554 emptyUsages :: EntityUsage
555 emptyUsages = emptyNameSet
559 %************************************************************************
561 Operations over ImportAvails
563 %************************************************************************
565 ImportAvails summarises what was imported from where, irrespective
566 of whether the imported htings are actually used or not
567 It is used * when processing the export list
568 * when constructing usage info for the inteface file
569 * to identify the list of directly imported modules
570 for initialisation purposes
571 * when figuring out what things are really unused
577 -- All the things that are available from the import
578 -- Its domain is all the "main" things;
579 -- i.e. *excluding* class ops and constructors
580 -- (which appear inside their parent AvailTC)
582 imp_qual :: ModuleEnv AvailEnv,
583 -- Used to figure out "module M" export specifiers
584 -- (see 1.4 Report Section 5.1.1). Ultimately, we want to find
585 -- everything that is unambiguously in scope as 'M.x'
586 -- and where plain 'x' is (perhaps ambiguously) in scope.
587 -- So the starting point is all things that are in scope as 'M.x',
588 -- which is what this field tells us.
590 -- Domain is the *module qualifier* for imports.
591 -- e.g. import List as Foo
592 -- would add a binding Foo |-> ...stuff from List...
594 -- We keep the stuff as an AvailEnv so that it's easy to
595 -- combine stuff coming from different (unqualified)
596 -- imports of the same module
598 imp_mods :: ModuleEnv (Module, Bool),
599 -- Domain is all directly-imported modules
600 -- Bool is True if there was an unrestricted import
601 -- (i.e. not a selective list)
602 -- We need the Module in the range because we can't get
603 -- the keys of a ModuleEnv
605 -- (a) to help construct the usage information in
606 -- the interface file; if we import everything we
607 -- need to recompile if the module version changes
608 -- (b) to specify what child modules to initialise
610 imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
611 -- Home-package modules needed by the module being compiled
613 -- It doesn't matter whether any of these dependencies are actually
614 -- *used* when compiling the module; they are listed if they are below
615 -- it at all. For example, suppose M imports A which imports X. Then
616 -- compiling M might not need to consult X.hi, but X is still listed
617 -- in M's dependencies.
619 imp_dep_pkgs :: [PackageName],
620 -- Packages needed by the module being compiled, whether
621 -- directly, or via other modules in this package, or via
622 -- modules imported from other packages.
624 imp_orphs :: [ModuleName]
625 -- Orphan modules below us in the import tree
628 emptyImportAvails :: ImportAvails
629 emptyImportAvails = ImportAvails { imp_env = emptyAvailEnv,
630 imp_qual = emptyModuleEnv,
631 imp_mods = emptyModuleEnv,
632 imp_dep_mods = emptyModuleEnv,
636 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
638 (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
639 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
640 (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
641 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
642 = ImportAvails { imp_env = env1 `plusAvailEnv` env2,
643 imp_qual = plusModuleEnv_C plusAvailEnv unqual1 unqual2,
644 imp_mods = mods1 `plusModuleEnv` mods2,
645 imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,
646 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
647 imp_orphs = orphs1 `unionLists` orphs2 }
649 plus_mod_dep (m1, boot1) (m2, boot2)
650 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
651 -- Check mod-names match
652 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
655 %************************************************************************
657 Avails, AvailEnv, etc
659 v%************************************************************************
662 plusAvail (Avail n1) (Avail n2) = Avail n1
663 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
666 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
669 -------------------------
670 pruneAvails :: (Name -> Bool) -- Keep if this is True
673 pruneAvails keep avails
674 = mapMaybe del avails
676 del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
677 del (Avail n) | keep n = Just (Avail n)
678 | otherwise = Nothing
679 del (AvailTC n ns) | null ns' = Nothing
680 | otherwise = Just (AvailTC n ns')
685 ---------------------------------------
687 ---------------------------------------
690 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
692 emptyAvailEnv :: AvailEnv
693 emptyAvailEnv = emptyNameEnv
695 unitAvailEnv :: AvailInfo -> AvailEnv
696 unitAvailEnv a = unitNameEnv (availName a) a
698 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
699 plusAvailEnv = plusNameEnv_C plusAvail
701 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
702 lookupAvailEnv_maybe = lookupNameEnv
704 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
705 lookupAvailEnv env n = case lookupNameEnv env n of
707 Nothing -> pprPanic "lookupAvailEnv" (ppr n)
709 availEnvElts = nameEnvElts
711 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
712 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
714 mkAvailEnv :: [AvailInfo] -> AvailEnv
715 -- 'avails' may have several items with the same availName
716 -- E.g import Ix( Ix(..), index )
717 -- will give Ix(Ix,index,range) and Ix(index)
718 -- We want to combine these; addAvail does that
719 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
722 %************************************************************************
724 \subsection{Where from}
726 %************************************************************************
728 The @WhereFrom@ type controls where the renamer looks for an interface file
732 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
734 | ImportForUsage IsBootInterface -- Import when chasing usage info from an interaface file
735 -- Failure in this case is not an error
737 | ImportBySystem -- Non user import.
739 instance Outputable WhereFrom where
740 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
742 ppr (ImportForUsage is_boot) | is_boot = ptext SLIT("{- USAGE SOURCE -}")
743 | otherwise = ptext SLIT("{- USAGE -}")
744 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
748 %************************************************************************
750 \subsection[Inst-types]{@Inst@ types}
752 v%************************************************************************
754 An @Inst@ is either a dictionary, an instance of an overloaded
755 literal, or an instance of an overloaded value. We call the latter a
756 ``method'' even though it may not correspond to a class operation.
757 For example, we might have an instance of the @double@ function at
758 type Int, represented by
760 Method 34 doubleId [Int] origin
772 TcId -- The overloaded function
773 -- This function will be a global, local, or ClassOpId;
774 -- inside instance decls (only) it can also be an InstId!
775 -- The id needn't be completely polymorphic.
776 -- You'll probably find its name (for documentation purposes)
777 -- inside the InstOrigin
779 [TcType] -- The types to which its polymorphic tyvars
780 -- should be instantiated.
781 -- These types must saturate the Id's foralls.
783 TcThetaType -- The (types of the) dictionaries to which the function
784 -- must be applied to get the method
786 TcTauType -- The tau-type of the method
790 -- INVARIANT 1: in (Method u f tys theta tau loc)
791 -- type of (f tys dicts(from theta)) = tau
793 -- INVARIANT 2: tau must not be of form (Pred -> Tau)
794 -- Reason: two methods are considerd equal if the
795 -- base Id matches, and the instantiating types
796 -- match. The TcThetaType should then match too.
797 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
801 HsOverLit -- The literal from the occurrence site
802 -- INVARIANT: never a rebindable-syntax literal
803 -- Reason: tcSyntaxName does unification, and we
804 -- don't want to deal with that during tcSimplify
805 TcType -- The type at which the literal is used
809 @Insts@ are ordered by their class/type info, rather than by their
810 unique. This allows the context-reduction mechanism to use standard finite
811 maps to do their stuff.
814 instance Ord Inst where
817 instance Eq Inst where
818 (==) i1 i2 = case i1 `cmpInst` i2 of
822 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
823 cmpInst (Dict _ _ _) other = LT
825 cmpInst (Method _ _ _ _ _ _) (Dict _ _ _) = GT
826 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
827 cmpInst (Method _ _ _ _ _ _) other = LT
829 cmpInst (LitInst _ _ _ _) (Dict _ _ _) = GT
830 cmpInst (LitInst _ _ _ _) (Method _ _ _ _ _ _) = GT
831 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
835 %************************************************************************
837 \subsection[Inst-collections]{LIE: a collection of Insts}
839 %************************************************************************
844 isEmptyLIE = isEmptyBag
846 unitLIE inst = unitBag inst
847 mkLIE insts = listToBag insts
848 plusLIE lie1 lie2 = lie1 `unionBags` lie2
849 consLIE inst lie = inst `consBag` lie
850 plusLIEs lies = unionManyBags lies
851 lieToList = bagToList
852 listToLIE = listToBag
856 %************************************************************************
858 \subsection[Inst-origin]{The @InstOrigin@ type}
860 %************************************************************************
862 The @InstOrigin@ type gives information about where a dictionary came from.
863 This is important for decent error message reporting because dictionaries
864 don't appear in the original source code. Doubtless this type will evolve...
866 It appears in TcMonad because there are a couple of error-message-generation
867 functions that deal with it.
870 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
872 instLocSrcLoc :: InstLoc -> SrcLoc
873 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
876 = OccurrenceOf Name -- Occurrence of an overloaded identifier
878 | IPOcc (IPName Name) -- Occurrence of an implicit parameter
879 | IPBind (IPName Name) -- Binding site of an implicit parameter
883 | DataDeclOrigin -- Typechecking a data declaration
885 | InstanceDeclOrigin -- Typechecking an instance decl
887 | LiteralOrigin HsOverLit -- Occurrence of a literal
889 | PatOrigin RenamedPat
891 | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
892 | PArrSeqOrigin RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
894 | SignatureOrigin -- A dict created from a type signature
895 | Rank2Origin -- A dict created when typechecking the argument
896 -- of a rank-2 typed function
898 | DoOrigin -- The monad for a do expression
899 | ProcOrigin -- A proc expression
901 | ClassDeclOrigin -- Manufactured during a class decl
903 | InstanceSpecOrigin Class -- in a SPECIALIZE instance pragma
906 -- When specialising instances the instance info attached to
907 -- each class is not yet ready, so we record it inside the
908 -- origin information. This is a bit of a hack, but it works
909 -- fine. (Patrick is to blame [WDP].)
911 | ValSpecOrigin Name -- in a SPECIALIZE pragma for a value
913 -- Argument or result of a ccall
914 -- Dictionaries with this origin aren't actually mentioned in the
915 -- translated term, and so need not be bound. Nor should they
916 -- be abstracted over.
918 | CCallOrigin String -- CCall label
919 (Maybe RenamedHsExpr) -- Nothing if it's the result
920 -- Just arg, for an argument
922 | UnknownOrigin -- Help! I give up...
926 pprInstLoc :: InstLoc -> SDoc
927 pprInstLoc (InstLoc orig locn ctxt)
928 = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
930 pp_orig (OccurrenceOf name)
931 = hsep [ptext SLIT("use of"), quotes (ppr name)]
933 = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
934 pp_orig (IPBind name)
935 = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
936 pp_orig RecordUpdOrigin
937 = ptext SLIT("a record update")
938 pp_orig DataDeclOrigin
939 = ptext SLIT("the data type declaration")
940 pp_orig InstanceDeclOrigin
941 = ptext SLIT("the instance declaration")
942 pp_orig (LiteralOrigin lit)
943 = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
944 pp_orig (PatOrigin pat)
945 = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
946 pp_orig (ArithSeqOrigin seq)
947 = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
948 pp_orig (PArrSeqOrigin seq)
949 = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
950 pp_orig (SignatureOrigin)
951 = ptext SLIT("a type signature")
952 pp_orig (Rank2Origin)
953 = ptext SLIT("a function with an overloaded argument type")
955 = ptext SLIT("a do statement")
957 = ptext SLIT("a proc expression")
958 pp_orig (ClassDeclOrigin)
959 = ptext SLIT("a class declaration")
960 pp_orig (InstanceSpecOrigin clas ty)
961 = hsep [text "a SPECIALIZE instance pragma; class",
962 quotes (ppr clas), text "type:", ppr ty]
963 pp_orig (ValSpecOrigin name)
964 = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
965 pp_orig (CCallOrigin clabel Nothing{-ccall result-})
966 = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
967 pp_orig (CCallOrigin clabel (Just arg_expr))
968 = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma,
969 text "namely", quotes (ppr arg_expr)]
970 pp_orig (UnknownOrigin)
971 = ptext SLIT("...oops -- I don't know where the overloading came from!")