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