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