daed79dbd48a4b3bb4e27c8404090e175ca67eba
[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, RecFieldEnv(..),
17         ImportAvails(..), emptyImportAvails, plusImportAvails, 
18         WhereFrom(..), mkModDeps,
19
20         -- Typechecker types
21         TcTyThing(..), pprTcTyThingCategory, RefinementVisibility(..),
22
23         -- Template Haskell
24         ThStage(..), topStage, topAnnStage, topSpliceStage,
25         ThLevel, impLevel, topLevel,
26
27         -- Arrows
28         ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
29
30         -- Insts
31         Inst(..), EqInstCo, InstOrigin(..), InstLoc(..), 
32         pprInstLoc, pprInstArising, instLocSpan, instLocOrigin, setInstLoc,
33         LIE, emptyLIE, unitLIE, plusLIE, consLIE, instLoc, instSpan,
34         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
35
36         -- Misc other types
37         TcId, TcIdSet, TcDictBinds, TcTyVarBind(..), TcTyVarBinds
38         
39   ) where
40
41 #include "HsVersions.h"
42
43 import HsSyn hiding (LIE)
44 import HscTypes
45 import Type
46 import Coercion
47 import TcType
48 import Annotations
49 import InstEnv
50 import FamInstEnv
51 import IOEnv
52 import RdrName
53 import Name
54 import NameEnv
55 import NameSet
56 import Var
57 import VarEnv
58 import Module
59 import LazyUniqFM
60 import SrcLoc
61 import VarSet
62 import ErrUtils
63 import UniqSupply
64 import BasicTypes
65 import Util
66 import Bag
67 import Outputable
68 import ListSetOps
69 import FastString
70
71 import Data.Set (Set)
72 \end{code}
73
74
75 %************************************************************************
76 %*                                                                      *
77                Standard monad definition for TcRn
78     All the combinators for the monad can be found in TcRnMonad
79 %*                                                                      *
80 %************************************************************************
81
82 The monad itself has to be defined here, because it is mentioned by ErrCtxt
83
84 \begin{code}
85 type TcRef a     = IORef a
86 type TcId        = Id                   -- Type may be a TcType
87 type TcIdSet     = IdSet
88 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
89
90 type TcRnIf a b c = IOEnv (Env a b) c
91 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
92
93 type IfG a  = IfM () a                          -- Top level
94 type IfL a  = IfM IfLclEnv a                    -- Nested
95 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
96 type RnM  a = TcRn a            -- Historical
97 type TcM  a = TcRn a            -- Historical
98 \end{code}
99
100 Representation of type bindings to uninstantiated meta variables used during
101 constraint solving.
102
103 \begin{code}
104 data TcTyVarBind = TcTyVarBind TcTyVar TcType
105
106 type TcTyVarBinds = Bag TcTyVarBind
107
108 instance Outputable TcTyVarBind where
109   ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
110 \end{code}
111
112
113 %************************************************************************
114 %*                                                                      *
115                 The main environment types
116 %*                                                                      *
117 %************************************************************************
118
119 \begin{code}
120 data Env gbl lcl        -- Changes as we move into an expression
121   = Env {
122         env_top  :: HscEnv,     -- Top-level stuff that never changes
123                                 -- Includes all info about imported things
124
125         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
126                                 -- Unique supply for local varibles
127
128         env_gbl  :: gbl,        -- Info about things defined at the top level
129                                 -- of the module being compiled
130
131         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
132     }
133
134 -- TcGblEnv describes the top-level of the module at the 
135 -- point at which the typechecker is finished work.
136 -- It is this structure that is handed on to the desugarer
137
138 data TcGblEnv
139   = TcGblEnv {
140         tcg_mod     :: Module,         -- ^ Module being compiled
141         tcg_src     :: HscSource,
142           -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
143
144         tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
145         tcg_default :: Maybe [Type],
146           -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
147
148         tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
149         tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
150
151         tcg_type_env :: TypeEnv,
152           -- ^ Global type env for the module we are compiling now.  All
153           -- TyCons and Classes (for this module) end up in here right away,
154           -- along with their derived constructors, selectors.
155           --
156           -- (Ids defined in this module start in the local envt, though they
157           --  move to the global envt during zonking)
158
159         tcg_type_env_var :: TcRef TypeEnv,
160                 -- Used only to initialise the interface-file
161                 -- typechecker in initIfaceTcRn, so that it can see stuff
162                 -- bound in this module when dealing with hi-boot recursions
163                 -- Updated at intervals (e.g. after dealing with types and classes)
164         
165         tcg_inst_env     :: InstEnv,
166           -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
167           -- tcg_insts
168         tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
169
170                 -- Now a bunch of things about this module that are simply 
171                 -- accumulated, but never consulted until the end.  
172                 -- Nevertheless, it's convenient to accumulate them along 
173                 -- with the rest of the info from this module.
174         tcg_exports :: [AvailInfo],     -- ^ What is exported
175         tcg_imports :: ImportAvails,
176           -- ^ Information about what was imported from where, including
177           -- things bound in this module.
178
179         tcg_dus :: DefUses,
180           -- ^ What is defined in this module and what is used.
181           -- The latter is used to generate
182           --
183           --  (a) version tracking; no need to recompile if these things have
184           --      not changed version stamp
185           --
186           --  (b) unused-import info
187
188         tcg_keep :: TcRef NameSet,
189           -- ^ Locally-defined top-level names to keep alive.
190           --
191           -- "Keep alive" means give them an Exported flag, so that the
192           -- simplifier does not discard them as dead code, and so that they
193           -- are exposed in the interface file (but not to export to the
194           -- user).
195           --
196           -- Some things, like dict-fun Ids and default-method Ids are "born"
197           -- with the Exported flag on, for exactly the above reason, but some
198           -- we only discover as we go.  Specifically:
199           --
200           --   * The to/from functions for generic data types
201           --
202           --   * Top-level variables appearing free in the RHS of an orphan
203           --     rule
204           --
205           --   * Top-level variables appearing free in a TH bracket
206
207         tcg_inst_uses :: TcRef NameSet,
208           -- ^ Home-package Dfuns actually used.
209           --
210           -- Used to generate version dependencies This records usages, rather
211           -- like tcg_dus, but it has to be a mutable variable so it can be
212           -- augmented when we look up an instance.  These uses of dfuns are
213           -- rather like the free variables of the program, but are implicit
214           -- instead of explicit.
215
216         tcg_th_used :: TcRef Bool,
217           -- ^ @True@ <=> Template Haskell syntax used.
218           --
219           -- We need this so that we can generate a dependency on the Template
220           -- Haskell package, becuase the desugarer is going to emit loads of
221           -- references to TH symbols.  It's rather like tcg_inst_uses; the
222           -- reference is implicit rather than explicit, so we have to zap a
223           -- mutable variable.
224
225         tcg_dfun_n  :: TcRef Int,
226           -- ^ Allows us to number off the names of DFuns.
227           --
228           -- It's convenient to allocate an External Name for a DFun, with
229           -- a permanently-fixed unique, just like other top-level functions
230           -- defined in this module.  But that means we need a canonical
231           -- occurrence name, distinct from all other dfuns in this module,
232           -- and this name supply serves that purpose (df1, df2, etc).
233
234         -- The next fields accumulate the payload of the module
235         -- The binds, rules and foreign-decl fiels are collected
236         -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
237
238         tcg_rn_exports :: Maybe [Located (IE Name)],
239         tcg_rn_imports :: [LImportDecl Name],
240                 -- Keep the renamed imports regardless.  They are not 
241                 -- voluminous and are needed if you want to report unused imports
242         tcg_used_rdrnames :: TcRef (Set RdrName),
243         tcg_rn_decls :: Maybe (HsGroup Name),
244           -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
245           -- decls.
246
247         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
248         tcg_warns     :: Warnings,          -- ...Warnings and deprecations
249         tcg_anns      :: [Annotation],      -- ...Annotations
250         tcg_insts     :: [Instance],        -- ...Instances
251         tcg_fam_insts :: [FamInst],         -- ...Family instances
252         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
253         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
254
255         tcg_doc :: Maybe (HsDoc Name), -- ^ Maybe Haddock documentation
256         tcg_hmi :: HaddockModInfo Name, -- ^ Haddock module information
257         tcg_hpc :: AnyHpcUsage -- ^ @True@ if any part of the prog uses hpc
258                                -- instrumentation.
259     }
260
261 data RecFieldEnv 
262   = RecFields (NameEnv [Name])  -- Maps a constructor name *in this module*
263                                 -- to the fields for that constructor
264               NameSet           -- Set of all fields declared *in this module*;
265                                 -- used to suppress name-shadowing complaints
266                                 -- when using record wild cards
267                                 -- E.g.  let fld = e in C {..}
268         -- This is used when dealing with ".." notation in record 
269         -- construction and pattern matching.
270         -- The FieldEnv deals *only* with constructors defined in *this*
271         -- module.  For imported modules, we get the same info from the
272         -- TypeEnv
273 \end{code}
274
275 %************************************************************************
276 %*                                                                      *
277                 The interface environments
278               Used when dealing with IfaceDecls
279 %*                                                                      *
280 %************************************************************************
281
282 \begin{code}
283 data IfGblEnv 
284   = IfGblEnv {
285         -- The type environment for the module being compiled,
286         -- in case the interface refers back to it via a reference that
287         -- was originally a hi-boot file.
288         -- We need the module name so we can test when it's appropriate
289         -- to look in this env.
290         if_rec_types :: Maybe (Module, IfG TypeEnv)
291                 -- Allows a read effect, so it can be in a mutable
292                 -- variable; c.f. handling the external package type env
293                 -- Nothing => interactive stuff, no loops possible
294     }
295
296 data IfLclEnv
297   = IfLclEnv {
298         -- The module for the current IfaceDecl
299         -- So if we see   f = \x -> x
300         -- it means M.f = \x -> x, where M is the if_mod
301         if_mod :: Module,
302
303         -- The field is used only for error reporting
304         -- if (say) there's a Lint error in it
305         if_loc :: SDoc,
306                 -- Where the interface came from:
307                 --      .hi file, or GHCi state, or ext core
308                 -- plus which bit is currently being examined
309
310         if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
311         if_id_env  :: UniqFM Id         -- Nested id binding
312     }
313 \end{code}
314
315
316 %************************************************************************
317 %*                                                                      *
318                 The local typechecker environment
319 %*                                                                      *
320 %************************************************************************
321
322 The Global-Env/Local-Env story
323 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
324 During type checking, we keep in the tcg_type_env
325         * All types and classes
326         * All Ids derived from types and classes (constructors, selectors)
327
328 At the end of type checking, we zonk the local bindings,
329 and as we do so we add to the tcg_type_env
330         * Locally defined top-level Ids
331
332 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
333         a) fed back (via the knot) to typechecking the 
334            unfoldings of interface signatures
335         b) used in the ModDetails of this module
336
337 \begin{code}
338 data TcLclEnv           -- Changes as we move inside an expression
339                         -- Discarded after typecheck/rename; not passed on to desugarer
340   = TcLclEnv {
341         tcl_loc  :: SrcSpan,            -- Source span
342         tcl_ctxt :: ErrCtxt,            -- Error context
343         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
344
345         tcl_th_ctxt    :: ThStage,            -- Template Haskell context
346         tcl_arrow_ctxt :: ArrowCtxt,          -- Arrow-notation context
347
348         tcl_rdr :: LocalRdrEnv,         -- Local name envt
349                 -- Maintained during renaming, of course, but also during
350                 -- type checking, solely so that when renaming a Template-Haskell
351                 -- splice we have the right environment for the renamer.
352                 -- 
353                 --   Does *not* include global name envt; may shadow it
354                 --   Includes both ordinary variables and type variables;
355                 --   they are kept distinct because tyvar have a different
356                 --   occurrence contructor (Name.TvOcc)
357                 -- We still need the unsullied global name env so that
358                 --   we can look up record field names
359
360         tcl_env  :: NameEnv TcTyThing,  -- The local type environment: Ids and
361                                         -- TyVars defined in this module
362                                         
363         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
364                         -- Namely, the in-scope TyVars bound in tcl_env, 
365                         -- plus the tyvars mentioned in the types of Ids bound
366                         -- in tcl_lenv. 
367                         -- Why mutable? see notes with tcGetGlobalTyVars
368
369         tcl_lie   :: TcRef LIE,         -- Place to accumulate type constraints
370
371         tcl_tybinds :: TcRef TcTyVarBinds -- Meta and coercion type variable
372                                           -- bindings accumulated during
373                                           -- constraint solving
374     }
375
376
377 {- Note [Given Insts]
378    ~~~~~~~~~~~~~~~~~~
379 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
380 and existential contexts. Consider
381         data T a where { T1 :: b -> b -> T [b] }
382         f :: Eq a => T a -> Bool
383         f (T1 x y) = [x]==[y]
384
385 The constructor T1 binds an existential variable 'b', and we need Eq [b].
386 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
387 pass it inwards.
388
389 -}
390
391 ---------------------------
392 -- Template Haskell levels 
393 ---------------------------
394
395 type ThLevel = Int      
396         -- Indicates how many levels of brackets we are inside
397         --      (always >= 0)
398         -- Incremented when going inside a bracket,
399         -- decremented when going inside a splice
400         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
401         --     original "Template meta-programming for Haskell" paper
402
403 impLevel, topLevel :: ThLevel
404 topLevel = 1    -- Things defined at top level of this module
405 impLevel = 0    -- Imported things; they can be used inside a top level splice
406 --
407 -- For example: 
408 --      f = ...
409 --      g1 = $(map ...)         is OK
410 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
411
412
413 data ThStage
414   = Comp   ThLevel                      -- Ordinary compiling, usually at level topLevel but annotations use a lower level
415   | Splice ThLevel                      -- Inside a splice
416   | Brack  ThLevel                      -- Inside brackets; 
417            (TcRef [PendingSplice])      --   accumulate pending splices here
418            (TcRef LIE)                  --   and type constraints here
419 topStage, topAnnStage, topSpliceStage :: ThStage
420 topStage       = Comp topLevel
421 topAnnStage    = Comp (topLevel - 1)
422 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
423
424 ---------------------------
425 -- Arrow-notation context
426 ---------------------------
427
428 {-
429 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
430 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
431 For example
432
433         proc x -> (e1 -< e2)
434
435 Here, x is not in scope in e1, but it is in scope in e2.  This can get
436 a bit complicated:
437
438         let x = 3 in
439         proc y -> (proc z -> e1) -< e2
440
441 Here, x and z are in scope in e1, but y is not.  We implement this by
442 recording the environment when passing a proc (using newArrowScope),
443 and returning to that (using escapeArrowScope) on the left of -< and the
444 head of (|..|).
445 -}
446
447 data ArrowCtxt
448   = NoArrowCtxt
449   | ArrowCtxt (Env TcGblEnv TcLclEnv)
450
451 -- Record the current environment (outside a proc)
452 newArrowScope :: TcM a -> TcM a
453 newArrowScope
454   = updEnv $ \env ->
455         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
456
457 -- Return to the stored environment (from the enclosing proc)
458 escapeArrowScope :: TcM a -> TcM a
459 escapeArrowScope
460   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
461         NoArrowCtxt -> env
462         ArrowCtxt env' -> env'
463
464 ---------------------------
465 -- TcTyThing
466 ---------------------------
467
468 data TcTyThing
469   = AGlobal TyThing             -- Used only in the return type of a lookup
470
471   | ATcId   {           -- Ids defined in this module; may not be fully zonked
472         tct_id :: TcId,         
473         tct_co :: RefinementVisibility, -- Previously: Maybe HsWrapper
474                                         -- Nothing <=>  Do not apply a GADT type refinement
475                                         --              I am wobbly, or have no free
476                                         --              type variables
477                                         -- Just co <=>  Apply any type refinement to me,
478                                         --              and record it in the coercion
479         tct_type  :: TcType,    -- Type of (coercion applied to id)
480         tct_level :: ThLevel }
481
482   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
483                                 -- is currently refined. We only need the Name
484                                 -- for error-message purposes
485
486   | AThing  TcKind              -- Used temporarily, during kind checking, for the
487                                 --      tycons and clases in this recursive group
488
489 data RefinementVisibility
490   = Unrefineable                        -- Do not apply a GADT refinement
491                                         -- I have no free variables     
492
493   | Rigid HsWrapper                     -- Apply any refinement to me
494                                         -- and record it in the coercion
495
496   | Wobbly                              -- Do not apply a GADT refinement
497                                         -- I am wobbly
498
499   | WobblyInvisible                     -- Wobbly type, not available inside current
500                                         -- GADT refinement
501
502 instance Outputable TcTyThing where     -- Debugging only
503    ppr (AGlobal g)      = pprTyThing g
504    ppr elt@(ATcId {})   = text "Identifier" <> 
505                           ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
506                                  <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
507    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
508    ppr (AThing k)       = text "AThing" <+> ppr k
509
510 pprTcTyThingCategory :: TcTyThing -> SDoc
511 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
512 pprTcTyThingCategory (ATyVar {})     = ptext (sLit "Type variable")
513 pprTcTyThingCategory (ATcId {})      = ptext (sLit "Local identifier")
514 pprTcTyThingCategory (AThing {})     = ptext (sLit "Kinded thing")
515
516 instance Outputable RefinementVisibility where
517     ppr Unrefineable          = ptext (sLit "unrefineable")
518     ppr (Rigid co)            = ptext (sLit "rigid") <+> ppr co
519     ppr Wobbly                = ptext (sLit "wobbly")
520     ppr WobblyInvisible       = ptext (sLit "wobbly-invisible")
521
522 \end{code}
523
524 \begin{code}
525 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
526                         -- Innermost first.  Monadic so that we have a chance
527                         -- to deal with bound type variables just before error
528                         -- message construction
529 \end{code}
530
531
532 %************************************************************************
533 %*                                                                      *
534         Operations over ImportAvails
535 %*                                                                      *
536 %************************************************************************
537
538 \begin{code}
539 -- | 'ImportAvails' summarises what was imported from where, irrespective of
540 -- whether the imported things are actually used or not.  It is used:
541 --
542 --  * when processing the export list,
543 --
544 --  * when constructing usage info for the interface file,
545 --
546 --  * to identify the list of directly imported modules for initialisation
547 --    purposes and for optimised overlap checking of family instances,
548 --
549 --  * when figuring out what things are really unused
550 --
551 data ImportAvails 
552    = ImportAvails {
553         imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
554           -- ^ Domain is all directly-imported modules
555           -- The 'ModuleName' is what the module was imported as, e.g. in
556           -- @
557           --     import Foo as Bar
558           -- @
559           -- it is @Bar@.
560           --
561           -- The 'Bool' means:
562           --
563           --  - @True@ => import was @import Foo ()@
564           --
565           --  - @False@ => import was some other form
566           --
567           -- Used
568           --
569           --   (a) to help construct the usage information in the interface
570           --       file; if we import somethign we need to recompile if the
571           --       export version changes
572           --
573           --   (b) to specify what child modules to initialise
574           --
575           -- We need a full ModuleEnv rather than a ModuleNameEnv here,
576           -- because we might be importing modules of the same name from
577           -- different packages. (currently not the case, but might be in the
578           -- future).
579
580         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
581           -- ^ Home-package modules needed by the module being compiled
582           --
583           -- It doesn't matter whether any of these dependencies
584           -- are actually /used/ when compiling the module; they
585           -- are listed if they are below it at all.  For
586           -- example, suppose M imports A which imports X.  Then
587           -- compiling M might not need to consult X.hi, but X
588           -- is still listed in M's dependencies.
589
590         imp_dep_pkgs :: [PackageId],
591           -- ^ Packages needed by the module being compiled, whether directly,
592           -- or via other modules in this package, or via modules imported
593           -- from other packages.
594
595         imp_orphs :: [Module],
596           -- ^ Orphan modules below us in the import tree (and maybe including
597           -- us for imported modules)
598
599         imp_finsts :: [Module]
600           -- ^ Family instance modules below us in the import tree (and maybe
601           -- including us for imported modules)
602       }
603
604 mkModDeps :: [(ModuleName, IsBootInterface)]
605           -> ModuleNameEnv (ModuleName, IsBootInterface)
606 mkModDeps deps = foldl add emptyUFM deps
607                where
608                  add env elt@(m,_) = addToUFM env m elt
609
610 emptyImportAvails :: ImportAvails
611 emptyImportAvails = ImportAvails { imp_mods     = emptyModuleEnv,
612                                    imp_dep_mods = emptyUFM,
613                                    imp_dep_pkgs = [],
614                                    imp_orphs    = [],
615                                    imp_finsts   = [] }
616
617 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
618 plusImportAvails
619   (ImportAvails { imp_mods = mods1,
620                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
621                   imp_orphs = orphs1, imp_finsts = finsts1 })
622   (ImportAvails { imp_mods = mods2,
623                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
624                   imp_orphs = orphs2, imp_finsts = finsts2 })
625   = ImportAvails { imp_mods     = plusModuleEnv_C (++) mods1 mods2,     
626                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
627                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
628                    imp_orphs    = orphs1 `unionLists` orphs2,
629                    imp_finsts   = finsts1 `unionLists` finsts2 }
630   where
631     plus_mod_dep (m1, boot1) (m2, boot2) 
632         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
633                 -- Check mod-names match
634           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
635 \end{code}
636
637 %************************************************************************
638 %*                                                                      *
639 \subsection{Where from}
640 %*                                                                      *
641 %************************************************************************
642
643 The @WhereFrom@ type controls where the renamer looks for an interface file
644
645 \begin{code}
646 data WhereFrom 
647   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
648   | ImportBySystem                      -- Non user import.
649
650 instance Outputable WhereFrom where
651   ppr (ImportByUser is_boot) | is_boot     = ptext (sLit "{- SOURCE -}")
652                              | otherwise   = empty
653   ppr ImportBySystem                       = ptext (sLit "{- SYSTEM -}")
654 \end{code}
655
656
657 %************************************************************************
658 %*                                                                      *
659 \subsection[Inst-types]{@Inst@ types}
660 %*                                                                      *
661 v%************************************************************************
662
663 An @Inst@ is either a dictionary, an instance of an overloaded
664 literal, or an instance of an overloaded value.  We call the latter a
665 ``method'' even though it may not correspond to a class operation.
666 For example, we might have an instance of the @double@ function at
667 type Int, represented by
668
669         Method 34 doubleId [Int] origin
670
671 In addition to the basic Haskell variants of 'Inst's, they can now also
672 represent implication constraints 'forall tvs. given => wanted'
673 and equality constraints 'co :: ty1 ~ ty2'.
674
675 NB: Equalities occur in two flavours:
676
677   (1) Dict {tci_pred = EqPred ty1 ty2}
678   (2) EqInst {tci_left = ty1, tci_right = ty2, tci_co = coe}
679
680 The former arises from equalities in contexts, whereas the latter is used
681 whenever the type checker introduces an equality (e.g., during deferring
682 unification).
683
684 I am not convinced that this duplication is necessary or useful! -=chak
685
686 \begin{code}
687 data Inst
688   = Dict {
689         tci_name :: Name,
690         tci_pred :: TcPredType,   -- Class or implicit parameter only
691         tci_loc  :: InstLoc 
692     }
693
694   | ImplicInst {        -- An implication constraint
695                         -- forall tvs. given => wanted
696         tci_name   :: Name,
697         tci_tyvars :: [TcTyVar],    -- Quantified type variables
698         tci_given  :: [Inst],       -- Only Dicts and EqInsts
699                                     --   (no Methods, LitInsts, ImplicInsts)
700         tci_wanted :: [Inst],       -- Only Dicts, EqInst, and ImplicInsts
701                                     --   (no Methods or LitInsts)
702
703         tci_loc    :: InstLoc
704     }
705         -- NB: the tci_given are not necessarily rigid
706
707   | Method {
708         tci_id :: TcId,         -- The Id for the Inst
709
710         tci_oid :: TcId,        -- The overloaded function
711                 -- This function will be a global, local, or ClassOpId;
712                 --   inside instance decls (only) it can also be an InstId!
713                 -- The id needn't be completely polymorphic.
714                 -- You'll probably find its name (for documentation purposes)
715                 --        inside the InstOrigin
716
717         tci_tys :: [TcType],    -- The types to which its polymorphic tyvars
718                                 --      should be instantiated.
719                                 -- These types must saturate the Id's foralls.
720
721         tci_theta :: TcThetaType,       
722                         -- The (types of the) dictionaries to which the function
723                         -- must be applied to get the method
724
725         tci_loc :: InstLoc 
726     }
727         -- INVARIANT 1: in (Method m f tys theta tau loc)
728         --      type of m = type of (f tys dicts(from theta))
729
730         -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
731         --   Reason: two methods are considered equal if the 
732         --           base Id matches, and the instantiating types
733         --           match.  The TcThetaType should then match too.
734         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
735
736   | LitInst {
737         tci_name :: Name,
738         tci_lit  :: HsOverLit Name,     -- The literal from the occurrence site
739                         -- INVARIANT: never a rebindable-syntax literal
740                         -- Reason: tcSyntaxName does unification, and we
741                         --         don't want to deal with that during tcSimplify,
742                         --         when resolving LitInsts
743
744         tci_ty :: TcType,       -- The type at which the literal is used
745         tci_loc :: InstLoc
746     }
747
748   | EqInst {                      -- delayed unification of the form 
749                                   --    co :: ty1 ~ ty2
750         tci_left  :: TcType,      -- ty1    -- both types are...
751         tci_right :: TcType,      -- ty2    -- ...free of boxes
752         tci_co    :: EqInstCo,            -- co
753         tci_loc   :: InstLoc,
754
755         tci_name  :: Name       -- Debugging help only: this makes it easier to
756                                 -- follow where a constraint is used in a morass
757                                 -- of trace messages!  Unlike other Insts, it 
758                                 -- has no semantic significance whatsoever.
759     }
760
761 type EqInstCo = Either    -- Distinguish between given and wanted coercions
762                   TcTyVar   --  - a wanted equation, with a hole, to be filled
763                             --    with a witness for the equality; for equation
764                             --    arising from deferring unification, 'ty1' is
765                             --    the actual and 'ty2' the expected type
766                   Coercion  --  - a given equation, with a coercion witnessing
767                             --    the equality; a coercion that originates
768                             --    from a signature or a GADT is a CoVar, but
769                             --    after normalisation of coercions, they can
770                             --    be arbitrary Coercions involving constructors 
771                             --    and pseudo-constructors like sym and trans.
772 \end{code}
773
774 @Insts@ are ordered by their class/type info, rather than by their
775 unique.  This allows the context-reduction mechanism to use standard finite
776 maps to do their stuff.  It's horrible that this code is here, rather
777 than with the Avails handling stuff in TcSimplify
778
779 \begin{code}
780 instance Ord Inst where
781    compare = cmpInst
782         -- Used *only* for AvailEnv in TcSimplify
783
784 instance Eq Inst where
785   (==) i1 i2 = case i1 `cmpInst` i2 of
786                EQ -> True
787                _  -> False
788
789 cmpInst :: Inst -> Inst -> Ordering
790 cmpInst d1@(Dict {})    d2@(Dict {})    = tci_pred d1 `tcCmpPred` tci_pred d2
791 cmpInst (Dict {})       _               = LT
792
793 cmpInst (Method {})     (Dict {})       = GT
794 cmpInst m1@(Method {})  m2@(Method {})  = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
795                                           (tci_tys m1 `tcCmpTypes` tci_tys m2)
796 cmpInst (Method {})     _               = LT
797
798 cmpInst (LitInst {})    (Dict {})       = GT
799 cmpInst (LitInst {})    (Method {})     = GT
800 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
801                                           (tci_ty l1 `tcCmpType` tci_ty l2)
802 cmpInst (LitInst {})    _               = LT
803
804         -- Implication constraints are compared by *name*
805         -- not by type; that is, we make no attempt to do CSE on them
806 cmpInst (ImplicInst {})    (Dict {})          = GT
807 cmpInst (ImplicInst {})    (Method {})        = GT
808 cmpInst (ImplicInst {})    (LitInst {})       = GT
809 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
810 cmpInst (ImplicInst {})    _                  = LT
811
812         -- same for Equality constraints
813 cmpInst (EqInst {})    (Dict {})       = GT
814 cmpInst (EqInst {})    (Method {})     = GT
815 cmpInst (EqInst {})    (LitInst {})    = GT
816 cmpInst (EqInst {})    (ImplicInst {}) = GT
817 cmpInst i1@(EqInst {}) i2@(EqInst {})  = (tci_left  i1 `tcCmpType` tci_left  i2) `thenCmp`
818                                          (tci_right i1 `tcCmpType` tci_right i2)
819 \end{code}
820
821
822 %************************************************************************
823 %*                                                                      *
824 \subsection[Inst-collections]{LIE: a collection of Insts}
825 %*                                                                      *
826 %************************************************************************
827
828 \begin{code}
829 -- FIXME: Rename this. It clashes with (Located (IE ...))
830 type LIE = Bag Inst
831
832 isEmptyLIE :: LIE -> Bool
833 isEmptyLIE = isEmptyBag
834
835 emptyLIE :: LIE
836 emptyLIE = emptyBag
837
838 unitLIE :: Inst -> LIE
839 unitLIE inst = unitBag inst
840
841 mkLIE :: [Inst] -> LIE
842 mkLIE insts = listToBag insts
843
844 plusLIE :: LIE -> LIE -> LIE
845 plusLIE lie1 lie2 = lie1 `unionBags` lie2
846
847 plusLIEs :: [LIE] -> LIE
848 plusLIEs lies = unionManyBags lies
849
850 lieToList :: LIE -> [Inst]
851 lieToList = bagToList
852
853 listToLIE :: [Inst] -> LIE
854 listToLIE = listToBag
855
856 consLIE :: Inst -> LIE -> LIE
857 consLIE inst lie  = lie `snocBag` inst
858 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
859 -- to ensure that we tend to report the *leftmost* type-constraint error
860 -- E.g.         f :: [a]
861 --              f = [1,2,3]
862 -- we'd like to complain about the '1', not the '3'.
863 --
864 -- "Half-hearted" because the rest of the type checker makes no great
865 -- claims for retaining order in the constraint set.  Still, this 
866 -- seems to improve matters slightly.  Exampes: mdofail001, tcfail015
867 \end{code}
868
869
870 %************************************************************************
871 %*                                                                      *
872 \subsection[Inst-origin]{The @InstOrigin@ type}
873 %*                                                                      *
874 %************************************************************************
875
876 The @InstOrigin@ type gives information about where a dictionary came from.
877 This is important for decent error message reporting because dictionaries
878 don't appear in the original source code.  Doubtless this type will evolve...
879
880 It appears in TcMonad because there are a couple of error-message-generation
881 functions that deal with it.
882
883 \begin{code}
884 -------------------------------------------
885 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
886
887 instLoc :: Inst -> InstLoc
888 instLoc inst = tci_loc inst
889
890 setInstLoc :: Inst -> InstLoc -> Inst
891 setInstLoc inst new_loc = inst { tci_loc = new_loc }
892
893 instSpan :: Inst -> SrcSpan
894 instSpan wanted = instLocSpan (instLoc wanted)
895
896 instLocSpan :: InstLoc -> SrcSpan
897 instLocSpan (InstLoc _ s _) = s
898
899 instLocOrigin :: InstLoc -> InstOrigin
900 instLocOrigin (InstLoc o _ _) = o
901
902 pprInstArising :: Inst -> SDoc
903 pprInstArising loc = ptext (sLit "arising from") <+> pprInstLoc (tci_loc loc)
904
905 pprInstLoc :: InstLoc -> SDoc
906 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
907
908 -------------------------------------------
909 data InstOrigin
910   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
911                                 -- Places that bind type variables and introduce
912                                 -- available constraints
913
914   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
915
916         -------------------------------------------------------
917         -- The rest are all occurrences: Insts that are 'wanted'
918         -------------------------------------------------------
919   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
920   | SpecPragOrigin Name         -- Specialisation pragma for identifier
921
922   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
923
924   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
925   | NegateOrigin                        -- Occurrence of syntactic negation
926
927   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
928   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
929   | TupleOrigin                        -- (..,..)
930
931   | InstSigOrigin       -- A dict occurrence arising from instantiating
932                         -- a polymorphic type during a subsumption check
933
934   | ExprSigOrigin       -- e :: ty
935   | RecordUpdOrigin
936   | ViewPatOrigin
937
938   | InstScOrigin        -- Typechecking superclasses of an instance declaration
939
940   | NoScOrigin          -- A very special hack; see TcSimplify,
941                         --   Note [Recursive instances and superclases]
942                            
943
944   | DerivOrigin         -- Typechecking deriving
945   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
946   | DefaultOrigin       -- Typechecking a default decl
947   | DoOrigin            -- Arising from a do expression
948   | ProcOrigin          -- Arising from a proc expression
949   | ImplicOrigin SDoc   -- An implication constraint
950   | EqOrigin            -- A type equality
951   | AnnOrigin           -- An annotation
952
953 instance Outputable InstOrigin where
954     ppr (OccurrenceOf name)   = hsep [ptext (sLit "a use of"), quotes (ppr name)]
955     ppr (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
956     ppr (IPOccOrigin name)    = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
957     ppr (IPBindOrigin name)   = hsep [ptext (sLit "a binding for implicit parameter"), quotes (ppr name)]
958     ppr RecordUpdOrigin       = ptext (sLit "a record update")
959     ppr ExprSigOrigin         = ptext (sLit "an expression type signature")
960     ppr ViewPatOrigin         = ptext (sLit "a view pattern")
961     ppr (LiteralOrigin lit)   = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
962     ppr (ArithSeqOrigin seq)  = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
963     ppr (PArrSeqOrigin seq)   = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
964     ppr TupleOrigin           = ptext (sLit "a tuple")
965     ppr NegateOrigin          = ptext (sLit "a use of syntactic negation")
966     ppr InstScOrigin          = ptext (sLit "the superclasses of an instance declaration")
967     ppr NoScOrigin            = ptext (sLit "an instance declaration")
968     ppr DerivOrigin           = ptext (sLit "the 'deriving' clause of a data type declaration")
969     ppr StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
970     ppr DefaultOrigin         = ptext (sLit "a 'default' declaration")
971     ppr DoOrigin              = ptext (sLit "a do statement")
972     ppr ProcOrigin            = ptext (sLit "a proc expression")
973     ppr (ImplicOrigin doc)    = doc
974     ppr (SigOrigin info)      = pprSkolInfo info
975     ppr EqOrigin              = ptext (sLit "a type equality")
976     ppr InstSigOrigin         = panic "ppr InstSigOrigin"
977     ppr AnnOrigin             = ptext (sLit "an annotation")
978 \end{code}