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