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