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