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