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