[project @ 2002-10-15 11:00:37 by simonmar]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-2002
3 %
4 \begin{code}
5 module TcRnTypes(
6         TcRn, TcM, RnM, -- The monad is opaque outside this module
7
8         -- Standard monadic operations
9         thenM, thenM_, returnM, failM,
10
11         -- Non-standard operations
12         runTcRn, fixM, tryM, ioToTcRn,
13         newMutVar, readMutVar, writeMutVar,
14         getEnv, setEnv, updEnv, unsafeInterleaveM, 
15                 
16         -- The environment types
17         Env(..), TopEnv(..), TcGblEnv(..), 
18         TcLclEnv(..), RnLclEnv(..),
19
20         -- Ranamer types
21         RnMode(..), isInterfaceMode, isCmdLineMode,
22         Usages(..), emptyUsages, ErrCtxt,
23         ImportAvails(..), emptyImportAvails, plusImportAvails, mkImportAvails,
24         plusAvail, pruneAvails,  
25         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, lookupAvailEnv, availEnvElts, addAvail,
26         WhereFrom(..),
27
28         -- Typechecker types
29         TcTyThing(..),
30
31         -- Template Haskell
32         Stage(..), topStage, topSpliceStage,
33         Level, impLevel, topLevel,
34
35         -- Insts
36         Inst(..), InstOrigin(..), InstLoc, pprInstLoc,
37         LIE, emptyLIE, unitLIE, plusLIE, consLIE, 
38         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
39
40         -- Misc other types
41         TcRef, TcId, TcIdSet
42   ) where
43
44 #include "HsVersions.h"
45
46 import HsSyn            ( PendingSplice, HsOverLit, MonoBinds, RuleDecl, ForeignDecl )
47 import RnHsSyn          ( RenamedHsExpr, RenamedPat, RenamedArithSeqInfo )
48 import HscTypes         ( GhciMode, ExternalPackageState, HomePackageTable, NameCache,
49                           GlobalRdrEnv, LocalRdrEnv, FixityEnv, TypeEnv, TyThing, 
50                           Avails, GenAvailInfo(..), AvailInfo, availName,
51                           IsBootInterface, Deprecations )
52 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, TcPredType, TcKind,
53                           tcCmpPred, tcCmpType, tcCmpTypes )
54 import InstEnv          ( DFunId, InstEnv )
55 import Name             ( Name )
56 import NameEnv
57 import NameSet          ( NameSet, emptyNameSet )
58 import Type             ( Type )
59 import Class            ( Class )
60 import Var              ( Id, TyVar )
61 import VarEnv           ( TidyEnv )
62 import Module
63 import SrcLoc           ( SrcLoc )
64 import VarSet           ( IdSet )
65 import ErrUtils         ( Messages, Message )
66 import CmdLineOpts      ( DynFlags )
67 import UniqSupply       ( UniqSupply )
68 import BasicTypes       ( IPName )
69 import Util             ( thenCmp )
70 import Bag
71 import Outputable
72 import DATA_IOREF       ( IORef, newIORef, readIORef, writeIORef )
73 import UNSAFE_IO        ( unsafeInterleaveIO )
74 import FIX_IO           ( fixIO )
75 import EXCEPTION        ( Exception )
76 import Maybe            ( mapMaybe )
77 import List             ( nub )
78 import Panic            ( tryMost )
79 \end{code}
80
81
82 \begin{code}
83 type TcRef a = IORef a
84 type TcId    = Id                       -- Type may be a TcType
85 type TcIdSet = IdSet
86 \end{code}
87
88 %************************************************************************
89 %*                                                                      *
90                Standard monad definition for TcRn
91     All the combinators for the monad can be found in TcRnMonad
92 %*                                                                      *
93 %************************************************************************
94
95 The monad itself has to be defined here, 
96 because it is mentioned by ErrCtxt
97
98 \begin{code}
99 newtype TcRn m a = TcRn (Env m -> IO a)
100 unTcRn (TcRn f) = f
101
102 type TcM a = TcRn TcLclEnv a
103 type RnM a = TcRn RnLclEnv a
104
105 returnM :: a -> TcRn m a
106 returnM a = TcRn (\ env -> return a)
107
108 thenM :: TcRn m a -> (a -> TcRn m b) -> TcRn m b
109 thenM (TcRn m) f = TcRn (\ env -> do { r <- m env ;
110                                        unTcRn (f r) env })
111
112 thenM_ :: TcRn m a -> TcRn m b -> TcRn m b
113 thenM_ (TcRn m) f = TcRn (\ env -> do { m env ; unTcRn f env })
114
115 failM :: TcRn m a
116 failM = TcRn (\ env -> ioError (userError "TcRn failure"))
117
118 instance Monad (TcRn m) where
119   (>>=)  = thenM
120   (>>)   = thenM_
121   return = returnM
122   fail s = failM        -- Ignore the string
123 \end{code}
124
125
126 %************************************************************************
127 %*                                                                      *
128         Fundmantal combinators specific to the monad
129 %*                                                                      *
130 %************************************************************************
131
132 Running it
133
134 \begin{code}
135 runTcRn :: Env m -> TcRn m a -> IO a
136 runTcRn env (TcRn m) = m env
137 \end{code}
138
139 The fixpoint combinator
140
141 \begin{code}
142 {-# NOINLINE fixM #-}
143   -- Aargh!  Not inlining fixTc alleviates a space leak problem.
144   -- Normally fixTc is used with a lazy tuple match: if the optimiser is
145   -- shown the definition of fixTc, it occasionally transforms the code
146   -- in such a way that the code generator doesn't spot the selector
147   -- thunks.  Sigh.
148
149 fixM :: (a -> TcRn m a) -> TcRn m a
150 fixM f = TcRn (\ env -> fixIO (\ r -> unTcRn (f r) env))
151 \end{code}
152
153 Error recovery
154
155 \begin{code}
156 tryM :: TcRn m r -> TcRn m (Either Exception r)
157 -- Reflect exception into TcRn monad
158 tryM (TcRn thing) = TcRn (\ env -> tryMost (thing env))
159 \end{code}
160
161 Lazy interleave 
162
163 \begin{code}
164 unsafeInterleaveM :: TcRn m a -> TcRn m a
165 unsafeInterleaveM (TcRn m) = TcRn (\ env -> unsafeInterleaveIO (m env))
166 \end{code}
167
168 \end{code}
169
170 Performing arbitrary I/O, plus the read/write var (for efficiency)
171
172 \begin{code}
173 ioToTcRn :: IO a -> TcRn m a
174 ioToTcRn io = TcRn (\ env -> io)
175
176 newMutVar :: a -> TcRn m (TcRef a)
177 newMutVar val = TcRn (\ env -> newIORef val)
178
179 writeMutVar :: TcRef a -> a -> TcRn m ()
180 writeMutVar var val = TcRn (\ env -> writeIORef var val)
181
182 readMutVar :: TcRef a -> TcRn m a
183 readMutVar var = TcRn (\ env -> readIORef var)
184 \end{code}
185
186 Getting the environment
187
188 \begin{code}
189 getEnv :: TcRn m (Env m)
190 {-# INLINE getEnv #-}
191 getEnv = TcRn (\ env -> return env)
192
193 setEnv :: Env n -> TcRn n a -> TcRn m a
194 {-# INLINE setEnv #-}
195 setEnv new_env (TcRn m) = TcRn (\ env -> m new_env)
196
197 updEnv :: (Env m -> Env n) -> TcRn n a -> TcRn m a
198 {-# INLINE updEnv #-}
199 updEnv upd (TcRn m) = TcRn (\ env -> m (upd env))
200 \end{code}
201
202
203 %************************************************************************
204 %*                                                                      *
205                 The main environment types
206 %*                                                                      *
207 %************************************************************************
208
209 \begin{code}
210 data Env a      -- Changes as we move into an expression
211   = Env {
212         env_top  :: TopEnv,     -- Top-level stuff that never changes
213                                 --   Mainly a bunch of updatable refs
214                                 --   Includes all info about imported things
215         env_gbl  :: TcGblEnv,   -- Info about things defined at the top leve
216                                 --   of the module being compiled
217
218         env_lcl  :: a,          -- Different for the type checker 
219                                 -- and the renamer
220
221         env_loc  :: SrcLoc      -- Source location
222     }
223
224 data TopEnv     -- Built once at top level then does not change
225                 -- Concerns imported stuff
226                 -- Exceptions: error recovery points, meta computation points
227    = TopEnv {
228         top_mode    :: GhciMode,
229         top_dflags  :: DynFlags,
230
231         -- Stuff about imports
232         top_eps    :: TcRef ExternalPackageState,
233                 -- PIT, ImportedModuleInfo
234                 -- DeclsMap, IfaceRules, IfaceInsts, InstGates
235                 -- TypeEnv, InstEnv, RuleBase
236
237         top_hpt  :: HomePackageTable,
238                 -- The home package table that we've accumulated while 
239                 -- compiling the home package, 
240                 -- *excluding* the module we are compiling right now.
241                 -- (In one-shot mode the current module is the only
242                 --  home-package module, so tc_hpt is empty.  All other
243                 --  modules count as "external-package" modules.)
244                 -- tc_hpt is not mutable because we only demand-load 
245                 -- external packages; the home package is eagerly 
246                 -- loaded by the compilation manager.
247
248         -- The global name supply
249         top_nc     :: TcRef NameCache,          -- Maps original names to Names
250         top_us     :: TcRef UniqSupply,         -- Unique supply for this module
251         top_errs   :: TcRef Messages
252    }
253
254 -- TcGblEnv describes the top-level of the module at the 
255 -- point at which the typechecker is finished work.
256 -- It is this structure that is handed on to the desugarer
257
258 data TcGblEnv
259   = TcGblEnv {
260         tcg_mod    :: Module,           -- Module being compiled
261         tcg_usages :: TcRef Usages,     -- What version of what entities 
262                                         -- have been used from other modules
263                                         -- (whether home or ext-package modules)
264         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
265         tcg_fix_env :: FixityEnv,       -- Ditto
266         tcg_default :: [Type],          -- Types used for defaulting
267
268         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
269                 -- All TyCons and Classes (for this module) end up in here right away,
270                 -- along with their derived constructors, selectors.
271                 --
272                 -- (Ids defined in this module start in the local envt, 
273                 --  though they move to the global envt during zonking)
274         
275                 -- Cached things
276         tcg_ist :: Name -> Maybe TyThing,       -- Imported symbol table
277                 -- Global type env: a combination of tcg_eps, tcg_hpt
278                 --      (but *not* tcg_type_env; no deep reason)
279                 -- When the PCS changes this must be refreshed, 
280                 -- notably after running some compile-time code
281         
282         tcg_inst_env :: InstEnv,        -- Global instance env: a combination of 
283                                         --      tc_pcs, tc_hpt, *and* tc_insts
284
285                 -- Now a bunch of things about this module that are simply 
286                 -- accumulated, but never consulted until the end.  
287                 -- Nevertheless, it's convenient to accumulate them along 
288                 -- with the rest of the info from this module.
289         tcg_exports :: Avails,                  -- What is exported
290         tcg_imports :: ImportAvails,            -- Information about what was imported 
291                                                 --    from where, including things bound
292                                                 --    in this module
293                 -- The next fields are always fully zonked
294         tcg_binds   :: MonoBinds Id,            -- Value bindings in this module
295         tcg_deprecs :: Deprecations,            -- ...Deprecations 
296         tcg_insts   :: [DFunId],                -- ...Instances
297         tcg_rules   :: [RuleDecl Id],           -- ...Rules
298         tcg_fords   :: [ForeignDecl Id]         -- ...Foreign import & exports
299     }
300 \end{code}
301
302
303 %************************************************************************
304 %*                                                                      *
305                 The local typechecker environment
306 %*                                                                      *
307 %************************************************************************
308
309 The Global-Env/Local-Env story
310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
311 During type checking, we keep in the tcg_type_env
312         * All types and classes
313         * All Ids derived from types and classes (constructors, selectors)
314
315 At the end of type checking, we zonk the local bindings,
316 and as we do so we add to the tcg_type_env
317         * Locally defined top-level Ids
318
319 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
320         a) fed back (via the knot) to typechecking the 
321            unfoldings of interface signatures
322         b) used in the ModDetails of this module
323
324 \begin{code}
325 data TcLclEnv
326   = TcLclEnv {
327         tcl_ctxt :: ErrCtxt,    -- Error context
328
329         tcl_level  :: Stage,            -- Template Haskell context
330
331         tcl_env    :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
332                                           -- defined in this module
333                                         
334         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
335                                         -- Namely, the in-scope TyVars bound in tcl_lenv, 
336                                         -- plus the tyvars mentioned in the types of 
337                                         -- Ids bound in tcl_lenv
338                                         -- Why mutable? see notes with tcGetGlobalTyVars
339
340         tcl_lie :: TcRef LIE            -- Place to accumulate type constraints
341     }
342
343 type Level = Int
344
345 data Stage
346   = Comp                                -- Ordinary compiling, at level topLevel
347   | Splice Level                        -- Inside a splice
348   | Brack  Level                        -- Inside brackets; 
349            (TcRef [PendingSplice])      --   accumulate pending splices here
350            (TcRef LIE)                  --   and type constraints here
351 topStage, topSpliceStage :: Stage
352 topStage       = Comp
353 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
354
355
356 impLevel, topLevel :: Level
357 topLevel = 1    -- Things dedined at top level of this module
358 impLevel = 0    -- Imported things; they can be used inside a top level splice
359 --
360 -- For example: 
361 --      f = ...
362 --      g1 = $(map ...)         is OK
363 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
364
365 data TcTyThing
366   = AGlobal TyThing             -- Used only in the return type of a lookup
367   | ATcId   TcId Level          -- Ids defined in this module; may not be fully zonked
368   | ATyVar  TyVar               -- Type variables
369   | AThing  TcKind              -- Used temporarily, during kind checking
370 -- Here's an example of how the AThing guy is used
371 -- Suppose we are checking (forall a. T a Int):
372 --      1. We first bind (a -> AThink kv), where kv is a kind variable. 
373 --      2. Then we kind-check the (T a Int) part.
374 --      3. Then we zonk the kind variable.
375 --      4. Now we know the kind for 'a', and we add (a -> ATyVar a::K) to the environment
376 \end{code}
377
378 \begin{code}
379 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
380                         -- Innermost first.  Monadic so that we have a chance
381                         -- to deal with bound type variables just before error
382                         -- message construction
383 \end{code}
384
385
386 %************************************************************************
387 %*                                                                      *
388                 The local renamer environment
389 %*                                                                      *
390 %************************************************************************
391
392 \begin{code}
393 data RnLclEnv
394   = RnLclEnv {
395         rn_mode :: RnMode,
396         rn_lenv :: LocalRdrEnv          -- Local name envt
397                 --   Does *not* include global name envt; may shadow it
398                 --   Includes both ordinary variables and type variables;
399                 --   they are kept distinct because tyvar have a different
400                 --   occurrence contructor (Name.TvOcc)
401                 -- We still need the unsullied global name env so that
402                 --   we can look up record field names
403      }  
404
405 data RnMode = SourceMode                -- Renaming source code
406             | InterfaceMode Module      -- Renaming interface declarations from M
407             | CmdLineMode               -- Renaming a command-line expression
408
409 isInterfaceMode (InterfaceMode _) = True
410 isInterfaceMode _                 = False
411
412 isCmdLineMode CmdLineMode = True
413 isCmdLineMode _ = False
414 \end{code}
415
416
417 %************************************************************************
418 %*                                                                      *
419                         Usages
420 %*                                                                      *
421 %************************************************************************
422
423 Usages tells what things are actually need in order to compile this
424 module.  It is used 
425         * for generating the usages field of the ModIface
426         * for reporting unused things in scope
427
428 \begin{code}
429 data Usages
430   = Usages {
431         usg_ext :: ModuleSet,
432                 -- The non-home-package modules from which we have
433                 -- slurped at least one name.
434
435         usg_home :: NameSet
436                 -- The Names are all the (a) home-package
437                 --                       (b) "big" (i.e. no data cons, class ops)
438                 --                       (c) non-locally-defined
439                 --                       (d) non-wired-in
440                 -- names that have been slurped in so far.
441                 -- This is used to generate the "usage" information for this module.
442     }
443
444 emptyUsages :: Usages
445 emptyUsages = Usages { usg_ext = emptyModuleSet,
446                        usg_home = emptyNameSet }
447 \end{code}
448
449
450 %************************************************************************
451 %*                                                                      *
452         Operations over ImportAvails
453 %*                                                                      *
454 %************************************************************************
455
456 ImportAvails summarises what was imported from where, irrespective
457 of whether the imported htings are actually used or not
458 It is used      * when porcessing the export list
459                 * when constructing usage info for the inteface file
460                 * to identify the list of directly imported modules
461                         for initialisation purposes
462
463 \begin{code}
464 data ImportAvails 
465    = ImportAvails {
466         imp_env :: AvailEnv,
467                 -- All the things that are available from the import
468                 -- Its domain is all the "main" things;
469                 -- i.e. *excluding* class ops and constructors
470                 --      (which appear inside their parent AvailTC)
471
472         imp_unqual :: ModuleEnv AvailEnv,
473                 -- Used to figure out "module M" export specifiers
474                 -- Domain is only modules with *unqualified* imports
475                 -- (see 1.4 Report Section 5.1.1)
476                 -- We keep the stuff as an AvailEnv so that it's easy to 
477                 -- combine stuff coming from different (unqualified) 
478                 -- imports of the same module
479
480         imp_mods :: ModuleEnv (Module, Bool)
481                 -- Domain is all directly-imported modules
482                 -- Bool is True if there was an unrestricted import
483                 --      (i.e. not a selective list)
484                 -- We need the Module in the range because we can't get
485                 --      the keys of a ModuleEnv
486                 -- Used 
487                 --   (a) to help construct the usage information in 
488                 --       the interface file; if we import everything we
489                 --       need to recompile if the module version changes
490                 --   (b) to specify what child modules to initialise
491       }
492
493 emptyImportAvails :: ImportAvails
494 emptyImportAvails = ImportAvails { imp_env    = emptyAvailEnv, 
495                                    imp_unqual = emptyModuleEnv, 
496                                    imp_mods   = emptyModuleEnv }
497
498 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
499 plusImportAvails
500   (ImportAvails { imp_env = env1, imp_unqual = unqual1, imp_mods = mods1 })
501   (ImportAvails { imp_env = env2, imp_unqual = unqual2, imp_mods = mods2 })
502   = ImportAvails { imp_env    = env1 `plusAvailEnv` env2, 
503                    imp_unqual = plusModuleEnv_C plusAvailEnv unqual1 unqual2, 
504                    imp_mods   = mods1 `plusModuleEnv` mods2 }
505
506 mkImportAvails :: ModuleName -> Bool
507                -> [AvailInfo] -> ImportAvails
508 mkImportAvails mod_name unqual_imp avails 
509   = ImportAvails { imp_unqual = mod_avail_env, 
510                    imp_env    = entity_avail_env,
511                    imp_mods   = emptyModuleEnv }-- Stays empty for module being compiled;
512                                                 -- gets updated for imported modules
513   where
514     mod_avail_env = unitModuleEnvByName mod_name unqual_avails 
515
516         -- unqual_avails is the Avails that are visible in *unqualified* form
517         -- We need to know this so we know what to export when we see
518         --      module M ( module P ) where ...
519         -- Then we must export whatever came from P unqualified.
520
521     unqual_avails | not unqual_imp = emptyAvailEnv      -- Qualified import
522                   | otherwise      = entity_avail_env   -- Unqualified import
523
524     entity_avail_env = foldl insert emptyAvailEnv avails
525     insert env avail = extendNameEnv_C plusAvail env (availName avail) avail
526         -- 'avails' may have several items with the same availName
527         -- E.g  import Ix( Ix(..), index )
528         -- will give Ix(Ix,index,range) and Ix(index)
529         -- We want to combine these
530 \end{code}
531
532 %************************************************************************
533 %*                                                                      *
534         Avails, AvailEnv, etc
535 %*                                                                      *
536 v%************************************************************************
537
538 \begin{code}
539 plusAvail (Avail n1)       (Avail n2)       = Avail n1
540 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (nub (ns1 ++ ns2))
541 -- Added SOF 4/97
542 #ifdef DEBUG
543 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
544 #endif
545
546 -------------------------
547 pruneAvails :: (Name -> Bool)   -- Keep if this is True
548             -> [AvailInfo]
549             -> [AvailInfo]
550 pruneAvails keep avails
551   = mapMaybe del avails
552   where
553     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
554     del (Avail n) | keep n    = Just (Avail n)
555                   | otherwise = Nothing
556     del (AvailTC n ns) | null ns'  = Nothing
557                        | otherwise = Just (AvailTC n ns')
558                        where
559                          ns' = filter keep ns
560 \end{code}
561
562 ---------------------------------------
563         AvailEnv and friends
564 ---------------------------------------
565
566 \begin{code}
567 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
568
569 emptyAvailEnv :: AvailEnv
570 emptyAvailEnv = emptyNameEnv
571
572 unitAvailEnv :: AvailInfo -> AvailEnv
573 unitAvailEnv a = unitNameEnv (availName a) a
574
575 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
576 plusAvailEnv = plusNameEnv_C plusAvail
577
578 lookupAvailEnv = lookupNameEnv
579
580 availEnvElts = nameEnvElts
581
582 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
583 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
584 \end{code}
585
586 %************************************************************************
587 %*                                                                      *
588 \subsection{Where from}
589 %*                                                                      *
590 %************************************************************************
591
592 The @WhereFrom@ type controls where the renamer looks for an interface file
593
594 \begin{code}
595 data WhereFrom 
596   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
597
598   | ImportForUsage IsBootInterface      -- Import when chasing usage info from an interaface file
599                                         --      Failure in this case is not an error
600
601   | ImportBySystem                      -- Non user import.  Use eps_mod_info to decide whether
602                                         -- the module this module depends on, or is a system-ish module; 
603                                         -- M.hi-boot otherwise
604
605 instance Outputable WhereFrom where
606   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
607                              | otherwise   = empty
608   ppr (ImportForUsage is_boot) | is_boot   = ptext SLIT("{- USAGE SOURCE -}")
609                                | otherwise = ptext SLIT("{- USAGE -}")
610   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
611 \end{code}
612
613
614 %************************************************************************
615 %*                                                                      *
616 \subsection[Inst-types]{@Inst@ types}
617 %*                                                                      *
618 v%************************************************************************
619
620 An @Inst@ is either a dictionary, an instance of an overloaded
621 literal, or an instance of an overloaded value.  We call the latter a
622 ``method'' even though it may not correspond to a class operation.
623 For example, we might have an instance of the @double@ function at
624 type Int, represented by
625
626         Method 34 doubleId [Int] origin
627
628 \begin{code}
629 data Inst
630   = Dict
631         Id
632         TcPredType
633         InstLoc
634
635   | Method
636         Id
637
638         TcId    -- The overloaded function
639                         -- This function will be a global, local, or ClassOpId;
640                         --   inside instance decls (only) it can also be an InstId!
641                         -- The id needn't be completely polymorphic.
642                         -- You'll probably find its name (for documentation purposes)
643                         --        inside the InstOrigin
644
645         [TcType]        -- The types to which its polymorphic tyvars
646                         --      should be instantiated.
647                         -- These types must saturate the Id's foralls.
648
649         TcThetaType     -- The (types of the) dictionaries to which the function
650                         -- must be applied to get the method
651
652         TcTauType       -- The type of the method
653
654         InstLoc
655
656         -- INVARIANT: in (Method u f tys theta tau loc)
657         --      type of (f tys dicts(from theta)) = tau
658
659   | LitInst
660         Id
661         HsOverLit       -- The literal from the occurrence site
662                         --      INVARIANT: never a rebindable-syntax literal
663                         --      Reason: tcSyntaxName does unification, and we
664                         --              don't want to deal with that during tcSimplify
665         TcType          -- The type at which the literal is used
666         InstLoc
667 \end{code}
668
669 @Insts@ are ordered by their class/type info, rather than by their
670 unique.  This allows the context-reduction mechanism to use standard finite
671 maps to do their stuff.
672
673 \begin{code}
674 instance Ord Inst where
675   compare = cmpInst
676
677 instance Eq Inst where
678   (==) i1 i2 = case i1 `cmpInst` i2 of
679                  EQ    -> True
680                  other -> False
681
682 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
683 cmpInst (Dict _ _ _)              other                     = LT
684
685 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
686 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
687 cmpInst (Method _ _ _ _ _ _)      other                     = LT
688
689 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
690 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
691 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
692 \end{code}
693
694
695 %************************************************************************
696 %*                                                                      *
697 \subsection[Inst-collections]{LIE: a collection of Insts}
698 %*                                                                      *
699 %************************************************************************
700
701 \begin{code}
702 type LIE = Bag Inst
703
704 isEmptyLIE        = isEmptyBag
705 emptyLIE          = emptyBag
706 unitLIE inst      = unitBag inst
707 mkLIE insts       = listToBag insts
708 plusLIE lie1 lie2 = lie1 `unionBags` lie2
709 consLIE inst lie  = inst `consBag` lie
710 plusLIEs lies     = unionManyBags lies
711 lieToList         = bagToList
712 listToLIE         = listToBag
713 \end{code}
714
715
716 %************************************************************************
717 %*                                                                      *
718 \subsection[Inst-origin]{The @InstOrigin@ type}
719 %*                                                                      *
720 %************************************************************************
721
722 The @InstOrigin@ type gives information about where a dictionary came from.
723 This is important for decent error message reporting because dictionaries
724 don't appear in the original source code.  Doubtless this type will evolve...
725
726 It appears in TcMonad because there are a couple of error-message-generation
727 functions that deal with it.
728
729 \begin{code}
730 type InstLoc = (InstOrigin, SrcLoc, ErrCtxt)
731
732 data InstOrigin
733   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
734
735   | IPOcc (IPName Name)         -- Occurrence of an implicit parameter
736   | IPBind (IPName Name)        -- Binding site of an implicit parameter
737
738   | RecordUpdOrigin
739
740   | DataDeclOrigin              -- Typechecking a data declaration
741
742   | InstanceDeclOrigin          -- Typechecking an instance decl
743
744   | LiteralOrigin HsOverLit     -- Occurrence of a literal
745
746   | PatOrigin RenamedPat
747
748   | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
749   | PArrSeqOrigin  RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
750
751   | SignatureOrigin             -- A dict created from a type signature
752   | Rank2Origin                 -- A dict created when typechecking the argument
753                                 -- of a rank-2 typed function
754
755   | DoOrigin                    -- The monad for a do expression
756
757   | ClassDeclOrigin             -- Manufactured during a class decl
758
759   | InstanceSpecOrigin  Class   -- in a SPECIALIZE instance pragma
760                         Type
761
762         -- When specialising instances the instance info attached to
763         -- each class is not yet ready, so we record it inside the
764         -- origin information.  This is a bit of a hack, but it works
765         -- fine.  (Patrick is to blame [WDP].)
766
767   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
768
769         -- Argument or result of a ccall
770         -- Dictionaries with this origin aren't actually mentioned in the
771         -- translated term, and so need not be bound.  Nor should they
772         -- be abstracted over.
773
774   | CCallOrigin         String                  -- CCall label
775                         (Maybe RenamedHsExpr)   -- Nothing if it's the result
776                                                 -- Just arg, for an argument
777
778   | LitLitOrigin        String  -- the litlit
779
780   | UnknownOrigin       -- Help! I give up...
781 \end{code}
782
783 \begin{code}
784 pprInstLoc :: InstLoc -> SDoc
785 pprInstLoc (orig, locn, ctxt)
786   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
787   where
788     pp_orig (OccurrenceOf name)
789         = hsep [ptext SLIT("use of"), quotes (ppr name)]
790     pp_orig (IPOcc name)
791         = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
792     pp_orig (IPBind name)
793         = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
794     pp_orig RecordUpdOrigin
795         = ptext SLIT("a record update")
796     pp_orig DataDeclOrigin
797         = ptext SLIT("the data type declaration")
798     pp_orig InstanceDeclOrigin
799         = ptext SLIT("the instance declaration")
800     pp_orig (LiteralOrigin lit)
801         = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
802     pp_orig (PatOrigin pat)
803         = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
804     pp_orig (ArithSeqOrigin seq)
805         = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
806     pp_orig (PArrSeqOrigin seq)
807         = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
808     pp_orig (SignatureOrigin)
809         =  ptext SLIT("a type signature")
810     pp_orig (Rank2Origin)
811         =  ptext SLIT("a function with an overloaded argument type")
812     pp_orig (DoOrigin)
813         =  ptext SLIT("a do statement")
814     pp_orig (ClassDeclOrigin)
815         =  ptext SLIT("a class declaration")
816     pp_orig (InstanceSpecOrigin clas ty)
817         = hsep [text "a SPECIALIZE instance pragma; class",
818                 quotes (ppr clas), text "type:", ppr ty]
819     pp_orig (ValSpecOrigin name)
820         = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
821     pp_orig (CCallOrigin clabel Nothing{-ccall result-})
822         = hsep [ptext SLIT("the result of the _ccall_ to"), quotes (text clabel)]
823     pp_orig (CCallOrigin clabel (Just arg_expr))
824         = hsep [ptext SLIT("an argument in the _ccall_ to"), quotes (text clabel) <> comma, 
825                 text "namely", quotes (ppr arg_expr)]
826     pp_orig (LitLitOrigin s)
827         = hsep [ptext SLIT("the ``literal-literal''"), quotes (text s)]
828     pp_orig (UnknownOrigin)
829         = ptext SLIT("...oops -- I don't know where the overloading came from!")
830 \end{code}