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