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