2bb80bcad1063cb586427991bd457c948c9926be
[ghc-hetmet.git] / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP Project, Glasgow University, 1992-2002
4 %
5 \begin{code}
6 module TcRnTypes(
7         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
8         TcRef,
9
10         -- The environment types
11         Env(..), 
12         TcGblEnv(..), TcLclEnv(..), 
13         IfGblEnv(..), IfLclEnv(..), 
14
15         -- Ranamer types
16         ErrCtxt,
17         ImportAvails(..), emptyImportAvails, plusImportAvails, 
18         plusAvail, pruneAvails,  
19         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, 
20         mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
21         WhereFrom(..), mkModDeps,
22
23         -- Typechecker types
24         TcTyThing(..), pprTcTyThingCategory, 
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 hiding (LIE)
46 import HscTypes
47 import Packages
48 import Type
49 import TcType
50 import InstEnv
51 import FamInstEnv
52 import IOEnv
53 import RdrName
54 import Name
55 import NameEnv
56 import NameSet
57 import Var
58 import VarEnv
59 import Module
60 import UniqFM
61 import SrcLoc
62 import VarSet
63 import ErrUtils
64 import UniqSupply
65 import BasicTypes
66 import Util
67 import Bag
68 import Outputable
69 import ListSetOps
70
71 import Data.Maybe
72 import Data.List
73 \end{code}
74
75
76 %************************************************************************
77 %*                                                                      *
78                Standard monad definition for TcRn
79     All the combinators for the monad can be found in TcRnMonad
80 %*                                                                      *
81 %************************************************************************
82
83 The monad itself has to be defined here, because it is mentioned by ErrCtxt
84
85 \begin{code}
86 type TcRef a     = IORef a
87 type TcId        = Id                   -- Type may be a TcType
88 type TcIdSet     = IdSet
89 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
90
91 type TcRnIf a b c = IOEnv (Env a b) c
92 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
93
94 type IfG a  = IfM () a                          -- Top level
95 type IfL a  = IfM IfLclEnv a                    -- Nested
96 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
97 type RnM  a = TcRn a            -- Historical
98 type TcM  a = TcRn a            -- Historical
99 \end{code}
100
101
102 %************************************************************************
103 %*                                                                      *
104                 The main environment types
105 %*                                                                      *
106 %************************************************************************
107
108 \begin{code}
109 data Env gbl lcl        -- Changes as we move into an expression
110   = Env {
111         env_top  :: HscEnv,     -- Top-level stuff that never changes
112                                 -- Includes all info about imported things
113
114         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
115                                 -- Unique supply for local varibles
116
117         env_gbl  :: gbl,        -- Info about things defined at the top level
118                                 -- of the module being compiled
119
120         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
121                                 -- an expression
122     }
123
124 -- TcGblEnv describes the top-level of the module at the 
125 -- point at which the typechecker is finished work.
126 -- It is this structure that is handed on to the desugarer
127
128 data TcGblEnv
129   = TcGblEnv {
130         tcg_mod     :: Module,          -- Module being compiled
131         tcg_src     :: HscSource,       -- What kind of module 
132                                         -- (regular Haskell, hs-boot, ext-core)
133
134         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
135         tcg_default :: Maybe [Type],    -- Types used for defaulting
136                                         -- Nothing => no 'default' decl
137
138         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
139
140         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
141                 -- All TyCons and Classes (for this module) end up in here right away,
142                 -- along with their derived constructors, selectors.
143                 --
144                 -- (Ids defined in this module start in the local envt, 
145                 --  though they move to the global envt during zonking)
146
147         tcg_type_env_var :: TcRef TypeEnv,      
148                 -- Used only to initialise the interface-file
149                 -- typechecker in initIfaceTcRn, so that it can see stuff
150                 -- bound in this module when dealing with hi-boot recursions
151                 -- Updated at intervals (e.g. after dealing with types and classes)
152         
153         tcg_inst_env     :: InstEnv,    -- Instance envt for *home-package* 
154                                         -- modules; Includes the dfuns in 
155                                         -- tcg_insts
156         tcg_fam_inst_env :: FamInstEnv, -- Ditto for family instances
157
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 :: [AvailInfo],     -- 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_dus :: DefUses,     -- What is defined in this module and what is used.
168                                 -- The latter is used to generate 
169                                 --      (a) version tracking; no need to recompile if these
170                                 --              things have not changed version stamp
171                                 --      (b) unused-import info
172
173         tcg_keep :: TcRef NameSet,      -- Locally-defined top-level names to keep alive
174                 -- "Keep alive" means give them an Exported flag, so
175                 -- that the simplifier does not discard them as dead 
176                 -- code, and so that they are exposed in the interface file
177                 -- (but not to export to the user).
178                 --
179                 -- Some things, like dict-fun Ids and default-method Ids are 
180                 -- "born" with the Exported flag on, for exactly the above reason,
181                 -- but some we only discover as we go.  Specifically:
182                 --      * The to/from functions for generic data types
183                 --      * Top-level variables appearing free in the RHS of an orphan rule
184                 --      * Top-level variables appearing free in a TH bracket
185
186         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
187                 -- Used to generate version dependencies
188                 -- This records usages, rather like tcg_dus, but it has to
189                 -- be a mutable variable so it can be augmented 
190                 -- when we look up an instance.  These uses of dfuns are
191                 -- rather like the free variables of the program, but
192                 -- are implicit instead of explicit.
193
194         tcg_th_used :: TcRef Bool,      -- True <=> Template Haskell syntax used
195                 -- We need this so that we can generate a dependency on the
196                 -- Template Haskell package, becuase the desugarer is going to
197                 -- emit loads of references to TH symbols.  It's rather like 
198                 -- tcg_inst_uses; the reference is implicit rather than explicit,
199                 -- so we have to zap a mutable variable.
200
201         tcg_dfun_n  :: TcRef Int,       -- Allows us to number off the names of DFuns
202                 -- It's convenient to allocate an External Name for a DFun, with
203                 -- a permanently-fixed unique, just like other top-level functions
204                 -- defined in this module.  But that means we need a canonical 
205                 -- occurrence name, distinct from all other dfuns in this module,
206                 -- and this name supply serves that purpose (df1, df2, etc).
207
208                 -- The next fields accumulate the payload of the module
209                 -- The binds, rules and foreign-decl fiels are collected
210                 -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
211
212                 -- The next fields accumulate the payload of the
213                 -- module The binds, rules and foreign-decl fiels are
214                 -- collected initially in un-zonked form and are
215                 -- finally zonked in tcRnSrcDecls
216
217         tcg_rn_imports :: Maybe [LImportDecl Name],
218         tcg_rn_exports :: Maybe [Located (IE Name)],
219         tcg_rn_decls :: Maybe (HsGroup Name),   -- renamed decls, maybe
220                 -- Nothing <=> Don't retain renamed decls
221
222         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
223         tcg_deprecs   :: Deprecations,      -- ...Deprecations 
224         tcg_insts     :: [Instance],        -- ...Instances
225         tcg_fam_insts :: [FamInst],         -- ...Family instances
226         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
227         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
228
229         tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
230         tcg_hmi :: HaddockModInfo Name -- Haddock module information
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  :: UniqFM TyVar,     -- Nested tyvar bindings
270         if_id_env  :: UniqFM 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
331 {- Note [Given Insts]
332    ~~~~~~~~~~~~~~~~~~
333 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
334 and existential contexts. Consider
335         data T a where { T1 :: b -> b -> T [b] }
336         f :: Eq a => T a -> Bool
337         f (T1 x y) = [x]==[y]
338
339 The constructor T1 binds an existential variable 'b', and we need Eq [b].
340 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
341 pass it inwards.
342
343 -}
344
345 ---------------------------
346 -- Template Haskell levels 
347 ---------------------------
348
349 type ThLevel = Int      
350         -- Indicates how many levels of brackets we are inside
351         --      (always >= 0)
352         -- Incremented when going inside a bracket,
353         -- decremented when going inside a splice
354         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
355         --     original "Template meta-programmign for Haskell" paper
356
357 impLevel, topLevel :: ThLevel
358 topLevel = 1    -- Things defined at top level of this module
359 impLevel = 0    -- Imported things; they can be used inside a top level splice
360 --
361 -- For example: 
362 --      f = ...
363 --      g1 = $(map ...)         is OK
364 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
365
366
367 data ThStage
368   = Comp                                -- Ordinary compiling, at level topLevel
369   | Splice ThLevel                      -- Inside a splice
370   | Brack  ThLevel                      -- Inside brackets; 
371            (TcRef [PendingSplice])      --   accumulate pending splices here
372            (TcRef LIE)                  --   and type constraints here
373 topStage, topSpliceStage :: ThStage
374 topStage       = Comp
375 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
376
377 ---------------------------
378 -- Arrow-notation context
379 ---------------------------
380
381 {-
382 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
383 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
384 For example
385
386         proc x -> (e1 -< e2)
387
388 Here, x is not in scope in e1, but it is in scope in e2.  This can get
389 a bit complicated:
390
391         let x = 3 in
392         proc y -> (proc z -> e1) -< e2
393
394 Here, x and z are in scope in e1, but y is not.  We implement this by
395 recording the environment when passing a proc (using newArrowScope),
396 and returning to that (using escapeArrowScope) on the left of -< and the
397 head of (|..|).
398 -}
399
400 data ArrowCtxt
401   = NoArrowCtxt
402   | ArrowCtxt (Env TcGblEnv TcLclEnv)
403
404 -- Record the current environment (outside a proc)
405 newArrowScope :: TcM a -> TcM a
406 newArrowScope
407   = updEnv $ \env ->
408         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
409
410 -- Return to the stored environment (from the enclosing proc)
411 escapeArrowScope :: TcM a -> TcM a
412 escapeArrowScope
413   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
414         NoArrowCtxt -> env
415         ArrowCtxt env' -> env'
416
417 ---------------------------
418 -- TcTyThing
419 ---------------------------
420
421 data TcTyThing
422   = AGlobal TyThing             -- Used only in the return type of a lookup
423
424   | ATcId   {           -- Ids defined in this module; may not be fully zonked
425         tct_id :: TcId,         
426         tct_co :: Maybe HsWrapper,      -- Nothing <=>  Do not apply a GADT type refinement
427                                         --              I am wobbly, or have no free
428                                         --              type variables
429                                         -- Just co <=>  Apply any type refinement to me,
430                                         --              and record it in the coercion
431         tct_type  :: TcType,    -- Type of (coercion applied to id)
432         tct_level :: ThLevel }
433
434   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
435                                 -- is currently refined. We only need the Name
436                                 -- for error-message purposes
437
438   | AThing  TcKind              -- Used temporarily, during kind checking, for the
439                                 --      tycons and clases in this recursive group
440
441 instance Outputable TcTyThing where     -- Debugging only
442    ppr (AGlobal g)      = ppr g
443    ppr elt@(ATcId {})   = text "Identifier" <> 
444                           ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
445                                  <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
446    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
447    ppr (AThing k)       = text "AThing" <+> ppr k
448
449 pprTcTyThingCategory :: TcTyThing -> SDoc
450 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
451 pprTcTyThingCategory (ATyVar {})     = ptext SLIT("Type variable")
452 pprTcTyThingCategory (ATcId {})      = ptext SLIT("Local identifier")
453 pprTcTyThingCategory (AThing {})     = ptext SLIT("Kinded thing")
454 \end{code}
455
456 \begin{code}
457 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
458                         -- Innermost first.  Monadic so that we have a chance
459                         -- to deal with bound type variables just before error
460                         -- message construction
461 \end{code}
462
463
464 %************************************************************************
465 %*                                                                      *
466         Operations over ImportAvails
467 %*                                                                      *
468 %************************************************************************
469
470 ImportAvails summarises what was imported from where, irrespective
471 of whether the imported things are actually used or not
472 It is used      * when processing the export list
473                 * when constructing usage info for the inteface file
474                 * to identify the list of directly imported modules
475                         for initialisation purposes
476                 * when figuring out what things are really unused
477
478 \begin{code}
479 data ImportAvails 
480    = ImportAvails {
481         imp_env :: ModuleNameEnv [AvailInfo],
482                 -- All the things imported *unqualified*, classified by 
483                 -- the *module qualifier* for its import
484                 --   e.g.        import List as Foo
485                 -- would add a binding Foo |-> ...stuff from List...
486                 -- to imp_env.
487                 -- 
488                 -- This is exactly the list of things that will be exported
489                 -- by a 'module M' specifier in the export list.
490                 -- (see Haskell 98 Report Section 5.2).
491                 --
492                 -- Warning: there may be duplciates in this list,
493                 -- duplicates are removed at the use site (rnExports).
494                 -- We might consider turning this into a NameEnv at
495                 -- some point.
496
497         imp_mods :: ModuleEnv (Module, Bool, SrcSpan),
498                 -- Domain is all directly-imported modules
499                 -- Bool means:
500                 --   True => import was "import Foo ()"
501                 --   False  => import was some other form
502                 --
503                 -- We need the Module in the range because we can't get
504                 --      the keys of a ModuleEnv
505                 -- Used 
506                 --   (a) to help construct the usage information in 
507                 --       the interface file; if we import somethign we
508                 --       need to recompile if the export version changes
509                 --   (b) to specify what child modules to initialise
510                 --
511                 -- We need a full ModuleEnv rather than a ModuleNameEnv
512                 -- here, because we might be importing modules of the
513                 -- same name from different packages. (currently not the case,
514                 -- but might be in the future).
515
516         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
517                 -- Home-package modules needed by the module being compiled
518                 --
519                 -- It doesn't matter whether any of these dependencies
520                 -- are actually *used* when compiling the module; they
521                 -- are listed if they are below it at all.  For
522                 -- example, suppose M imports A which imports X.  Then
523                 -- compiling M might not need to consult X.hi, but X
524                 -- is still listed in M's dependencies.
525
526         imp_dep_pkgs :: [PackageId],
527                 -- Packages needed by the module being compiled, whether
528                 -- directly, or via other modules in this package, or via
529                 -- modules imported from other packages.
530
531         imp_orphs :: [Module],
532                 -- Orphan modules below us in the import tree (and maybe
533                 -- including us for imported modules) 
534
535         imp_finsts :: [Module],
536                 -- Family instance modules below us in the import tree  (and
537                 -- maybe including us for imported modules)
538
539         imp_parent :: NameEnv AvailInfo
540                 -- for the names in scope in this module, tells us
541                 -- the relationship between parents and children
542                 -- (eg. a TyCon is the parent of its DataCons, a
543                 -- class is the parent of its methods, etc.).
544       }
545
546 mkModDeps :: [(ModuleName, IsBootInterface)]
547           -> ModuleNameEnv (ModuleName, IsBootInterface)
548 mkModDeps deps = foldl add emptyUFM deps
549                where
550                  add env elt@(m,_) = addToUFM env m elt
551
552 emptyImportAvails :: ImportAvails
553 emptyImportAvails = ImportAvails { imp_env      = emptyUFM, 
554                                    imp_mods     = emptyModuleEnv,
555                                    imp_dep_mods = emptyUFM,
556                                    imp_dep_pkgs = [],
557                                    imp_orphs    = [],
558                                    imp_finsts   = [],
559                                    imp_parent   = emptyNameEnv }
560
561 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
562 plusImportAvails
563   (ImportAvails { imp_env = env1, imp_mods = mods1,
564                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
565                   imp_orphs = orphs1, imp_finsts = finsts1, 
566                   imp_parent = parent1 })
567   (ImportAvails { imp_env = env2, imp_mods = mods2,
568                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
569                   imp_orphs = orphs2, imp_finsts = finsts2, 
570                   imp_parent = parent2  })
571   = ImportAvails { imp_env      = plusUFM_C (++) env1 env2, 
572                    imp_mods     = mods1  `plusModuleEnv` mods2, 
573                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
574                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
575                    imp_orphs    = orphs1 `unionLists` orphs2,
576                    imp_finsts   = finsts1 `unionLists` finsts2,
577                    imp_parent   = plusNameEnv_C plus_avails parent1 parent2 }
578   where
579     plus_avails (AvailTC tc subs1) (AvailTC _ subs2)
580                 = AvailTC tc (nub (subs1 ++ subs2))
581     plus_avails avail _ = avail
582
583     plus_mod_dep (m1, boot1) (m2, boot2) 
584         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
585                 -- Check mod-names match
586           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
587 \end{code}
588
589 %************************************************************************
590 %*                                                                      *
591         Avails, AvailEnv, etc
592 %*                                                                      *
593 v%************************************************************************
594
595 \begin{code}
596 plusAvail (Avail n1)       (Avail n2)       = Avail n1
597 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
598 -- Added SOF 4/97
599 #ifdef DEBUG
600 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
601 #endif
602
603 -------------------------
604 pruneAvails :: (Name -> Bool)   -- Keep if this is True
605             -> [AvailInfo]
606             -> [AvailInfo]
607 pruneAvails keep avails
608   = mapMaybe del avails
609   where
610     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
611     del (Avail n) | keep n    = Just (Avail n)
612                   | otherwise = Nothing
613     del (AvailTC n ns) | null ns'  = Nothing
614                        | otherwise = Just (AvailTC n ns')
615                        where
616                          ns' = filter keep ns
617 \end{code}
618
619 ---------------------------------------
620         AvailEnv and friends
621 ---------------------------------------
622
623 \begin{code}
624 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
625
626 emptyAvailEnv :: AvailEnv
627 emptyAvailEnv = emptyNameEnv
628
629 unitAvailEnv :: AvailInfo -> AvailEnv
630 unitAvailEnv a = unitNameEnv (availName a) a
631
632 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
633 plusAvailEnv = plusNameEnv_C plusAvail
634
635 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
636 lookupAvailEnv_maybe = lookupNameEnv
637
638 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
639 lookupAvailEnv env n = case lookupNameEnv env n of
640                          Just avail -> avail
641                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
642
643 availEnvElts = nameEnvElts
644
645 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
646 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
647
648 mkAvailEnv :: [AvailInfo] -> AvailEnv
649         -- 'avails' may have several items with the same availName
650         -- E.g  import Ix( Ix(..), index )
651         -- will give Ix(Ix,index,range) and Ix(index)
652         -- We want to combine these; addAvail does that
653 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
654 \end{code}
655
656 %************************************************************************
657 %*                                                                      *
658 \subsection{Where from}
659 %*                                                                      *
660 %************************************************************************
661
662 The @WhereFrom@ type controls where the renamer looks for an interface file
663
664 \begin{code}
665 data WhereFrom 
666   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
667   | ImportBySystem                      -- Non user import.
668
669 instance Outputable WhereFrom where
670   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
671                              | otherwise   = empty
672   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
673 \end{code}
674
675
676 %************************************************************************
677 %*                                                                      *
678 \subsection[Inst-types]{@Inst@ types}
679 %*                                                                      *
680 v%************************************************************************
681
682 An @Inst@ is either a dictionary, an instance of an overloaded
683 literal, or an instance of an overloaded value.  We call the latter a
684 ``method'' even though it may not correspond to a class operation.
685 For example, we might have an instance of the @double@ function at
686 type Int, represented by
687
688         Method 34 doubleId [Int] origin
689
690 \begin{code}
691 data Inst
692   = Dict {
693         tci_name :: Name,
694         tci_pred :: TcPredType,
695         tci_loc  :: InstLoc 
696     }
697
698   | Method {
699         tci_id :: TcId,         -- The Id for the Inst
700
701         tci_oid :: TcId,        -- The overloaded function
702                 -- This function will be a global, local, or ClassOpId;
703                 --   inside instance decls (only) it can also be an InstId!
704                 -- The id needn't be completely polymorphic.
705                 -- You'll probably find its name (for documentation purposes)
706                 --        inside the InstOrigin
707
708         tci_tys :: [TcType],    -- The types to which its polymorphic tyvars
709                                 --      should be instantiated.
710                                 -- These types must saturate the Id's foralls.
711
712         tci_theta :: TcThetaType,       
713                         -- The (types of the) dictionaries to which the function
714                         -- must be applied to get the method
715
716         tci_loc :: InstLoc 
717     }
718         -- INVARIANT 1: in (Method m f tys theta tau loc)
719         --      type of m = type of (f tys dicts(from theta))
720
721         -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
722         --   Reason: two methods are considered equal if the 
723         --           base Id matches, and the instantiating types
724         --           match.  The TcThetaType should then match too.
725         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
726
727   | LitInst {
728         tci_name :: Name,
729         tci_lit  :: HsOverLit Name,     -- The literal from the occurrence site
730                         -- INVARIANT: never a rebindable-syntax literal
731                         -- Reason: tcSyntaxName does unification, and we
732                         --         don't want to deal with that during tcSimplify,
733                         --         when resolving LitInsts
734
735         tci_ty :: TcType,       -- The type at which the literal is used
736         tci_loc :: InstLoc
737     }
738 \end{code}
739
740 @Insts@ are ordered by their class/type info, rather than by their
741 unique.  This allows the context-reduction mechanism to use standard finite
742 maps to do their stuff.
743
744 \begin{code}
745 instance Ord Inst where
746   compare = cmpInst
747
748 instance Eq Inst where
749   (==) i1 i2 = case i1 `cmpInst` i2 of
750                  EQ    -> True
751                  other -> False
752
753 cmpInst d1@(Dict {})    d2@(Dict {})    = tci_pred d1 `tcCmpPred` tci_pred d2
754 cmpInst (Dict {})       other           = LT
755
756 cmpInst (Method {})     (Dict {})       = GT
757 cmpInst m1@(Method {})  m2@(Method {})  = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
758                                           (tci_tys m1 `tcCmpTypes` tci_tys m2)
759 cmpInst (Method {})     other           = LT
760
761 cmpInst (LitInst {})    (Dict {})       = GT
762 cmpInst (LitInst {})    (Method {})     = GT
763 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
764                                           (tci_ty l1 `tcCmpType` tci_ty l2)
765 \end{code}
766
767
768 %************************************************************************
769 %*                                                                      *
770 \subsection[Inst-collections]{LIE: a collection of Insts}
771 %*                                                                      *
772 %************************************************************************
773
774 \begin{code}
775 -- FIXME: Rename this. It clashes with (Located (IE ...))
776 type LIE = Bag Inst
777
778 isEmptyLIE        = isEmptyBag
779 emptyLIE          = emptyBag
780 unitLIE inst      = unitBag inst
781 mkLIE insts       = listToBag insts
782 plusLIE lie1 lie2 = lie1 `unionBags` lie2
783 consLIE inst lie  = inst `consBag` lie
784 plusLIEs lies     = unionManyBags lies
785 lieToList         = bagToList
786 listToLIE         = listToBag
787 \end{code}
788
789
790 %************************************************************************
791 %*                                                                      *
792 \subsection[Inst-origin]{The @InstOrigin@ type}
793 %*                                                                      *
794 %************************************************************************
795
796 The @InstOrigin@ type gives information about where a dictionary came from.
797 This is important for decent error message reporting because dictionaries
798 don't appear in the original source code.  Doubtless this type will evolve...
799
800 It appears in TcMonad because there are a couple of error-message-generation
801 functions that deal with it.
802
803 \begin{code}
804 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
805
806 instLocSrcLoc :: InstLoc -> SrcLoc
807 instLocSrcLoc (InstLoc _ src_span _) = srcSpanStart src_span
808
809 instLocSrcSpan :: InstLoc -> SrcSpan
810 instLocSrcSpan (InstLoc _ src_span _) = src_span
811
812 data InstOrigin
813   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
814                                 -- Places that bind type variables and introduce
815                                 -- available constraints
816
817   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
818
819         -------------------------------------------------------
820         -- The rest are all occurrences: Insts that are 'wanted'
821         -------------------------------------------------------
822   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
823
824   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
825
826   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
827
828   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
829   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
830
831   | InstSigOrigin       -- A dict occurrence arising from instantiating
832                         -- a polymorphic type during a subsumption check
833
834   | RecordUpdOrigin
835   | InstScOrigin        -- Typechecking superclasses of an instance declaration
836   | DerivOrigin         -- Typechecking deriving
837   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
838   | DefaultOrigin       -- Typechecking a default decl
839   | DoOrigin            -- Arising from a do expression
840   | ProcOrigin          -- Arising from a proc expression
841 \end{code}
842
843 \begin{code}
844 pprInstLoc :: InstLoc -> SDoc
845 pprInstLoc (InstLoc orig locn _)
846   = sep [text "arising from" <+> pp_orig orig, 
847          text "at" <+> ppr locn]
848   where
849     pp_orig (OccurrenceOf name)  = hsep [ptext SLIT("use of"), quotes (ppr name)]
850     pp_orig (IPOccOrigin name)   = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
851     pp_orig (IPBindOrigin name)  = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
852     pp_orig RecordUpdOrigin      = ptext SLIT("a record update")
853     pp_orig (LiteralOrigin lit)  = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
854     pp_orig (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
855     pp_orig (PArrSeqOrigin seq)  = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
856     pp_orig InstSigOrigin        = ptext SLIT("instantiating a type signature")
857     pp_orig InstScOrigin         = ptext SLIT("the superclasses of an instance declaration")
858     pp_orig DerivOrigin          = ptext SLIT("the 'deriving' clause of a data type declaration")
859     pp_orig StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
860     pp_orig DefaultOrigin        = ptext SLIT("a 'default' declaration")
861     pp_orig DoOrigin             = ptext SLIT("a do statement")
862     pp_orig ProcOrigin           = ptext SLIT("a proc expression")
863     pp_orig (SigOrigin info)     = pprSkolInfo info
864 \end{code}