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