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, Maybe Bool),
599 -- Domain is all directly-imported modules
600 -- Maybe value answers the question "is the import restricted?"
601 -- Nothing => unrestricted import (e.g., "import Foo")
602 -- Just True => restricted import, at least one entity (e.g., "import Foo(x)")
603 -- Just False => fully restricted import (e.g., "import Foo ()")
605 -- A distinction is made between the first and the third in order
606 -- to more precisely emit warnings about unused imports.
608 -- We need the Module in the range because we can't get
609 -- the keys of a ModuleEnv
611 -- (a) to help construct the usage information in
612 -- the interface file; if we import everything we
613 -- need to recompile if the module version changes
614 -- (b) to specify what child modules to initialise
616 imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
617 -- Home-package modules needed by the module being compiled
619 -- It doesn't matter whether any of these dependencies are actually
620 -- *used* when compiling the module; they are listed if they are below
621 -- it at all. For example, suppose M imports A which imports X. Then
622 -- compiling M might not need to consult X.hi, but X is still listed
623 -- in M's dependencies.
625 imp_dep_pkgs :: [PackageName],
626 -- Packages needed by the module being compiled, whether
627 -- directly, or via other modules in this package, or via
628 -- modules imported from other packages.
630 imp_orphs :: [ModuleName]
631 -- Orphan modules below us in the import tree
634 emptyImportAvails :: ImportAvails
635 emptyImportAvails = ImportAvails { imp_env = emptyAvailEnv,
636 imp_qual = emptyModuleEnv,
637 imp_mods = emptyModuleEnv,
638 imp_dep_mods = emptyModuleEnv,
642 plusImportAvails :: ImportAvails -> ImportAvails -> ImportAvails
644 (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
645 imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
646 (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
647 imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
648 = ImportAvails { imp_env = env1 `plusAvailEnv` env2,
649 imp_qual = plusModuleEnv_C plusAvailEnv unqual1 unqual2,
650 imp_mods = mods1 `plusModuleEnv` mods2,
651 imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,
652 imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
653 imp_orphs = orphs1 `unionLists` orphs2 }
655 plus_mod_dep (m1, boot1) (m2, boot2)
656 = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
657 -- Check mod-names match
658 (m1, boot1 && boot2) -- If either side can "see" a non-hi-boot interface, use that
661 %************************************************************************
663 Avails, AvailEnv, etc
665 v%************************************************************************
668 plusAvail (Avail n1) (Avail n2) = Avail n1
669 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
672 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
675 -------------------------
676 pruneAvails :: (Name -> Bool) -- Keep if this is True
679 pruneAvails keep avails
680 = mapMaybe del avails
682 del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
683 del (Avail n) | keep n = Just (Avail n)
684 | otherwise = Nothing
685 del (AvailTC n ns) | null ns' = Nothing
686 | otherwise = Just (AvailTC n ns')
691 ---------------------------------------
693 ---------------------------------------
696 type AvailEnv = NameEnv AvailInfo -- Maps a Name to the AvailInfo that contains it
698 emptyAvailEnv :: AvailEnv
699 emptyAvailEnv = emptyNameEnv
701 unitAvailEnv :: AvailInfo -> AvailEnv
702 unitAvailEnv a = unitNameEnv (availName a) a
704 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
705 plusAvailEnv = plusNameEnv_C plusAvail
707 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
708 lookupAvailEnv_maybe = lookupNameEnv
710 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
711 lookupAvailEnv env n = case lookupNameEnv env n of
713 Nothing -> pprPanic "lookupAvailEnv" (ppr n)
715 availEnvElts = nameEnvElts
717 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
718 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
720 mkAvailEnv :: [AvailInfo] -> AvailEnv
721 -- 'avails' may have several items with the same availName
722 -- E.g import Ix( Ix(..), index )
723 -- will give Ix(Ix,index,range) and Ix(index)
724 -- We want to combine these; addAvail does that
725 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
728 %************************************************************************
730 \subsection{Where from}
732 %************************************************************************
734 The @WhereFrom@ type controls where the renamer looks for an interface file
738 = ImportByUser IsBootInterface -- Ordinary user import (perhaps {-# SOURCE #-})
740 | ImportForUsage IsBootInterface -- Import when chasing usage info from an interaface file
741 -- Failure in this case is not an error
743 | ImportBySystem -- Non user import.
745 instance Outputable WhereFrom where
746 ppr (ImportByUser is_boot) | is_boot = ptext SLIT("{- SOURCE -}")
748 ppr (ImportForUsage is_boot) | is_boot = ptext SLIT("{- USAGE SOURCE -}")
749 | otherwise = ptext SLIT("{- USAGE -}")
750 ppr ImportBySystem = ptext SLIT("{- SYSTEM -}")
754 %************************************************************************
756 \subsection[Inst-types]{@Inst@ types}
758 v%************************************************************************
760 An @Inst@ is either a dictionary, an instance of an overloaded
761 literal, or an instance of an overloaded value. We call the latter a
762 ``method'' even though it may not correspond to a class operation.
763 For example, we might have an instance of the @double@ function at
764 type Int, represented by
766 Method 34 doubleId [Int] origin
778 TcId -- The overloaded function
779 -- This function will be a global, local, or ClassOpId;
780 -- inside instance decls (only) it can also be an InstId!
781 -- The id needn't be completely polymorphic.
782 -- You'll probably find its name (for documentation purposes)
783 -- inside the InstOrigin
785 [TcType] -- The types to which its polymorphic tyvars
786 -- should be instantiated.
787 -- These types must saturate the Id's foralls.
789 TcThetaType -- The (types of the) dictionaries to which the function
790 -- must be applied to get the method
792 TcTauType -- The tau-type of the method
796 -- INVARIANT 1: in (Method u f tys theta tau loc)
797 -- type of (f tys dicts(from theta)) = tau
799 -- INVARIANT 2: tau must not be of form (Pred -> Tau)
800 -- Reason: two methods are considerd equal if the
801 -- base Id matches, and the instantiating types
802 -- match. The TcThetaType should then match too.
803 -- This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
807 HsOverLit -- The literal from the occurrence site
808 -- INVARIANT: never a rebindable-syntax literal
809 -- Reason: tcSyntaxName does unification, and we
810 -- don't want to deal with that during tcSimplify
811 TcType -- The type at which the literal is used
815 @Insts@ are ordered by their class/type info, rather than by their
816 unique. This allows the context-reduction mechanism to use standard finite
817 maps to do their stuff.
820 instance Ord Inst where
823 instance Eq Inst where
824 (==) i1 i2 = case i1 `cmpInst` i2 of
828 cmpInst (Dict _ pred1 _) (Dict _ pred2 _) = pred1 `tcCmpPred` pred2
829 cmpInst (Dict _ _ _) other = LT
831 cmpInst (Method _ _ _ _ _ _) (Dict _ _ _) = GT
832 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
833 cmpInst (Method _ _ _ _ _ _) other = LT
835 cmpInst (LitInst _ _ _ _) (Dict _ _ _) = GT
836 cmpInst (LitInst _ _ _ _) (Method _ _ _ _ _ _) = GT
837 cmpInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _) = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
841 %************************************************************************
843 \subsection[Inst-collections]{LIE: a collection of Insts}
845 %************************************************************************
850 isEmptyLIE = isEmptyBag
852 unitLIE inst = unitBag inst
853 mkLIE insts = listToBag insts
854 plusLIE lie1 lie2 = lie1 `unionBags` lie2
855 consLIE inst lie = inst `consBag` lie
856 plusLIEs lies = unionManyBags lies
857 lieToList = bagToList
858 listToLIE = listToBag
862 %************************************************************************
864 \subsection[Inst-origin]{The @InstOrigin@ type}
866 %************************************************************************
868 The @InstOrigin@ type gives information about where a dictionary came from.
869 This is important for decent error message reporting because dictionaries
870 don't appear in the original source code. Doubtless this type will evolve...
872 It appears in TcMonad because there are a couple of error-message-generation
873 functions that deal with it.
876 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
878 instLocSrcLoc :: InstLoc -> SrcLoc
879 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
882 = OccurrenceOf Name -- Occurrence of an overloaded identifier
884 | IPOcc (IPName Name) -- Occurrence of an implicit parameter
885 | IPBind (IPName Name) -- Binding site of an implicit parameter
889 | DataDeclOrigin -- Typechecking a data declaration
891 | InstanceDeclOrigin -- Typechecking an instance decl
893 | LiteralOrigin HsOverLit -- Occurrence of a literal
895 | PatOrigin RenamedPat
897 | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
898 | PArrSeqOrigin RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
900 | SignatureOrigin -- A dict created from a type signature
901 | Rank2Origin -- A dict created when typechecking the argument
902 -- of a rank-2 typed function
904 | DoOrigin -- The monad for a do expression
905 | ProcOrigin -- A proc expression
907 | ClassDeclOrigin -- Manufactured during a class decl
909 | InstanceSpecOrigin Class -- in a SPECIALIZE instance pragma
912 -- When specialising instances the instance info attached to
913 -- each class is not yet ready, so we record it inside the
914 -- origin information. This is a bit of a hack, but it works
915 -- fine. (Patrick is to blame [WDP].)
917 | ValSpecOrigin Name -- in a SPECIALIZE pragma for a value
919 -- Argument or result of a ccall
920 -- Dictionaries with this origin aren't actually mentioned in the
921 -- translated term, and so need not be bound. Nor should they
922 -- be abstracted over.
924 | CCallOrigin String -- CCall label
925 (Maybe RenamedHsExpr) -- Nothing if it's the result
926 -- Just arg, for an argument
928 | UnknownOrigin -- Help! I give up...
932 pprInstLoc :: InstLoc -> SDoc
933 pprInstLoc (InstLoc orig locn ctxt)
934 = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
936 pp_orig (OccurrenceOf name)
937 = hsep [ptext SLIT("use of"), quotes (ppr name)]
939 = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
940 pp_orig (IPBind name)
941 = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
942 pp_orig RecordUpdOrigin
943 = ptext SLIT("a record update")
944 pp_orig DataDeclOrigin
945 = ptext SLIT("the data type declaration")
946 pp_orig InstanceDeclOrigin
947 = ptext SLIT("the instance declaration")
948 pp_orig (LiteralOrigin lit)
949 = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
950 pp_orig (PatOrigin pat)
951 = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
952 pp_orig (ArithSeqOrigin seq)
953 = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
954 pp_orig (PArrSeqOrigin seq)
955 = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
956 pp_orig (SignatureOrigin)
957 = ptext SLIT("a type signature")
958 pp_orig (Rank2Origin)
959 = ptext SLIT("a function with an overloaded argument type")
961 = ptext SLIT("a do statement")
963 = ptext SLIT("a proc expression")
964 pp_orig (ClassDeclOrigin)
965 = ptext SLIT("a class declaration")
966 pp_orig (InstanceSpecOrigin clas ty)
967 = hsep [text "a SPECIALIZE instance pragma; class",
968 quotes (ppr clas), text "type:", ppr ty]
969 pp_orig (ValSpecOrigin name)
970 = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
971 pp_orig (CCallOrigin clabel Nothing{-ccall result-})
972 = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
973 pp_orig (CCallOrigin clabel (Just arg_expr))
974 = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma,
975 text "namely", quotes (ppr arg_expr)]
976 pp_orig (UnknownOrigin)
977 = ptext SLIT("...oops -- I don't know where the overloading came from!")