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