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