[project @ 2005-06-21 10:44:37 by simonmar]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-2002
3 %
4 \begin{code}
5 module TcRnTypes(
6         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
7         TcRef,
8
9         -- The environment types
10         Env(..), 
11         TcGblEnv(..), TcLclEnv(..), 
12         IfGblEnv(..), IfLclEnv(..), 
13
14         -- Ranamer types
15         ErrCtxt,
16         ImportAvails(..), emptyImportAvails, plusImportAvails, 
17         plusAvail, pruneAvails,  
18         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, 
19         mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
20         WhereFrom(..), mkModDeps,
21
22         -- Typechecker types
23         TcTyThing(..), pprTcTyThingCategory, GadtRefinement,
24
25         -- Template Haskell
26         ThStage(..), topStage, topSpliceStage,
27         ThLevel, impLevel, topLevel,
28
29         -- 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, HsGroup )
46 import HscTypes         ( FixityEnv,
47                           HscEnv, TypeEnv, TyThing, 
48                           GenAvailInfo(..), AvailInfo, HscSource(..),
49                           availName, IsBootInterface, Deprecations )
50 import Packages         ( PackageId, HomeModules )
51 import Type             ( Type, TvSubstEnv, pprParendType, pprTyThingCategory )
52 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, SkolemInfo,
53                           TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes, pprSkolInfo )
54 import InstEnv          ( Instance, InstEnv )
55 import IOEnv
56 import RdrName          ( GlobalRdrEnv, LocalRdrEnv )
57 import Name             ( Name )
58 import NameEnv
59 import NameSet          ( NameSet, unionNameSets, DefUses )
60 import OccName          ( OccEnv )
61 import Var              ( Id, TyVar )
62 import VarEnv           ( TidyEnv )
63 import Module
64 import SrcLoc           ( SrcSpan, SrcLoc, srcSpanStart )
65 import VarSet           ( IdSet )
66 import ErrUtils         ( Messages, Message )
67 import UniqSupply       ( UniqSupply )
68 import BasicTypes       ( IPName )
69 import Util             ( thenCmp )
70 import Bag
71 import Outputable
72 import Maybe            ( mapMaybe )
73 import ListSetOps       ( unionLists )
74 \end{code}
75
76
77 %************************************************************************
78 %*                                                                      *
79                Standard monad definition for TcRn
80     All the combinators for the monad can be found in TcRnMonad
81 %*                                                                      *
82 %************************************************************************
83
84 The monad itself has to be defined here, because it is mentioned by ErrCtxt
85
86 \begin{code}
87 type TcRef a     = IORef a
88 type TcId        = Id                   -- Type may be a TcType
89 type TcIdSet     = IdSet
90 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
91
92
93
94 type TcRnIf a b c = IOEnv (Env a b) c
95 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
96 type IfG a  = IfM () a                          -- Top level
97 type IfL a  = IfM IfLclEnv a                    -- Nested
98 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
99 type RnM  a = TcRn a            -- Historical
100 type TcM  a = TcRn a            -- Historical
101 \end{code}
102
103
104 %************************************************************************
105 %*                                                                      *
106                 The main environment types
107 %*                                                                      *
108 %************************************************************************
109
110 \begin{code}
111 data Env gbl lcl        -- Changes as we move into an expression
112   = Env {
113         env_top  :: HscEnv,     -- Top-level stuff that never changes
114                                 -- Includes all info about imported things
115
116         env_us   :: TcRef UniqSupply,   -- Unique supply for local varibles
117
118         env_gbl  :: gbl,        -- Info about things defined at the top level
119                                 -- of the module being compiled
120
121         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
122                                 -- an expression
123     }
124
125 -- TcGblEnv describes the top-level of the module at the 
126 -- point at which the typechecker is finished work.
127 -- It is this structure that is handed on to the desugarer
128
129 data TcGblEnv
130   = TcGblEnv {
131         tcg_mod     :: Module,          -- Module being compiled
132         tcg_src     :: HscSource,       -- What kind of module 
133                                         -- (regular Haskell, hs-boot, ext-core)
134
135         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
136         tcg_default :: Maybe [Type],    -- Types used for defaulting
137                                         -- Nothing => no 'default' decl
138
139         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
140
141         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
142                 -- All TyCons and Classes (for this module) end up in here right away,
143                 -- along with their derived constructors, selectors.
144                 --
145                 -- (Ids defined in this module start in the local envt, 
146                 --  though they move to the global envt during zonking)
147
148         tcg_type_env_var :: TcRef TypeEnv,      
149                 -- Used only to initialise the interface-file
150                 -- typechecker in initIfaceTcRn, so that it can see stuff
151                 -- bound in this module when dealing with hi-boot recursions
152                 -- Updated at intervals (e.g. after dealing with types and classes)
153         
154         tcg_inst_env :: InstEnv,        -- Instance envt for *home-package* modules
155                                         -- Includes the dfuns in tcg_insts
156                 -- Now a bunch of things about this module that are simply 
157                 -- accumulated, but never consulted until the end.  
158                 -- Nevertheless, it's convenient to accumulate them along 
159                 -- with the rest of the info from this module.
160         tcg_exports :: NameSet,         -- What is exported
161         tcg_imports :: ImportAvails,    -- Information about what was imported 
162                                         --    from where, including things bound
163                                         --    in this module
164
165         tcg_home_mods :: HomeModules,
166                                 -- Calculated from ImportAvails, allows us to
167                                 -- call Packages.isHomeModule
168
169         tcg_dus :: DefUses,     -- What is defined in this module and what is used.
170                                 -- The latter is used to generate 
171                                 --      (a) version tracking; no need to recompile if these
172                                 --              things have not changed version stamp
173                                 --      (b) unused-import info
174
175         tcg_keep :: TcRef NameSet,      -- Locally-defined top-level names to keep alive
176                 -- "Keep alive" means give them an Exported flag, so
177                 -- that the simplifier does not discard them as dead 
178                 -- code, and so that they are exposed in the interface file
179                 -- (but not to export to the user).
180                 --
181                 -- Some things, like dict-fun Ids and default-method Ids are 
182                 -- "born" with the Exported flag on, for exactly the above reason,
183                 -- but some we only discover as we go.  Specifically:
184                 --      * The to/from functions for generic data types
185                 --      * Top-level variables appearing free in the RHS of an orphan rule
186                 --      * Top-level variables appearing free in a TH bracket
187
188         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
189                 -- Used to generate version dependencies
190                 -- This records usages, rather like tcg_dus, but it has to
191                 -- be a mutable variable so it can be augmented 
192                 -- when we look up an instance.  These uses of dfuns are
193                 -- rather like the free variables of the program, but
194                 -- are implicit instead of explicit.
195
196         tcg_th_used :: TcRef Bool,      -- True <=> Template Haskell syntax used
197                 -- We need this so that we can generate a dependency on the
198                 -- Template Haskell package, becuase the desugarer is going to
199                 -- emit loads of references to TH symbols.  It's rather like 
200                 -- tcg_inst_uses; the reference is implicit rather than explicit,
201                 -- so we have to zap a mutable variable.
202
203         tcg_dfun_n  :: TcRef Int,       -- Allows us to number off the names of DFuns
204                 -- It's convenient to allocate an External Name for a DFun, with
205                 -- a permanently-fixed unique, just like other top-level functions
206                 -- defined in this module.  But that means we need a canonical 
207                 -- occurrence name, distinct from all other dfuns in this module,
208                 -- and this name supply serves that purpose (df1, df2, etc).
209
210                 -- The next fields accumulate the payload of the module
211                 -- The binds, rules and foreign-decl fiels are collected
212                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
213
214                 -- The next fields accumulate the payload of the
215                 -- module The binds, rules and foreign-decl fiels are
216                 -- collected initially in un-zonked form and are
217                 -- finally zonked in tcRnSrcDecls
218
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  :: OccEnv TyVar,     -- Nested tyvar bindings
266         if_id_env  :: OccEnv 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         tcl_gadt  :: GadtRefinement     -- The current type refinement for GADTs
325
326 -----------------------------------------------------------
327 -- Not yet; it's a new complication and I want to see whether it bites
328 --      tcl_given :: [Inst]             -- Insts available in the current context (see Note [Given Insts])
329 -----------------------------------------------------------
330     }
331
332 type GadtRefinement = TvSubstEnv        -- Binds rigid type variables to their refinements
333
334 {- Note [Given Insts]
335    ~~~~~~~~~~~~~~~~~~
336 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
337 and existential contexts. Consider
338         data T a where { T1 :: b -> b -> T [b] }
339         f :: Eq a => T a -> Bool
340         f (T1 x y) = [x]==[y]
341
342 The constructor T1 binds an existential variable 'b', and we need Eq [b].
343 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
344 pass it inwards.
345
346 -}
347
348 ---------------------------
349 -- Template Haskell levels 
350 ---------------------------
351
352 type ThLevel = Int      
353         -- Indicates how many levels of brackets we are inside
354         --      (always >= 0)
355         -- Incremented when going inside a bracket,
356         -- decremented when going inside a splice
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   TcId ThLevel                -- Ids defined in this module; may not be fully zonked
426
427   | ATyVar  Name TcType                 -- Type variables; tv -> type.  It can't just be a TyVar
428                                         -- that is mutated to point to the type it is bound to,
429                                         -- because that would make it a wobbly type, and we
430                                         -- want pattern-bound lexically-scoped type variables to
431                                         -- be able to stand for rigid types
432
433   | AThing  TcKind                      -- Used temporarily, during kind checking, for the
434                                         --      tycons and clases in this recursive group
435
436 instance Outputable TcTyThing where     -- Debugging only
437    ppr (AGlobal g)      = ppr g
438    ppr (ATcId g tl)     = text "Identifier" <> 
439                           ifPprDebug (brackets (ppr g <> comma <> ppr tl))
440    ppr (ATyVar tv ty)   = text "Type variable" <+> quotes (ppr tv) <+> pprParendType ty
441    ppr (AThing k)       = text "AThing" <+> ppr k
442
443 pprTcTyThingCategory :: TcTyThing -> SDoc
444 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
445 pprTcTyThingCategory (ATyVar _ _)    = ptext SLIT("Type variable")
446 pprTcTyThingCategory (ATcId _ _)     = ptext SLIT("Local identifier")
447 pprTcTyThingCategory (AThing _)      = ptext SLIT("Kinded thing")
448 \end{code}
449
450 \begin{code}
451 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
452                         -- Innermost first.  Monadic so that we have a chance
453                         -- to deal with bound type variables just before error
454                         -- message construction
455 \end{code}
456
457
458 %************************************************************************
459 %*                                                                      *
460         Operations over ImportAvails
461 %*                                                                      *
462 %************************************************************************
463
464 ImportAvails summarises what was imported from where, irrespective
465 of whether the imported things are actually used or not
466 It is used      * when processing the export list
467                 * when constructing usage info for the inteface file
468                 * to identify the list of directly imported modules
469                         for initialisation purposes
470                 * when figuring out what things are really unused
471
472 \begin{code}
473 data ImportAvails 
474    = ImportAvails {
475         imp_env :: ModuleEnv NameSet,
476                 -- All the things imported, classified by 
477                 -- the *module qualifier* for its import
478                 --   e.g.        import List as Foo
479                 -- would add a binding Foo |-> ...stuff from List...
480                 -- to imp_env.
481                 -- 
482                 -- We need to classify them like this so that we can figure out 
483                 -- "module M" export specifiers in an export list 
484                 -- (see 1.4 Report Section 5.1.1).  Ultimately, we want to find 
485                 -- everything that is unambiguously in scope as 'M.x'
486                 -- and where plain 'x' is (perhaps ambiguously) in scope.
487                 -- So the starting point is all things that are in scope as 'M.x',
488                 -- which is what this field tells us.
489
490         imp_mods :: ModuleEnv (Module, Maybe Bool, SrcSpan),
491                 -- Domain is all directly-imported modules
492                 -- Maybe value answers the question "is the import restricted?"
493                 --   Nothing    => unrestricted import (e.g., "import Foo")
494                 --   Just True  => restricted import, at least one entity (e.g., "import Foo(x)")
495                 --   Just False => fully restricted import (e.g., "import Foo ()")
496                 --
497                 --  A distinction is made between the first and the third in order
498                 --  to more precisely emit warnings about unused imports.
499                 --
500                 -- We need the Module in the range because we can't get
501                 --      the keys of a ModuleEnv
502                 -- Used 
503                 --   (a) to help construct the usage information in 
504                 --       the interface file; if we import everything we
505                 --       need to recompile if the module version changes
506                 --   (b) to specify what child modules to initialise
507
508         imp_dep_mods :: ModuleEnv (Module, IsBootInterface),
509                 -- Home-package modules needed by the module being compiled
510                 --
511                 -- It doesn't matter whether any of these dependencies
512                 -- are actually *used* when compiling the module; they
513                 -- are listed if they are below it at all.  For
514                 -- example, suppose M imports A which imports X.  Then
515                 -- compiling M might not need to consult X.hi, but X
516                 -- is still listed in M's dependencies.
517
518         imp_dep_pkgs :: [PackageId],
519                 -- Packages needed by the module being compiled, whether
520                 -- directly, or via other modules in this package, or via
521                 -- modules imported from other packages.
522
523         imp_orphs :: [Module]
524                 -- Orphan modules below us in the import tree
525       }
526
527 mkModDeps :: [(Module, IsBootInterface)]
528           -> ModuleEnv (Module, IsBootInterface)
529 mkModDeps deps = foldl add emptyModuleEnv deps
530                where
531                  add env elt@(m,_) = extendModuleEnv env m elt
532
533 emptyImportAvails :: ImportAvails
534 emptyImportAvails = ImportAvails { imp_env      = emptyModuleEnv, 
535                                    imp_mods     = emptyModuleEnv,
536                                    imp_dep_mods = emptyModuleEnv,
537                                    imp_dep_pkgs = [],
538                                    imp_orphs    = [] }
539
540 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
541 plusImportAvails
542   (ImportAvails { imp_env = env1, imp_mods = mods1,
543                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
544   (ImportAvails { imp_env = env2, imp_mods = mods2,
545                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
546   = ImportAvails { imp_env      = plusModuleEnv_C unionNameSets env1 env2, 
547                    imp_mods     = mods1  `plusModuleEnv` mods2, 
548                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
549                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
550                    imp_orphs    = orphs1 `unionLists` orphs2 }
551   where
552     plus_mod_dep (m1, boot1) (m2, boot2) 
553         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
554                 -- Check mod-names match
555           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
556 \end{code}
557
558 %************************************************************************
559 %*                                                                      *
560         Avails, AvailEnv, etc
561 %*                                                                      *
562 v%************************************************************************
563
564 \begin{code}
565 plusAvail (Avail n1)       (Avail n2)       = Avail n1
566 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
567 -- Added SOF 4/97
568 #ifdef DEBUG
569 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
570 #endif
571
572 -------------------------
573 pruneAvails :: (Name -> Bool)   -- Keep if this is True
574             -> [AvailInfo]
575             -> [AvailInfo]
576 pruneAvails keep avails
577   = mapMaybe del avails
578   where
579     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
580     del (Avail n) | keep n    = Just (Avail n)
581                   | otherwise = Nothing
582     del (AvailTC n ns) | null ns'  = Nothing
583                        | otherwise = Just (AvailTC n ns')
584                        where
585                          ns' = filter keep ns
586 \end{code}
587
588 ---------------------------------------
589         AvailEnv and friends
590 ---------------------------------------
591
592 \begin{code}
593 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
594
595 emptyAvailEnv :: AvailEnv
596 emptyAvailEnv = emptyNameEnv
597
598 unitAvailEnv :: AvailInfo -> AvailEnv
599 unitAvailEnv a = unitNameEnv (availName a) a
600
601 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
602 plusAvailEnv = plusNameEnv_C plusAvail
603
604 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
605 lookupAvailEnv_maybe = lookupNameEnv
606
607 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
608 lookupAvailEnv env n = case lookupNameEnv env n of
609                          Just avail -> avail
610                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
611
612 availEnvElts = nameEnvElts
613
614 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
615 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
616
617 mkAvailEnv :: [AvailInfo] -> AvailEnv
618         -- 'avails' may have several items with the same availName
619         -- E.g  import Ix( Ix(..), index )
620         -- will give Ix(Ix,index,range) and Ix(index)
621         -- We want to combine these; addAvail does that
622 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
623 \end{code}
624
625 %************************************************************************
626 %*                                                                      *
627 \subsection{Where from}
628 %*                                                                      *
629 %************************************************************************
630
631 The @WhereFrom@ type controls where the renamer looks for an interface file
632
633 \begin{code}
634 data WhereFrom 
635   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
636   | ImportBySystem                      -- Non user import.
637
638 instance Outputable WhereFrom where
639   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
640                              | otherwise   = empty
641   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
642 \end{code}
643
644
645 %************************************************************************
646 %*                                                                      *
647 \subsection[Inst-types]{@Inst@ types}
648 %*                                                                      *
649 v%************************************************************************
650
651 An @Inst@ is either a dictionary, an instance of an overloaded
652 literal, or an instance of an overloaded value.  We call the latter a
653 ``method'' even though it may not correspond to a class operation.
654 For example, we might have an instance of the @double@ function at
655 type Int, represented by
656
657         Method 34 doubleId [Int] origin
658
659 \begin{code}
660 data Inst
661   = Dict
662         Name
663         TcPredType
664         InstLoc
665
666   | Method
667         Id
668
669         TcId    -- The overloaded function
670                         -- This function will be a global, local, or ClassOpId;
671                         --   inside instance decls (only) it can also be an InstId!
672                         -- The id needn't be completely polymorphic.
673                         -- You'll probably find its name (for documentation purposes)
674                         --        inside the InstOrigin
675
676         [TcType]        -- The types to which its polymorphic tyvars
677                         --      should be instantiated.
678                         -- These types must saturate the Id's foralls.
679
680         TcThetaType     -- The (types of the) dictionaries to which the function
681                         -- must be applied to get the method
682
683         TcTauType       -- The tau-type of 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 type LIE = Bag Inst
741
742 isEmptyLIE        = isEmptyBag
743 emptyLIE          = emptyBag
744 unitLIE inst      = unitBag inst
745 mkLIE insts       = listToBag insts
746 plusLIE lie1 lie2 = lie1 `unionBags` lie2
747 consLIE inst lie  = inst `consBag` lie
748 plusLIEs lies     = unionManyBags lies
749 lieToList         = bagToList
750 listToLIE         = listToBag
751 \end{code}
752
753
754 %************************************************************************
755 %*                                                                      *
756 \subsection[Inst-origin]{The @InstOrigin@ type}
757 %*                                                                      *
758 %************************************************************************
759
760 The @InstOrigin@ type gives information about where a dictionary came from.
761 This is important for decent error message reporting because dictionaries
762 don't appear in the original source code.  Doubtless this type will evolve...
763
764 It appears in TcMonad because there are a couple of error-message-generation
765 functions that deal with it.
766
767 \begin{code}
768 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
769
770 instLocSrcLoc :: InstLoc -> SrcLoc
771 instLocSrcLoc (InstLoc _ src_span _) = srcSpanStart src_span
772
773 instLocSrcSpan :: InstLoc -> SrcSpan
774 instLocSrcSpan (InstLoc _ src_span _) = src_span
775
776 data InstOrigin
777   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
778                                 -- Places that bind type variables and introduce
779                                 -- available constraints
780
781   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
782
783         -------------------------------------------------------
784         -- The rest are all occurrences: Insts that are 'wanted'
785         -------------------------------------------------------
786   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
787
788   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
789
790   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
791
792   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
793   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
794
795   | InstSigOrigin       -- A dict occurrence arising from instantiating
796                         -- a polymorphic type during a subsumption check
797
798   | RecordUpdOrigin
799   | InstScOrigin        -- Typechecking superclasses of an instance declaration
800   | DerivOrigin         -- Typechecking deriving
801   | DefaultOrigin       -- Typechecking a default decl
802   | DoOrigin            -- Arising from a do expression
803   | ProcOrigin          -- Arising from a proc expression
804 \end{code}
805
806 \begin{code}
807 pprInstLoc :: InstLoc -> SDoc
808 pprInstLoc (InstLoc orig locn _)
809   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
810   where
811     pp_orig (OccurrenceOf name)  = hsep [ptext SLIT("use of"), quotes (ppr name)]
812     pp_orig (IPOccOrigin name)   = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
813     pp_orig (IPBindOrigin name)  = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
814     pp_orig RecordUpdOrigin      = ptext SLIT("a record update")
815     pp_orig (LiteralOrigin lit)  = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
816     pp_orig (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
817     pp_orig (PArrSeqOrigin seq)  = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
818     pp_orig InstSigOrigin        = ptext SLIT("instantiating a type signature")
819     pp_orig InstScOrigin         = ptext SLIT("the superclasses of an instance declaration")
820     pp_orig DerivOrigin          = ptext SLIT("the 'deriving' clause of a data type declaration")
821     pp_orig DefaultOrigin        = ptext SLIT("a 'default' declaration")
822     pp_orig DoOrigin             = ptext SLIT("a do statement")
823     pp_orig ProcOrigin           = ptext SLIT("a proc expression")
824     pp_orig (SigOrigin info)     = pprSkolInfo info
825 \end{code}