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