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