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