[project @ 2005-04-16 16:05:52 by ross]
[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         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(..), pprTcTyThingCategory, GadtRefinement,
24
25         -- Template Haskell
26         ThStage(..), topStage, topSpliceStage,
27         ThLevel, impLevel, topLevel,
28
29         -- Insts
30         Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, 
31         instLocSrcLoc, instLocSrcSpan,
32         LIE, emptyLIE, unitLIE, plusLIE, consLIE, 
33         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
34
35         -- Misc other types
36         TcId, TcIdSet, TcDictBinds
37   ) where
38
39 #include "HsVersions.h"
40
41 import HsSyn            ( PendingSplice, HsOverLit, LRuleDecl, LForeignDecl,
42                           ArithSeqInfo, DictBinds, LHsBinds )
43 import HscTypes         ( FixityEnv,
44                           HscEnv, TypeEnv, TyThing, 
45                           GenAvailInfo(..), AvailInfo, HscSource(..),
46                           availName, IsBootInterface, Deprecations )
47 import Packages         ( PackageId )
48 import Type             ( Type, TvSubstEnv, pprParendType, pprTyThingCategory )
49 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, SkolemInfo,
50                           TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes, pprSkolInfo )
51 import InstEnv          ( DFunId, InstEnv )
52 import IOEnv
53 import RdrName          ( GlobalRdrEnv, LocalRdrEnv )
54 import Name             ( Name )
55 import NameEnv
56 import NameSet          ( NameSet, unionNameSets, DefUses )
57 import OccName          ( OccEnv )
58 import Var              ( Id, TyVar )
59 import VarEnv           ( TidyEnv )
60 import Module
61 import SrcLoc           ( SrcSpan, SrcLoc, srcSpanStart )
62 import VarSet           ( IdSet )
63 import ErrUtils         ( Messages, Message )
64 import UniqSupply       ( UniqSupply )
65 import BasicTypes       ( IPName )
66 import Util             ( thenCmp )
67 import Bag
68 import Outputable
69 import Maybe            ( mapMaybe )
70 import ListSetOps       ( unionLists )
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76                Standard monad definition for TcRn
77     All the combinators for the monad can be found in TcRnMonad
78 %*                                                                      *
79 %************************************************************************
80
81 The monad itself has to be defined here, because it is mentioned by ErrCtxt
82
83 \begin{code}
84 type TcRef a     = IORef a
85 type TcId        = Id                   -- Type may be a TcType
86 type TcIdSet     = IdSet
87 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
88
89
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_src     :: HscSource,       -- What kind of module 
130                                         -- (regular Haskell, hs-boot, ext-core)
131
132         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
133         tcg_default :: Maybe [Type],    -- Types used for defaulting
134                                         -- Nothing => no 'default' decl
135
136         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
137
138         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
139                 -- All TyCons and Classes (for this module) end up in here right away,
140                 -- along with their derived constructors, selectors.
141                 --
142                 -- (Ids defined in this module start in the local envt, 
143                 --  though they move to the global envt during zonking)
144
145         tcg_type_env_var :: TcRef TypeEnv,      
146                 -- Used only to initialise the interface-file
147                 -- typechecker in initIfaceTcRn, so that it can see stuff
148                 -- bound in this module when dealing with hi-boot recursions
149                 -- Updated at intervals (e.g. after dealing with types and classes)
150         
151         tcg_inst_env :: InstEnv,        -- Instance envt for *home-package* modules
152                                         -- Includes the dfuns in tcg_insts
153                 -- Now a bunch of things about this module that are simply 
154                 -- accumulated, but never consulted until the end.  
155                 -- Nevertheless, it's convenient to accumulate them along 
156                 -- with the rest of the info from this module.
157         tcg_exports :: NameSet,         -- What is exported
158         tcg_imports :: ImportAvails,    -- Information about what was imported 
159                                         --    from where, including things bound
160                                         --    in this module
161
162         tcg_dus :: DefUses,     -- What is defined in this module and what is used.
163                                 -- The latter is used to generate 
164                                 --      (a) version tracking; no need to recompile if these
165                                 --              things have not changed version stamp
166                                 --      (b) unused-import info
167
168         tcg_keep :: TcRef NameSet,      -- Locally-defined top-level names to keep alive
169                 -- "Keep alive" means give them an Exported flag, so
170                 -- that the simplifier does not discard them as dead 
171                 -- code, and so that they are exposed in the interface file
172                 -- (but not to export to the user).
173                 --
174                 -- Some things, like dict-fun Ids and default-method Ids are 
175                 -- "born" with the Exported flag on, for exactly the above reason,
176                 -- but some we only discover as we go.  Specifically:
177                 --      * The to/from functions for generic data types
178                 --      * Top-level variables appearing free in the RHS of an orphan rule
179                 --      * Top-level variables appearing free in a TH bracket
180
181         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
182                 -- Used to generate version dependencies
183                 -- This records usages, rather like tcg_dus, but it has to
184                 -- be a mutable variable so it can be augmented 
185                 -- when we look up an instance.  These uses of dfuns are
186                 -- rather like the free variables of the program, but
187                 -- are implicit instead of explicit.
188
189         tcg_th_used :: TcRef Bool,      -- True <=> Template Haskell syntax used
190                 -- We need this so that we can generate a dependency on the
191                 -- Template Haskell package, becuase the desugarer is going to
192                 -- emit loads of references to TH symbols.  It's rather like 
193                 -- tcg_inst_uses; the reference is implicit rather than explicit,
194                 -- so we have to zap a mutable variable.
195
196                 -- The next fields accumulate the payload of the module
197                 -- The binds, rules and foreign-decl fiels are collected
198                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
199         tcg_binds   :: LHsBinds Id,             -- Value bindings in this module
200         tcg_deprecs :: Deprecations,            -- ...Deprecations 
201         tcg_insts   :: [DFunId],                -- ...Instances
202         tcg_rules   :: [LRuleDecl Id],          -- ...Rules
203         tcg_fords   :: [LForeignDecl Id]        -- ...Foreign import & exports
204     }
205 \end{code}
206
207 %************************************************************************
208 %*                                                                      *
209                 The interface environments
210               Used when dealing with IfaceDecls
211 %*                                                                      *
212 %************************************************************************
213
214 \begin{code}
215 data IfGblEnv 
216   = IfGblEnv {
217         -- The type environment for the module being compiled,
218         -- in case the interface refers back to it via a reference that
219         -- was originally a hi-boot file.
220         -- We need the module name so we can test when it's appropriate
221         -- to look in this env.
222         if_rec_types :: Maybe (Module, IfG TypeEnv)
223                 -- Allows a read effect, so it can be in a mutable
224                 -- variable; c.f. handling the external package type env
225                 -- Nothing => interactive stuff, no loops possible
226     }
227
228 data IfLclEnv
229   = IfLclEnv {
230         -- The module for the current IfaceDecl
231         -- So if we see   f = \x -> x
232         -- it means M.f = \x -> x, where M is the if_mod
233         if_mod :: Module,
234
235         -- The field is used only for error reporting
236         -- if (say) there's a Lint error in it
237         if_loc :: SDoc,
238                 -- Where the interface came from:
239                 --      .hi file, or GHCi state, or ext core
240                 -- plus which bit is currently being examined
241
242         if_tv_env  :: OccEnv TyVar,     -- Nested tyvar bindings
243         if_id_env  :: OccEnv Id         -- Nested id binding
244     }
245 \end{code}
246
247
248 %************************************************************************
249 %*                                                                      *
250                 The local typechecker environment
251 %*                                                                      *
252 %************************************************************************
253
254 The Global-Env/Local-Env story
255 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256 During type checking, we keep in the tcg_type_env
257         * All types and classes
258         * All Ids derived from types and classes (constructors, selectors)
259
260 At the end of type checking, we zonk the local bindings,
261 and as we do so we add to the tcg_type_env
262         * Locally defined top-level Ids
263
264 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
265         a) fed back (via the knot) to typechecking the 
266            unfoldings of interface signatures
267         b) used in the ModDetails of this module
268
269 \begin{code}
270 data TcLclEnv           -- Changes as we move inside an expression
271                         -- Discarded after typecheck/rename; not passed on to desugarer
272   = TcLclEnv {
273         tcl_loc  :: SrcSpan,            -- Source span
274         tcl_ctxt :: ErrCtxt,            -- Error context
275         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
276
277         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
278
279         tcl_rdr :: LocalRdrEnv,         -- Local name envt
280                 -- Maintained during renaming, of course, but also during
281                 -- type checking, solely so that when renaming a Template-Haskell
282                 -- splice we have the right environment for the renamer.
283                 -- 
284                 --   Does *not* include global name envt; may shadow it
285                 --   Includes both ordinary variables and type variables;
286                 --   they are kept distinct because tyvar have a different
287                 --   occurrence contructor (Name.TvOcc)
288                 -- We still need the unsullied global name env so that
289                 --   we can look up record field names
290
291         tcl_env  :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
292                                         -- defined in this module
293                                         
294         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
295                         -- Namely, the in-scope TyVars bound in tcl_env, 
296                         -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
297                         -- Why mutable? see notes with tcGetGlobalTyVars
298
299         tcl_lie   :: TcRef LIE,         -- Place to accumulate type constraints
300         tcl_gadt  :: GadtRefinement     -- The current type refinement for GADTs
301
302 -----------------------------------------------------------
303 -- Not yet; it's a new complication and I want to see whether it bites
304 --      tcl_given :: [Inst]             -- Insts available in the current context (see Note [Given Insts])
305 -----------------------------------------------------------
306     }
307
308 type GadtRefinement = TvSubstEnv        -- Binds rigid type variables to their refinements
309
310 {- Note [Given Insts]
311    ~~~~~~~~~~~~~~~~~~
312 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
313 and existential contexts. Consider
314         data T a where { T1 :: b -> b -> T [b] }
315         f :: Eq a => T a -> Bool
316         f (T1 x y) = [x]==[y]
317
318 The constructor T1 binds an existential variable 'b', and we need Eq [b].
319 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
320 pass it inwards.
321
322 -}
323
324 ---------------------------
325 -- Template Haskell levels 
326 ---------------------------
327
328 type ThLevel = Int      
329         -- Indicates how many levels of brackets we are inside
330         --      (always >= 0)
331         -- Incremented when going inside a bracket,
332         -- decremented when going inside a splice
333
334 impLevel, topLevel :: ThLevel
335 topLevel = 1    -- Things defined at top level of this module
336 impLevel = 0    -- Imported things; they can be used inside a top level splice
337 --
338 -- For example: 
339 --      f = ...
340 --      g1 = $(map ...)         is OK
341 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
342
343
344 data ThStage
345   = Comp                                -- Ordinary compiling, at level topLevel
346   | Splice ThLevel                      -- Inside a splice
347   | Brack  ThLevel                      -- Inside brackets; 
348            (TcRef [PendingSplice])      --   accumulate pending splices here
349            (TcRef LIE)                  --   and type constraints here
350 topStage, topSpliceStage :: ThStage
351 topStage       = Comp
352 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
353
354
355 ---------------------------
356 -- TcTyThing
357 ---------------------------
358
359 data TcTyThing
360   = AGlobal TyThing                     -- Used only in the return type of a lookup
361
362   | ATcId   TcId ThLevel                -- Ids defined in this module; may not be fully zonked
363
364   | ATyVar  Name TcType                 -- Type variables; tv -> type.  It can't just be a TyVar
365                                         -- that is mutated to point to the type it is bound to,
366                                         -- because that would make it a wobbly type, and we
367                                         -- want pattern-bound lexically-scoped type variables to
368                                         -- be able to stand for rigid types
369
370   | AThing  TcKind                      -- Used temporarily, during kind checking, for the
371                                         --      tycons and clases in this recursive group
372
373 instance Outputable TcTyThing where     -- Debugging only
374    ppr (AGlobal g)      = ppr g
375    ppr (ATcId g tl)     = text "Identifier" <> 
376                           ifPprDebug (brackets (ppr g <> comma <> ppr tl))
377    ppr (ATyVar tv ty)   = text "Type variable" <+> quotes (ppr tv) <+> pprParendType ty
378    ppr (AThing k)       = text "AThing" <+> ppr k
379
380 pprTcTyThingCategory :: TcTyThing -> SDoc
381 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
382 pprTcTyThingCategory (ATyVar _ _)    = ptext SLIT("Type variable")
383 pprTcTyThingCategory (ATcId _ _)     = ptext SLIT("Local identifier")
384 pprTcTyThingCategory (AThing _)      = ptext SLIT("Kinded thing")
385 \end{code}
386
387 \begin{code}
388 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
389                         -- Innermost first.  Monadic so that we have a chance
390                         -- to deal with bound type variables just before error
391                         -- message construction
392 \end{code}
393
394
395 %************************************************************************
396 %*                                                                      *
397         Operations over ImportAvails
398 %*                                                                      *
399 %************************************************************************
400
401 ImportAvails summarises what was imported from where, irrespective
402 of whether the imported things are actually used or not
403 It is used      * when processing the export list
404                 * when constructing usage info for the inteface file
405                 * to identify the list of directly imported modules
406                         for initialisation purposes
407                 * when figuring out what things are really unused
408
409 \begin{code}
410 data ImportAvails 
411    = ImportAvails {
412         imp_env :: ModuleEnv NameSet,
413                 -- All the things imported, classified by 
414                 -- the *module qualifier* for its import
415                 --   e.g.        import List as Foo
416                 -- would add a binding Foo |-> ...stuff from List...
417                 -- to imp_env.
418                 -- 
419                 -- We need to classify them like this so that we can figure out 
420                 -- "module M" export specifiers in an export list 
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         imp_mods :: ModuleEnv (Module, Maybe Bool, SrcSpan),
428                 -- Domain is all directly-imported modules
429                 -- Maybe value answers the question "is the import restricted?"
430                 --   Nothing    => unrestricted import (e.g., "import Foo")
431                 --   Just True  => restricted import, at least one entity (e.g., "import Foo(x)")
432                 --   Just False => fully restricted import (e.g., "import Foo ()")
433                 --
434                 --  A distinction is made between the first and the third in order
435                 --  to more precisely emit warnings about unused imports.
436                 --
437                 -- We need the Module in the range because we can't get
438                 --      the keys of a ModuleEnv
439                 -- Used 
440                 --   (a) to help construct the usage information in 
441                 --       the interface file; if we import everything we
442                 --       need to recompile if the module version changes
443                 --   (b) to specify what child modules to initialise
444
445         imp_dep_mods :: ModuleEnv (Module, IsBootInterface),
446                 -- Home-package modules needed by the module being compiled
447                 --
448                 -- It doesn't matter whether any of these dependencies
449                 -- are actually *used* when compiling the module; they
450                 -- are listed if they are below it at all.  For
451                 -- example, suppose M imports A which imports X.  Then
452                 -- compiling M might not need to consult X.hi, but X
453                 -- is still listed in M's dependencies.
454
455         imp_dep_pkgs :: [PackageId],
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 :: [Module]
461                 -- Orphan modules below us in the import tree
462       }
463
464 mkModDeps :: [(Module, IsBootInterface)]
465           -> ModuleEnv (Module, IsBootInterface)
466 mkModDeps deps = foldl add emptyModuleEnv deps
467                where
468                  add env elt@(m,_) = extendModuleEnv env m elt
469
470 emptyImportAvails :: ImportAvails
471 emptyImportAvails = ImportAvails { imp_env      = emptyModuleEnv, 
472                                    imp_mods     = emptyModuleEnv,
473                                    imp_dep_mods = emptyModuleEnv,
474                                    imp_dep_pkgs = [],
475                                    imp_orphs    = [] }
476
477 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
478 plusImportAvails
479   (ImportAvails { imp_env = env1, imp_mods = mods1,
480                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
481   (ImportAvails { imp_env = env2, imp_mods = mods2,
482                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
483   = ImportAvails { imp_env      = plusModuleEnv_C unionNameSets env1 env2, 
484                    imp_mods     = mods1  `plusModuleEnv` mods2, 
485                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
486                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
487                    imp_orphs    = orphs1 `unionLists` orphs2 }
488   where
489     plus_mod_dep (m1, boot1) (m2, boot2) 
490         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
491                 -- Check mod-names match
492           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
493 \end{code}
494
495 %************************************************************************
496 %*                                                                      *
497         Avails, AvailEnv, etc
498 %*                                                                      *
499 v%************************************************************************
500
501 \begin{code}
502 plusAvail (Avail n1)       (Avail n2)       = Avail n1
503 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
504 -- Added SOF 4/97
505 #ifdef DEBUG
506 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
507 #endif
508
509 -------------------------
510 pruneAvails :: (Name -> Bool)   -- Keep if this is True
511             -> [AvailInfo]
512             -> [AvailInfo]
513 pruneAvails keep avails
514   = mapMaybe del avails
515   where
516     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
517     del (Avail n) | keep n    = Just (Avail n)
518                   | otherwise = Nothing
519     del (AvailTC n ns) | null ns'  = Nothing
520                        | otherwise = Just (AvailTC n ns')
521                        where
522                          ns' = filter keep ns
523 \end{code}
524
525 ---------------------------------------
526         AvailEnv and friends
527 ---------------------------------------
528
529 \begin{code}
530 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
531
532 emptyAvailEnv :: AvailEnv
533 emptyAvailEnv = emptyNameEnv
534
535 unitAvailEnv :: AvailInfo -> AvailEnv
536 unitAvailEnv a = unitNameEnv (availName a) a
537
538 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
539 plusAvailEnv = plusNameEnv_C plusAvail
540
541 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
542 lookupAvailEnv_maybe = lookupNameEnv
543
544 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
545 lookupAvailEnv env n = case lookupNameEnv env n of
546                          Just avail -> avail
547                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
548
549 availEnvElts = nameEnvElts
550
551 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
552 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
553
554 mkAvailEnv :: [AvailInfo] -> AvailEnv
555         -- 'avails' may have several items with the same availName
556         -- E.g  import Ix( Ix(..), index )
557         -- will give Ix(Ix,index,range) and Ix(index)
558         -- We want to combine these; addAvail does that
559 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
560 \end{code}
561
562 %************************************************************************
563 %*                                                                      *
564 \subsection{Where from}
565 %*                                                                      *
566 %************************************************************************
567
568 The @WhereFrom@ type controls where the renamer looks for an interface file
569
570 \begin{code}
571 data WhereFrom 
572   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
573   | ImportBySystem                      -- Non user import.
574
575 instance Outputable WhereFrom where
576   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
577                              | otherwise   = empty
578   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
579 \end{code}
580
581
582 %************************************************************************
583 %*                                                                      *
584 \subsection[Inst-types]{@Inst@ types}
585 %*                                                                      *
586 v%************************************************************************
587
588 An @Inst@ is either a dictionary, an instance of an overloaded
589 literal, or an instance of an overloaded value.  We call the latter a
590 ``method'' even though it may not correspond to a class operation.
591 For example, we might have an instance of the @double@ function at
592 type Int, represented by
593
594         Method 34 doubleId [Int] origin
595
596 \begin{code}
597 data Inst
598   = Dict
599         Name
600         TcPredType
601         InstLoc
602
603   | Method
604         Id
605
606         TcId    -- The overloaded function
607                         -- This function will be a global, local, or ClassOpId;
608                         --   inside instance decls (only) it can also be an InstId!
609                         -- The id needn't be completely polymorphic.
610                         -- You'll probably find its name (for documentation purposes)
611                         --        inside the InstOrigin
612
613         [TcType]        -- The types to which its polymorphic tyvars
614                         --      should be instantiated.
615                         -- These types must saturate the Id's foralls.
616
617         TcThetaType     -- The (types of the) dictionaries to which the function
618                         -- must be applied to get the method
619
620         TcTauType       -- The tau-type of the method
621
622         InstLoc
623
624         -- INVARIANT 1: in (Method u f tys theta tau loc)
625         --      type of (f tys dicts(from theta)) = tau
626
627         -- INVARIANT 2: tau must not be of form (Pred -> Tau)
628         --   Reason: two methods are considered equal if the 
629         --           base Id matches, and the instantiating types
630         --           match.  The TcThetaType should then match too.
631         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
632
633   | LitInst
634         Name
635         (HsOverLit Name)        -- The literal from the occurrence site
636                                 -- INVARIANT: never a rebindable-syntax literal
637                                 -- Reason: tcSyntaxName does unification, and we
638                                 --         don't want to deal with that during tcSimplify,
639                                 --         when resolving LitInsts
640         TcType          -- The type at which the literal is used
641         InstLoc
642 \end{code}
643
644 @Insts@ are ordered by their class/type info, rather than by their
645 unique.  This allows the context-reduction mechanism to use standard finite
646 maps to do their stuff.
647
648 \begin{code}
649 instance Ord Inst where
650   compare = cmpInst
651
652 instance Eq Inst where
653   (==) i1 i2 = case i1 `cmpInst` i2 of
654                  EQ    -> True
655                  other -> False
656
657 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
658 cmpInst (Dict _ _ _)              other                     = LT
659
660 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
661 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
662 cmpInst (Method _ _ _ _ _ _)      other                     = LT
663
664 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
665 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
666 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
667 \end{code}
668
669
670 %************************************************************************
671 %*                                                                      *
672 \subsection[Inst-collections]{LIE: a collection of Insts}
673 %*                                                                      *
674 %************************************************************************
675
676 \begin{code}
677 type LIE = Bag Inst
678
679 isEmptyLIE        = isEmptyBag
680 emptyLIE          = emptyBag
681 unitLIE inst      = unitBag inst
682 mkLIE insts       = listToBag insts
683 plusLIE lie1 lie2 = lie1 `unionBags` lie2
684 consLIE inst lie  = inst `consBag` lie
685 plusLIEs lies     = unionManyBags lies
686 lieToList         = bagToList
687 listToLIE         = listToBag
688 \end{code}
689
690
691 %************************************************************************
692 %*                                                                      *
693 \subsection[Inst-origin]{The @InstOrigin@ type}
694 %*                                                                      *
695 %************************************************************************
696
697 The @InstOrigin@ type gives information about where a dictionary came from.
698 This is important for decent error message reporting because dictionaries
699 don't appear in the original source code.  Doubtless this type will evolve...
700
701 It appears in TcMonad because there are a couple of error-message-generation
702 functions that deal with it.
703
704 \begin{code}
705 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
706
707 instLocSrcLoc :: InstLoc -> SrcLoc
708 instLocSrcLoc (InstLoc _ src_span _) = srcSpanStart src_span
709
710 instLocSrcSpan :: InstLoc -> SrcSpan
711 instLocSrcSpan (InstLoc _ src_span _) = src_span
712
713 data InstOrigin
714   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
715                                 -- Places that bind type variables and introduce
716                                 -- available constraints
717
718   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
719
720         -------------------------------------------------------
721         -- The rest are all occurrences: Insts that are 'wanted'
722         -------------------------------------------------------
723   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
724
725   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
726
727   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
728
729   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
730   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
731
732   | InstSigOrigin       -- A dict occurrence arising from instantiating
733                         -- a polymorphic type during a subsumption check
734
735   | RecordUpdOrigin
736   | InstScOrigin        -- Typechecking superclasses of an instance declaration
737   | DerivOrigin         -- Typechecking deriving
738   | DefaultOrigin       -- Typechecking a default decl
739   | DoOrigin            -- Arising from a do expression
740   | ProcOrigin          -- Arising from a proc expression
741 \end{code}
742
743 \begin{code}
744 pprInstLoc :: InstLoc -> SDoc
745 pprInstLoc (InstLoc orig locn _)
746   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
747   where
748     pp_orig (OccurrenceOf name)  = hsep [ptext SLIT("use of"), quotes (ppr name)]
749     pp_orig (IPOccOrigin name)   = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
750     pp_orig (IPBindOrigin name)  = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
751     pp_orig RecordUpdOrigin      = ptext SLIT("a record update")
752     pp_orig (LiteralOrigin lit)  = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
753     pp_orig (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
754     pp_orig (PArrSeqOrigin seq)  = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
755     pp_orig InstSigOrigin        = ptext SLIT("instantiating a type signature")
756     pp_orig InstScOrigin         = ptext SLIT("the superclasses of an instance declaration")
757     pp_orig DerivOrigin          = ptext SLIT("the 'deriving' clause of a data type declaration")
758     pp_orig DefaultOrigin        = ptext SLIT("a 'default' declaration")
759     pp_orig DoOrigin             = ptext SLIT("a do statement")
760     pp_orig ProcOrigin           = ptext SLIT("a proc expression")
761     pp_orig (SigOrigin info)     = pprSkolInfo info
762 \end{code}