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