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