[project @ 2003-10-09 11:58:39 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         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
7         TcRef,
8
9         -- The environment types
10         Env(..), 
11         TcGblEnv(..), TcLclEnv(..), 
12         IfGblEnv(..), IfLclEnv(..),
13
14         -- Ranamer types
15         EntityUsage, emptyUsages, ErrCtxt,
16         ImportAvails(..), emptyImportAvails, plusImportAvails, 
17         plusAvail, pruneAvails,  
18         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, 
19         mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
20         WhereFrom(..), mkModDeps,
21
22         -- Typechecker types
23         TcTyThing(..),
24
25         -- Template Haskell
26         ThStage(..), topStage, topSpliceStage,
27         ThLevel, impLevel, topLevel,
28
29         -- Arrows
30         ArrowCtxt(..), topArrowCtxt, ProcLevel, topProcLevel, 
31
32         -- Insts
33         Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, instLocSrcLoc,
34         LIE, emptyLIE, unitLIE, plusLIE, consLIE, 
35         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
36
37         -- Misc other types
38         TcId, TcIdSet
39   ) where
40
41 #include "HsVersions.h"
42
43 import HsSyn            ( PendingSplice, HsOverLit, MonoBinds, RuleDecl, ForeignDecl )
44 import RnHsSyn          ( RenamedPat, RenamedArithSeqInfo )
45 import HscTypes         ( FixityEnv,
46                           HscEnv, TypeEnv, TyThing, 
47                           Avails, GenAvailInfo(..), AvailInfo,
48                           availName, IsBootInterface, Deprecations )
49 import Packages         ( PackageName )
50 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, 
51                           TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes )
52 import InstEnv          ( DFunId, InstEnv )
53 import IOEnv
54 import RdrName          ( GlobalRdrEnv, LocalRdrEnv )
55 import Name             ( Name )
56 import NameEnv
57 import NameSet          ( NameSet, emptyNameSet, DefUses )
58 import OccName          ( OccEnv )
59 import Type             ( Type )
60 import Class            ( Class )
61 import Var              ( Id, TyVar )
62 import VarEnv           ( TidyEnv )
63 import Module
64 import SrcLoc           ( SrcLoc )
65 import VarSet           ( IdSet )
66 import ErrUtils         ( Messages, Message )
67 import UniqSupply       ( UniqSupply )
68 import BasicTypes       ( IPName )
69 import Util             ( thenCmp )
70 import Bag
71 import Outputable
72 import Maybe            ( mapMaybe )
73 import ListSetOps       ( unionLists )
74 \end{code}
75
76
77 %************************************************************************
78 %*                                                                      *
79                Standard monad definition for TcRn
80     All the combinators for the monad can be found in TcRnMonad
81 %*                                                                      *
82 %************************************************************************
83
84 The monad itself has to be defined here, because it is mentioned by ErrCtxt
85
86 \begin{code}
87 type TcRef a = IORef a
88 type TcId    = Id                       -- Type may be a TcType
89 type TcIdSet = IdSet
90
91 type TcRnIf a b c = IOEnv (Env a b) c
92 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
93 type IfG a  = IfM () a                          -- Top level
94 type IfL a  = IfM IfLclEnv a                    -- Nested
95 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
96 type RnM  a = TcRn a            -- Historical
97 type TcM  a = TcRn a            -- Historical
98 \end{code}
99
100
101 %************************************************************************
102 %*                                                                      *
103                 The main environment types
104 %*                                                                      *
105 %************************************************************************
106
107 \begin{code}
108 data Env gbl lcl        -- Changes as we move into an expression
109   = Env {
110         env_top  :: HscEnv,     -- Top-level stuff that never changes
111                                 --   Includes all info about imported things
112
113         env_us   :: TcRef UniqSupply,   -- Unique supply for local varibles
114
115         env_gbl  :: gbl,        -- Info about things defined at the top level
116                                 --   of the module being compiled
117
118         env_lcl  :: lcl         -- Nested stuff -- changes as we go into 
119                                 -- an expression
120     }
121
122 -- TcGblEnv describes the top-level of the module at the 
123 -- point at which the typechecker is finished work.
124 -- It is this structure that is handed on to the desugarer
125
126 data TcGblEnv
127   = TcGblEnv {
128         tcg_mod     :: Module,          -- Module being compiled
129         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
130         tcg_default :: Maybe [Type],    -- Types used for defaulting
131                                         -- Nothing => no 'default' decl
132
133         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
134
135         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
136                 -- All TyCons and Classes (for this module) end up in here right away,
137                 -- along with their derived constructors, selectors.
138                 --
139                 -- (Ids defined in this module start in the local envt, 
140                 --  though they move to the global envt during zonking)
141
142         tcg_type_env_var :: TcRef TypeEnv,      
143                 -- Used only to initialise the interface-file
144                 -- typechecker in initIfaceTcRn, so that it can see stuff
145                 -- bound in this module when dealing with hi-boot recursions
146                 -- Updated at intervals (e.g. after dealing with types and classes)
147         
148         tcg_inst_env :: InstEnv,        -- Instance envt for *home-package* modules
149                                         -- Includes the dfuns in tcg_insts
150         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
151                 -- Used to generate version dependencies
152                 -- This records usages, rather like tcg_dus, but it has to
153                 -- be a mutable variable so it can be augmented 
154                 -- when we look up an instance.  These uses of dfuns are
155                 -- rather like the free variables of the program, but
156                 -- are implicit instead of explicit.
157
158                 -- Now a bunch of things about this module that are simply 
159                 -- accumulated, but never consulted until the end.  
160                 -- Nevertheless, it's convenient to accumulate them along 
161                 -- with the rest of the info from this module.
162         tcg_exports :: Avails,                  -- What is exported
163         tcg_imports :: ImportAvails,            -- Information about what was imported 
164                                                 --    from where, including things bound
165                                                 --    in this module
166         tcg_dus :: DefUses,     -- What is defined in this module and what is used.
167                                 -- The latter is used to generate 
168                                 --      (a) version tracking; no need to recompile if these
169                                 --              things have not changed version stamp
170                                 --      (b) unused-import info
171
172                 -- The next fields accumulate the payload of the module
173                 -- The binds, rules and foreign-decl fiels are collected
174                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
175         tcg_binds   :: MonoBinds Id,            -- Value bindings in this module
176         tcg_deprecs :: Deprecations,            -- ...Deprecations 
177         tcg_insts   :: [DFunId],                -- ...Instances
178         tcg_rules   :: [RuleDecl Id],           -- ...Rules
179         tcg_fords   :: [ForeignDecl Id]         -- ...Foreign import & exports
180     }
181 \end{code}
182
183 %************************************************************************
184 %*                                                                      *
185                 The interface environments
186               Used when dealing with IfaceDecls
187 %*                                                                      *
188 %************************************************************************
189
190 \begin{code}
191 data IfGblEnv 
192   = IfGblEnv {
193         -- The type environment for the module being compiled,
194         -- in case the interface refers back to it via a reference that
195         -- was originally a hi-boot file.
196         -- We need the module name so we can test when it's appropriate
197         -- to look in this env.
198         if_rec_types :: Maybe (Module, IfG TypeEnv),
199                 -- Allows a read effect, so it can be in a mutable
200                 -- variable; c.f. handling the external package type env
201                 -- Nothing => interactive stuff, no loops possible
202
203         if_is_boot   :: ModuleEnv (ModuleName, IsBootInterface)
204         -- Tells what we know about boot interface files
205         -- When we're importing a module we know absolutely
206         -- nothing about, so we assume it's from
207         -- another package, where we aren't doing 
208         -- dependency tracking. So it won't be a hi-boot file.
209     }
210
211 data IfLclEnv
212   = IfLclEnv {
213         -- The module for the current IfaceDecl
214         -- So if we see   f = \x -> x
215         -- it means M.f = \x -> x, where M is the if_mod
216         if_mod :: ModuleName,
217
218         if_tv_env  :: OccEnv TyVar,     -- Nested tyvar bindings
219         if_id_env  :: OccEnv Id         -- Nested id binding
220     }
221 \end{code}
222
223
224 %************************************************************************
225 %*                                                                      *
226                 The local typechecker environment
227 %*                                                                      *
228 %************************************************************************
229
230 The Global-Env/Local-Env story
231 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
232 During type checking, we keep in the tcg_type_env
233         * All types and classes
234         * All Ids derived from types and classes (constructors, selectors)
235
236 At the end of type checking, we zonk the local bindings,
237 and as we do so we add to the tcg_type_env
238         * Locally defined top-level Ids
239
240 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
241         a) fed back (via the knot) to typechecking the 
242            unfoldings of interface signatures
243         b) used in the ModDetails of this module
244
245 \begin{code}
246 data TcLclEnv           -- Changes as we move inside an expression
247                         -- Discarded after typecheck/rename; not passed on to desugarer
248   = TcLclEnv {
249         tcl_loc  :: SrcLoc,             -- Source location
250         tcl_ctxt :: ErrCtxt,            -- Error context
251         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
252
253         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
254         tcl_arrow_ctxt :: ArrowCtxt,    -- Arrow-notation context
255
256         tcl_rdr :: LocalRdrEnv,         -- Local name envt
257                 --   Does *not* include global name envt; may shadow it
258                 --   Includes both ordinary variables and type variables;
259                 --   they are kept distinct because tyvar have a different
260                 --   occurrence contructor (Name.TvOcc)
261                 -- We still need the unsullied global name env so that
262                 --   we can look up record field names
263
264         tcl_env    :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
265                                           -- defined in this module
266                                         
267         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
268                         -- Namely, the in-scope TyVars bound in tcl_lenv, 
269                         -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
270                         -- Why mutable? see notes with tcGetGlobalTyVars
271
272         tcl_lie :: TcRef LIE            -- Place to accumulate type constraints
273     }
274
275 ---------------------------
276 -- Template Haskell levels 
277 ---------------------------
278
279 type ThLevel = Int      -- Always >= 0
280
281 data ThStage
282   = Comp                                -- Ordinary compiling, at level topLevel
283   | Splice ThLevel                      -- Inside a splice
284   | Brack  ThLevel                      -- Inside brackets; 
285            (TcRef [PendingSplice])      --   accumulate pending splices here
286            (TcRef LIE)                  --   and type constraints here
287 topStage, topSpliceStage :: ThStage
288 topStage       = Comp
289 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
290
291
292 impLevel, topLevel :: ThLevel
293 topLevel = 1    -- Things defined at top level of this module
294 impLevel = 0    -- Imported things; they can be used inside a top level splice
295 --
296 -- For example: 
297 --      f = ...
298 --      g1 = $(map ...)         is OK
299 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
300
301
302 ---------------------------
303 -- Arrow-notation stages
304 ---------------------------
305
306 -- In arrow notation, a variable bound by a proc (or enclosed let/kappa)
307 -- is not in scope to the left of an arrow tail (-<).  For example
308 --
309 --      proc x -> (e1 -< e2)
310 --
311 -- Here, x is not in scope in e1, but it is in scope in e2.  This can get 
312 -- a bit complicated:
313 --
314 --      let x = 3 in
315 --      prox y -> (proc z -> e1) -< e2
316 --
317 -- Here, x and z are in scope in e1, but y is not.  Here's how we track this:
318 --      a) Assign an "proc level" to each proc, being the number of
319 --         lexically-enclosing procs + 1.  
320 --      b) Assign to each local variable the proc-level of its lexically
321 --         enclosing proc.
322 --      c) Keep a list of out-of-scope procs.  When moving to the left of
323 --         an arrow-tail, add the proc-level of the immediately enclosing
324 --         proc to the list.
325 --      d) When looking up a variable, complain if its proc-level is in
326 --         the banned list
327
328 type ProcLevel = Int    -- Always >= 0
329 topProcLevel = 0        -- Not inside any proc
330
331 data ArrowCtxt = ArrCtxt { proc_level :: ProcLevel,     -- Current level
332                            proc_banned :: [ProcLevel] } -- Out of scope proc-levels
333
334 topArrowCtxt = ArrCtxt { proc_level = topProcLevel, proc_banned = [] }
335
336 ---------------------------
337 -- TcTyThing
338 ---------------------------
339
340 data TcTyThing
341   = AGlobal TyThing                     -- Used only in the return type of a lookup
342   | ATcId   TcId ThLevel ProcLevel      -- Ids defined in this module; may not be fully zonked
343   | ATyVar  TyVar                       -- Type variables
344   | ARecTyCon TcKind                    -- Used temporarily, during kind checking, for the
345   | ARecClass TcKind                    --      tycons and clases in this recursive group
346
347 instance Outputable TcTyThing where     -- Debugging only
348    ppr (AGlobal g)      = text "AGlobal" <+> ppr g
349    ppr (ATcId g tl pl)  = text "ATcId" <+> ppr g <+> ppr tl <+> ppr pl
350    ppr (ATyVar t)       = text "ATyVar" <+> ppr t
351    ppr (ARecTyCon k)    = text "ARecTyCon" <+> ppr k
352    ppr (ARecClass k)    = text "ARecClass" <+> ppr k
353 \end{code}
354
355 \begin{code}
356 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
357                         -- Innermost first.  Monadic so that we have a chance
358                         -- to deal with bound type variables just before error
359                         -- message construction
360 \end{code}
361
362
363 %************************************************************************
364 %*                                                                      *
365                         EntityUsage
366 %*                                                                      *
367 %************************************************************************
368
369 EntityUsage tells what things are actually need in order to compile this
370 module.  It is used for generating the usage-version field of the ModIface.
371
372 Note that we do not record version info for entities from 
373 other (non-home) packages.  If the package changes, GHC doesn't help.
374
375 \begin{code}
376 type EntityUsage = NameSet
377         -- The Names are all the (a) home-package
378         --                       (b) "big" (i.e. no data cons, class ops)
379         --                       (c) non-locally-defined
380         --                       (d) non-wired-in
381         -- names that have been slurped in so far.
382         -- This is used to generate the "usage" information for this module.
383
384 emptyUsages :: EntityUsage
385 emptyUsages = emptyNameSet
386 \end{code}
387
388
389 %************************************************************************
390 %*                                                                      *
391         Operations over ImportAvails
392 %*                                                                      *
393 %************************************************************************
394
395 ImportAvails summarises what was imported from where, irrespective
396 of whether the imported things are actually used or not
397 It is used      * when processing the export list
398                 * when constructing usage info for the inteface file
399                 * to identify the list of directly imported modules
400                         for initialisation purposes
401                 * when figuring out what things are really unused
402
403 \begin{code}
404 data ImportAvails 
405    = ImportAvails {
406         imp_env :: AvailEnv,
407                 -- All the things that are available from the import
408                 -- Its domain is all the "main" things;
409                 -- i.e. *excluding* class ops and constructors
410                 --      (which appear inside their parent AvailTC)
411
412         imp_qual :: ModuleEnv AvailEnv,
413                 -- Used to figure out "module M" export specifiers
414                 -- (see 1.4 Report Section 5.1.1).  Ultimately, we want to find 
415                 -- everything that is unambiguously in scope as 'M.x'
416                 -- and where plain 'x' is (perhaps ambiguously) in scope.
417                 -- So the starting point is all things that are in scope as 'M.x',
418                 -- which is what this field tells us.
419                 --
420                 -- Domain is the *module qualifier* for imports.
421                 --   e.g.        import List as Foo
422                 -- would add a binding Foo |-> ...stuff from List...
423                 -- to imp_qual.
424                 -- We keep the stuff as an AvailEnv so that it's easy to 
425                 -- combine stuff coming from different (unqualified) 
426                 -- imports of the same module
427
428         imp_mods :: ModuleEnv (Module, Maybe Bool),
429                 -- Domain is all directly-imported modules
430                 -- Maybe value answers the question "is the import restricted?"
431                 --   Nothing    => unrestricted import (e.g., "import Foo")
432                 --   Just True  => restricted import, at least one entity (e.g., "import Foo(x)")
433                 --   Just False => fully restricted import (e.g., "import Foo ()")
434                 --
435                 --  A distinction is made between the first and the third in order
436                 --  to more precisely emit warnings about unused imports.
437                 --
438                 -- We need the Module in the range because we can't get
439                 --      the keys of a ModuleEnv
440                 -- Used 
441                 --   (a) to help construct the usage information in 
442                 --       the interface file; if we import everything we
443                 --       need to recompile if the module version changes
444                 --   (b) to specify what child modules to initialise
445
446         imp_dep_mods :: ModuleEnv (ModuleName, IsBootInterface),
447                 -- Home-package modules needed by the module being compiled
448                 --
449                 -- It doesn't matter whether any of these dependencies are actually
450                 -- *used* when compiling the module; they are listed if they are below
451                 -- it at all.  For example, suppose M imports A which imports X.  Then
452                 -- compiling M might not need to consult X.hi, but X is still listed
453                 -- in M's dependencies.
454
455         imp_dep_pkgs :: [PackageName],
456                 -- Packages needed by the module being compiled, whether
457                 -- directly, or via other modules in this package, or via
458                 -- modules imported from other packages.
459
460         imp_orphs :: [ModuleName]
461                 -- Orphan modules below us in the import tree
462       }
463
464 mkModDeps :: [(ModuleName, IsBootInterface)]
465           -> ModuleEnv (ModuleName, IsBootInterface)
466 mkModDeps deps = foldl add emptyModuleEnv deps
467                where
468                  add env elt@(m,_) = extendModuleEnvByName env m elt
469
470 emptyImportAvails :: ImportAvails
471 emptyImportAvails = ImportAvails { imp_env      = emptyAvailEnv, 
472                                    imp_qual     = emptyModuleEnv, 
473                                    imp_mods     = emptyModuleEnv,
474                                    imp_dep_mods = emptyModuleEnv,
475                                    imp_dep_pkgs = [],
476                                    imp_orphs    = [] }
477
478 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
479 plusImportAvails
480   (ImportAvails { imp_env = env1, imp_qual = unqual1, imp_mods = mods1,
481                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
482   (ImportAvails { imp_env = env2, imp_qual = unqual2, imp_mods = mods2,
483                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
484   = ImportAvails { imp_env      = env1 `plusAvailEnv` env2, 
485                    imp_qual     = plusModuleEnv_C plusAvailEnv unqual1 unqual2, 
486                    imp_mods     = mods1  `plusModuleEnv` mods2, 
487                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
488                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
489                    imp_orphs    = orphs1 `unionLists` orphs2 }
490   where
491     plus_mod_dep (m1, boot1) (m2, boot2) 
492         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
493                 -- Check mod-names match
494           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
495 \end{code}
496
497 %************************************************************************
498 %*                                                                      *
499         Avails, AvailEnv, etc
500 %*                                                                      *
501 v%************************************************************************
502
503 \begin{code}
504 plusAvail (Avail n1)       (Avail n2)       = Avail n1
505 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
506 -- Added SOF 4/97
507 #ifdef DEBUG
508 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
509 #endif
510
511 -------------------------
512 pruneAvails :: (Name -> Bool)   -- Keep if this is True
513             -> [AvailInfo]
514             -> [AvailInfo]
515 pruneAvails keep avails
516   = mapMaybe del avails
517   where
518     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
519     del (Avail n) | keep n    = Just (Avail n)
520                   | otherwise = Nothing
521     del (AvailTC n ns) | null ns'  = Nothing
522                        | otherwise = Just (AvailTC n ns')
523                        where
524                          ns' = filter keep ns
525 \end{code}
526
527 ---------------------------------------
528         AvailEnv and friends
529 ---------------------------------------
530
531 \begin{code}
532 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
533
534 emptyAvailEnv :: AvailEnv
535 emptyAvailEnv = emptyNameEnv
536
537 unitAvailEnv :: AvailInfo -> AvailEnv
538 unitAvailEnv a = unitNameEnv (availName a) a
539
540 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
541 plusAvailEnv = plusNameEnv_C plusAvail
542
543 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
544 lookupAvailEnv_maybe = lookupNameEnv
545
546 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
547 lookupAvailEnv env n = case lookupNameEnv env n of
548                          Just avail -> avail
549                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
550
551 availEnvElts = nameEnvElts
552
553 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
554 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
555
556 mkAvailEnv :: [AvailInfo] -> AvailEnv
557         -- 'avails' may have several items with the same availName
558         -- E.g  import Ix( Ix(..), index )
559         -- will give Ix(Ix,index,range) and Ix(index)
560         -- We want to combine these; addAvail does that
561 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
562 \end{code}
563
564 %************************************************************************
565 %*                                                                      *
566 \subsection{Where from}
567 %*                                                                      *
568 %************************************************************************
569
570 The @WhereFrom@ type controls where the renamer looks for an interface file
571
572 \begin{code}
573 data WhereFrom 
574   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
575   | ImportBySystem                      -- Non user import.
576
577 instance Outputable WhereFrom where
578   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
579                              | otherwise   = empty
580   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
581 \end{code}
582
583
584 %************************************************************************
585 %*                                                                      *
586 \subsection[Inst-types]{@Inst@ types}
587 %*                                                                      *
588 v%************************************************************************
589
590 An @Inst@ is either a dictionary, an instance of an overloaded
591 literal, or an instance of an overloaded value.  We call the latter a
592 ``method'' even though it may not correspond to a class operation.
593 For example, we might have an instance of the @double@ function at
594 type Int, represented by
595
596         Method 34 doubleId [Int] origin
597
598 \begin{code}
599 data Inst
600   = Dict
601         Id
602         TcPredType
603         InstLoc
604
605   | Method
606         Id
607
608         TcId    -- The overloaded function
609                         -- This function will be a global, local, or ClassOpId;
610                         --   inside instance decls (only) it can also be an InstId!
611                         -- The id needn't be completely polymorphic.
612                         -- You'll probably find its name (for documentation purposes)
613                         --        inside the InstOrigin
614
615         [TcType]        -- The types to which its polymorphic tyvars
616                         --      should be instantiated.
617                         -- These types must saturate the Id's foralls.
618
619         TcThetaType     -- The (types of the) dictionaries to which the function
620                         -- must be applied to get the method
621
622         TcTauType       -- The tau-type of the method
623
624         InstLoc
625
626         -- INVARIANT 1: in (Method u f tys theta tau loc)
627         --      type of (f tys dicts(from theta)) = tau
628
629         -- INVARIANT 2: tau must not be of form (Pred -> Tau)
630         --   Reason: two methods are considerd equal if the 
631         --           base Id matches, and the instantiating types
632         --           match.  The TcThetaType should then match too.
633         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
634
635   | LitInst
636         Id
637         HsOverLit       -- The literal from the occurrence site
638                         --      INVARIANT: never a rebindable-syntax literal
639                         --      Reason: tcSyntaxName does unification, and we
640                         --              don't want to deal with that during tcSimplify
641         TcType          -- The type at which the literal is used
642         InstLoc
643 \end{code}
644
645 @Insts@ are ordered by their class/type info, rather than by their
646 unique.  This allows the context-reduction mechanism to use standard finite
647 maps to do their stuff.
648
649 \begin{code}
650 instance Ord Inst where
651   compare = cmpInst
652
653 instance Eq Inst where
654   (==) i1 i2 = case i1 `cmpInst` i2 of
655                  EQ    -> True
656                  other -> False
657
658 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
659 cmpInst (Dict _ _ _)              other                     = LT
660
661 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
662 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
663 cmpInst (Method _ _ _ _ _ _)      other                     = LT
664
665 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
666 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
667 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
668 \end{code}
669
670
671 %************************************************************************
672 %*                                                                      *
673 \subsection[Inst-collections]{LIE: a collection of Insts}
674 %*                                                                      *
675 %************************************************************************
676
677 \begin{code}
678 type LIE = Bag Inst
679
680 isEmptyLIE        = isEmptyBag
681 emptyLIE          = emptyBag
682 unitLIE inst      = unitBag inst
683 mkLIE insts       = listToBag insts
684 plusLIE lie1 lie2 = lie1 `unionBags` lie2
685 consLIE inst lie  = inst `consBag` lie
686 plusLIEs lies     = unionManyBags lies
687 lieToList         = bagToList
688 listToLIE         = listToBag
689 \end{code}
690
691
692 %************************************************************************
693 %*                                                                      *
694 \subsection[Inst-origin]{The @InstOrigin@ type}
695 %*                                                                      *
696 %************************************************************************
697
698 The @InstOrigin@ type gives information about where a dictionary came from.
699 This is important for decent error message reporting because dictionaries
700 don't appear in the original source code.  Doubtless this type will evolve...
701
702 It appears in TcMonad because there are a couple of error-message-generation
703 functions that deal with it.
704
705 \begin{code}
706 data InstLoc = InstLoc InstOrigin SrcLoc ErrCtxt
707
708 instLocSrcLoc :: InstLoc -> SrcLoc
709 instLocSrcLoc (InstLoc _ src_loc _) = src_loc
710
711 data InstOrigin
712   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
713
714   | IPOcc (IPName Name)         -- Occurrence of an implicit parameter
715   | IPBind (IPName Name)        -- Binding site of an implicit parameter
716
717   | RecordUpdOrigin
718
719   | DataDeclOrigin              -- Typechecking a data declaration
720
721   | InstanceDeclOrigin          -- Typechecking an instance decl
722
723   | LiteralOrigin HsOverLit     -- Occurrence of a literal
724
725   | PatOrigin RenamedPat
726
727   | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
728   | PArrSeqOrigin  RenamedArithSeqInfo -- [:x..y:] and [:x,y..z:]
729
730   | SignatureOrigin             -- A dict created from a type signature
731   | Rank2Origin                 -- A dict created when typechecking the argument
732                                 -- of a rank-2 typed function
733
734   | DoOrigin                    -- The monad for a do expression
735   | ProcOrigin                  -- A proc expression
736
737   | ClassDeclOrigin             -- Manufactured during a class decl
738
739   | InstanceSpecOrigin  Class   -- in a SPECIALIZE instance pragma
740                         Type
741
742         -- When specialising instances the instance info attached to
743         -- each class is not yet ready, so we record it inside the
744         -- origin information.  This is a bit of a hack, but it works
745         -- fine.  (Patrick is to blame [WDP].)
746
747   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
748
749         -- Argument or result of a ccall
750         -- Dictionaries with this origin aren't actually mentioned in the
751         -- translated term, and so need not be bound.  Nor should they
752         -- be abstracted over.
753
754   | UnknownOrigin       -- Help! I give up...
755 \end{code}
756
757 \begin{code}
758 pprInstLoc :: InstLoc -> SDoc
759 pprInstLoc (InstLoc orig locn ctxt)
760   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
761   where
762     pp_orig (OccurrenceOf name)
763         = hsep [ptext SLIT("use of"), quotes (ppr name)]
764     pp_orig (IPOcc name)
765         = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
766     pp_orig (IPBind name)
767         = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
768     pp_orig RecordUpdOrigin
769         = ptext SLIT("a record update")
770     pp_orig DataDeclOrigin
771         = ptext SLIT("the data type declaration")
772     pp_orig InstanceDeclOrigin
773         = ptext SLIT("the instance declaration")
774     pp_orig (LiteralOrigin lit)
775         = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
776     pp_orig (PatOrigin pat)
777         = hsep [ptext SLIT("the pattern"), quotes (ppr pat)]
778     pp_orig (ArithSeqOrigin seq)
779         = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
780     pp_orig (PArrSeqOrigin seq)
781         = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
782     pp_orig (SignatureOrigin)
783         =  ptext SLIT("a type signature")
784     pp_orig (Rank2Origin)
785         =  ptext SLIT("a function with an overloaded argument type")
786     pp_orig (DoOrigin)
787         =  ptext SLIT("a do statement")
788     pp_orig (ProcOrigin)
789         =  ptext SLIT("a proc expression")
790     pp_orig (ClassDeclOrigin)
791         =  ptext SLIT("a class declaration")
792     pp_orig (InstanceSpecOrigin clas ty)
793         = hsep [text "a SPECIALIZE instance pragma; class",
794                 quotes (ppr clas), text "type:", ppr ty]
795     pp_orig (ValSpecOrigin name)
796         = hsep [ptext SLIT("a SPECIALIZE user-pragma for"), quotes (ppr name)]
797     pp_orig (UnknownOrigin)
798         = ptext SLIT("...oops -- I don't know where the overloading came from!")
799 \end{code}