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