17f8d63012de7038d2b8e09cc4c12e8988a70e44
[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         TcTypeEnv, TcTyThing(..), pprTcTyThingCategory, 
22
23         -- Template Haskell
24         ThStage(..), topStage, topAnnStage, topSpliceStage,
25         ThLevel, impLevel, outerLevel, thLevel,
26
27         -- Arrows
28         ArrowCtxt(NoArrowCtxt), newArrowScope, escapeArrowScope,
29
30         -- Constraints
31         Untouchables,
32         WantedConstraints, emptyWanteds, andWanteds, extendWanteds,
33         WantedConstraint(..), WantedEvVar(..), wantedEvVarLoc, 
34         wantedEvVarToVar, wantedEvVarPred, splitWanteds,
35
36         evVarsToWanteds,
37         Implication(..), 
38         CtLoc(..), ctLocSpan, ctLocOrigin, setCtLocOrigin,
39         CtOrigin(..), EqOrigin(..), 
40         WantedLoc, GivenLoc,
41
42         SkolemInfo(..),
43
44         -- Pretty printing
45         pprEvVarTheta, pprWantedsWithLocs, pprWantedWithLoc, 
46         pprEvVars, pprEvVarWithType,
47         pprArising, pprArisingAt,
48
49         -- Misc other types
50         TcId, TcIdSet, TcTyVarBind(..), TcTyVarBinds
51         
52   ) where
53
54 #include "HsVersions.h"
55
56 import HsSyn
57 import HscTypes
58 import Type
59 import TcType
60 import Annotations
61 import InstEnv
62 import FamInstEnv
63 import IOEnv
64 import RdrName
65 import Name
66 import NameEnv
67 import NameSet
68 import Var
69 import VarEnv
70 import Module
71 import UniqFM
72 import SrcLoc
73 import VarSet
74 import ErrUtils
75 import UniqSupply
76 import BasicTypes
77 import Bag
78 import Outputable
79 import ListSetOps
80 import FastString
81 import StaticFlags( opt_ErrorSpans )
82
83 import Data.Set (Set)
84 \end{code}
85
86
87 %************************************************************************
88 %*                                                                      *
89                Standard monad definition for TcRn
90     All the combinators for the monad can be found in TcRnMonad
91 %*                                                                      *
92 %************************************************************************
93
94 The monad itself has to be defined here, because it is mentioned by ErrCtxt
95
96 \begin{code}
97 type TcRef a     = IORef a
98 type TcId        = Id                   -- Type may be a TcType  DV: WHAT??????????
99 type TcIdSet     = IdSet
100
101
102 type TcRnIf a b c = IOEnv (Env a b) c
103 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
104
105 type IfG a  = IfM () a                          -- Top level
106 type IfL a  = IfM IfLclEnv a                    -- Nested
107 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
108 type RnM  a = TcRn a            -- Historical
109 type TcM  a = TcRn a            -- Historical
110 \end{code}
111
112 Representation of type bindings to uninstantiated meta variables used during
113 constraint solving.
114
115 \begin{code}
116 data TcTyVarBind = TcTyVarBind TcTyVar TcType
117
118 type TcTyVarBinds = Bag TcTyVarBind
119
120 instance Outputable TcTyVarBind where
121   ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
122 \end{code}
123
124
125 %************************************************************************
126 %*                                                                      *
127                 The main environment types
128 %*                                                                      *
129 %************************************************************************
130
131 \begin{code}
132 data Env gbl lcl        -- Changes as we move into an expression
133   = Env {
134         env_top  :: HscEnv,     -- Top-level stuff that never changes
135                                 -- Includes all info about imported things
136
137         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
138                                 -- Unique supply for local varibles
139
140         env_gbl  :: gbl,        -- Info about things defined at the top level
141                                 -- of the module being compiled
142
143         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
144     }
145
146 -- TcGblEnv describes the top-level of the module at the 
147 -- point at which the typechecker is finished work.
148 -- It is this structure that is handed on to the desugarer
149
150 data TcGblEnv
151   = TcGblEnv {
152         tcg_mod     :: Module,         -- ^ Module being compiled
153         tcg_src     :: HscSource,
154           -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
155
156         tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
157         tcg_default :: Maybe [Type],
158           -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
159
160         tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
161         tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
162
163         tcg_type_env :: TypeEnv,
164           -- ^ Global type env for the module we are compiling now.  All
165           -- TyCons and Classes (for this module) end up in here right away,
166           -- along with their derived constructors, selectors.
167           --
168           -- (Ids defined in this module start in the local envt, though they
169           --  move to the global envt during zonking)
170
171         tcg_type_env_var :: TcRef TypeEnv,
172                 -- Used only to initialise the interface-file
173                 -- typechecker in initIfaceTcRn, so that it can see stuff
174                 -- bound in this module when dealing with hi-boot recursions
175                 -- Updated at intervals (e.g. after dealing with types and classes)
176         
177         tcg_inst_env     :: InstEnv,
178           -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
179           -- tcg_insts
180         tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
181
182                 -- Now a bunch of things about this module that are simply 
183                 -- accumulated, but never consulted until the end.  
184                 -- Nevertheless, it's convenient to accumulate them along 
185                 -- with the rest of the info from this module.
186         tcg_exports :: [AvailInfo],     -- ^ What is exported
187         tcg_imports :: ImportAvails,
188           -- ^ Information about what was imported from where, including
189           -- things bound in this module.
190
191         tcg_dus :: DefUses,
192           -- ^ What is defined in this module and what is used.
193           -- The latter is used to generate
194           --
195           --  (a) version tracking; no need to recompile if these things have
196           --      not changed version stamp
197           --
198           --  (b) unused-import info
199
200         tcg_keep :: TcRef NameSet,
201           -- ^ Locally-defined top-level names to keep alive.
202           --
203           -- "Keep alive" means give them an Exported flag, so that the
204           -- simplifier does not discard them as dead code, and so that they
205           -- are exposed in the interface file (but not to export to the
206           -- user).
207           --
208           -- Some things, like dict-fun Ids and default-method Ids are "born"
209           -- with the Exported flag on, for exactly the above reason, but some
210           -- we only discover as we go.  Specifically:
211           --
212           --   * The to/from functions for generic data types
213           --
214           --   * Top-level variables appearing free in the RHS of an orphan
215           --     rule
216           --
217           --   * Top-level variables appearing free in a TH bracket
218
219         tcg_inst_uses :: TcRef NameSet,
220           -- ^ Home-package Dfuns actually used.
221           --
222           -- Used to generate version dependencies This records usages, rather
223           -- like tcg_dus, but it has to be a mutable variable so it can be
224           -- augmented when we look up an instance.  These uses of dfuns are
225           -- rather like the free variables of the program, but are implicit
226           -- instead of explicit.
227
228         tcg_th_used :: TcRef Bool,
229           -- ^ @True@ <=> Template Haskell syntax used.
230           --
231           -- We need this so that we can generate a dependency on the Template
232           -- Haskell package, becuase the desugarer is going to emit loads of
233           -- references to TH symbols.  It's rather like tcg_inst_uses; the
234           -- reference is implicit rather than explicit, so we have to zap a
235           -- mutable variable.
236
237         tcg_dfun_n  :: TcRef OccSet,
238           -- ^ Allows us to choose unique DFun names.
239
240         -- The next fields accumulate the payload of the module
241         -- The binds, rules and foreign-decl fiels are collected
242         -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
243
244         tcg_rn_exports :: Maybe [Located (IE Name)],
245         tcg_rn_imports :: [LImportDecl Name],
246                 -- Keep the renamed imports regardless.  They are not 
247                 -- voluminous and are needed if you want to report unused imports
248
249         tcg_used_rdrnames :: TcRef (Set RdrName),
250                 -- The set of used *imported* (not locally-defined) RdrNames
251                 -- Used only to report unused import declarations
252
253         tcg_rn_decls :: Maybe (HsGroup Name),
254           -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
255           -- decls.
256
257         tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
258         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
259         tcg_sigs      :: NameSet,           -- ...Top-level names that *lack* a signature
260         tcg_imp_specs :: [LTcSpecPrag],     -- ...SPECIALISE prags for imported Ids
261         tcg_warns     :: Warnings,          -- ...Warnings and deprecations
262         tcg_anns      :: [Annotation],      -- ...Annotations
263         tcg_insts     :: [Instance],        -- ...Instances
264         tcg_fam_insts :: [FamInst],         -- ...Family instances
265         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
266         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
267
268         tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
269         tcg_hpc       :: AnyHpcUsage,        -- ^ @True@ if any part of the
270                                              --  prog uses hpc instrumentation.
271
272         tcg_main      :: Maybe Name          -- ^ The Name of the main
273                                              -- function, if this module is
274                                              -- the main module.
275     }
276
277 data RecFieldEnv 
278   = RecFields (NameEnv [Name])  -- Maps a constructor name *in this module*
279                                 -- to the fields for that constructor
280               NameSet           -- Set of all fields declared *in this module*;
281                                 -- used to suppress name-shadowing complaints
282                                 -- when using record wild cards
283                                 -- E.g.  let fld = e in C {..}
284         -- This is used when dealing with ".." notation in record 
285         -- construction and pattern matching.
286         -- The FieldEnv deals *only* with constructors defined in *this*
287         -- module.  For imported modules, we get the same info from the
288         -- TypeEnv
289 \end{code}
290
291 %************************************************************************
292 %*                                                                      *
293                 The interface environments
294               Used when dealing with IfaceDecls
295 %*                                                                      *
296 %************************************************************************
297
298 \begin{code}
299 data IfGblEnv 
300   = IfGblEnv {
301         -- The type environment for the module being compiled,
302         -- in case the interface refers back to it via a reference that
303         -- was originally a hi-boot file.
304         -- We need the module name so we can test when it's appropriate
305         -- to look in this env.
306         if_rec_types :: Maybe (Module, IfG TypeEnv)
307                 -- Allows a read effect, so it can be in a mutable
308                 -- variable; c.f. handling the external package type env
309                 -- Nothing => interactive stuff, no loops possible
310     }
311
312 data IfLclEnv
313   = IfLclEnv {
314         -- The module for the current IfaceDecl
315         -- So if we see   f = \x -> x
316         -- it means M.f = \x -> x, where M is the if_mod
317         if_mod :: Module,
318
319         -- The field is used only for error reporting
320         -- if (say) there's a Lint error in it
321         if_loc :: SDoc,
322                 -- Where the interface came from:
323                 --      .hi file, or GHCi state, or ext core
324                 -- plus which bit is currently being examined
325
326         if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
327         if_id_env  :: UniqFM Id         -- Nested id binding
328     }
329 \end{code}
330
331
332 %************************************************************************
333 %*                                                                      *
334                 The local typechecker environment
335 %*                                                                      *
336 %************************************************************************
337
338 The Global-Env/Local-Env story
339 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
340 During type checking, we keep in the tcg_type_env
341         * All types and classes
342         * All Ids derived from types and classes (constructors, selectors)
343
344 At the end of type checking, we zonk the local bindings,
345 and as we do so we add to the tcg_type_env
346         * Locally defined top-level Ids
347
348 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
349         a) fed back (via the knot) to typechecking the 
350            unfoldings of interface signatures
351         b) used in the ModDetails of this module
352
353 \begin{code}
354 data TcLclEnv           -- Changes as we move inside an expression
355                         -- Discarded after typecheck/rename; not passed on to desugarer
356   = TcLclEnv {
357         tcl_loc  :: SrcSpan,            -- Source span
358         tcl_ctxt :: [ErrCtxt],          -- Error context, innermost on top
359         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
360
361         tcl_th_ctxt    :: ThStage,            -- Template Haskell context
362         tcl_arrow_ctxt :: ArrowCtxt,          -- Arrow-notation context
363
364         tcl_rdr :: LocalRdrEnv,         -- Local name envt
365                 -- Maintained during renaming, of course, but also during
366                 -- type checking, solely so that when renaming a Template-Haskell
367                 -- splice we have the right environment for the renamer.
368                 -- 
369                 --   Does *not* include global name envt; may shadow it
370                 --   Includes both ordinary variables and type variables;
371                 --   they are kept distinct because tyvar have a different
372                 --   occurrence contructor (Name.TvOcc)
373                 -- We still need the unsullied global name env so that
374                 --   we can look up record field names
375
376         tcl_env  :: TcTypeEnv,    -- The local type environment: Ids and
377                                   -- TyVars defined in this module
378                                         
379         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
380                         -- Namely, the in-scope TyVars bound in tcl_env, 
381                         -- plus the tyvars mentioned in the types of Ids bound
382                         -- in tcl_lenv. 
383                         -- Why mutable? see notes with tcGetGlobalTyVars
384
385         tcl_lie   :: TcRef WantedConstraints,    -- Place to accumulate type constraints
386         tcl_untch :: Untouchables                -- Untouchables
387     }
388
389 type TcTypeEnv = NameEnv TcTyThing
390
391
392 {- Note [Given Insts]
393    ~~~~~~~~~~~~~~~~~~
394 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
395 and existential contexts. Consider
396         data T a where { T1 :: b -> b -> T [b] }
397         f :: Eq a => T a -> Bool
398         f (T1 x y) = [x]==[y]
399
400 The constructor T1 binds an existential variable 'b', and we need Eq [b].
401 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
402 pass it inwards.
403
404 -}
405
406 ---------------------------
407 -- Template Haskell stages and levels 
408 ---------------------------
409
410 data ThStage    -- See Note [Template Haskell state diagram] in TcSplice
411   = Splice      -- Top-level splicing
412                 -- This code will be run *at compile time*;
413                 --   the result replaces the splice
414                 -- Binding level = 0
415  
416   | Comp        -- Ordinary Haskell code
417                 -- Binding level = 1
418
419   | Brack                       -- Inside brackets 
420       ThStage                   --   Binding level = level(stage) + 1
421       (TcRef [PendingSplice])   --   Accumulate pending splices here
422       (TcRef WantedConstraints) --     and type constraints here
423
424 topStage, topAnnStage, topSpliceStage :: ThStage
425 topStage       = Comp
426 topAnnStage    = Splice
427 topSpliceStage = Splice
428
429 instance Outputable ThStage where
430    ppr Splice        = text "Splice"
431    ppr Comp          = text "Comp"
432    ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
433
434 type ThLevel = Int      
435         -- See Note [Template Haskell levels] in TcSplice
436         -- Incremented when going inside a bracket,
437         -- decremented when going inside a splice
438         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
439         --     original "Template meta-programming for Haskell" paper
440
441 impLevel, outerLevel :: ThLevel
442 impLevel = 0    -- Imported things; they can be used inside a top level splice
443 outerLevel = 1  -- Things defined outside brackets
444 -- NB: Things at level 0 are not *necessarily* imported.
445 --      eg  $( \b -> ... )   here b is bound at level 0
446 --
447 -- For example: 
448 --      f = ...
449 --      g1 = $(map ...)         is OK
450 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
451
452 thLevel :: ThStage -> ThLevel
453 thLevel Splice        = 0
454 thLevel Comp          = 1
455 thLevel (Brack s _ _) = thLevel s + 1
456
457 ---------------------------
458 -- Arrow-notation context
459 ---------------------------
460
461 {-
462 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
463 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
464 For example
465
466         proc x -> (e1 -< e2)
467
468 Here, x is not in scope in e1, but it is in scope in e2.  This can get
469 a bit complicated:
470
471         let x = 3 in
472         proc y -> (proc z -> e1) -< e2
473
474 Here, x and z are in scope in e1, but y is not.  We implement this by
475 recording the environment when passing a proc (using newArrowScope),
476 and returning to that (using escapeArrowScope) on the left of -< and the
477 head of (|..|).
478 -}
479
480 data ArrowCtxt
481   = NoArrowCtxt
482   | ArrowCtxt (Env TcGblEnv TcLclEnv)
483
484 -- Record the current environment (outside a proc)
485 newArrowScope :: TcM a -> TcM a
486 newArrowScope
487   = updEnv $ \env ->
488         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
489
490 -- Return to the stored environment (from the enclosing proc)
491 escapeArrowScope :: TcM a -> TcM a
492 escapeArrowScope
493   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
494         NoArrowCtxt -> env
495         ArrowCtxt env' -> env'
496
497 ---------------------------
498 -- TcTyThing
499 ---------------------------
500
501 data TcTyThing
502   = AGlobal TyThing             -- Used only in the return type of a lookup
503
504   | ATcId   {           -- Ids defined in this module; may not be fully zonked
505         tct_id    :: TcId,              
506         tct_level :: ThLevel }
507
508   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
509                                 -- is currently refined. We only need the Name
510                                 -- for error-message purposes; it is the corresponding
511                                 -- Name in the domain of the envt
512
513   | AThing  TcKind              -- Used temporarily, during kind checking, for the
514                                 --      tycons and clases in this recursive group
515
516 instance Outputable TcTyThing where     -- Debugging only
517    ppr (AGlobal g)      = pprTyThing g
518    ppr elt@(ATcId {})   = text "Identifier" <> 
519                           brackets (ppr (tct_id elt) <> dcolon 
520                                  <> ppr (varType (tct_id elt)) <> comma
521                                  <+> ppr (tct_level elt))
522    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
523    ppr (AThing k)       = text "AThing" <+> ppr k
524
525 pprTcTyThingCategory :: TcTyThing -> SDoc
526 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
527 pprTcTyThingCategory (ATyVar {})     = ptext (sLit "Type variable")
528 pprTcTyThingCategory (ATcId {})      = ptext (sLit "Local identifier")
529 pprTcTyThingCategory (AThing {})     = ptext (sLit "Kinded thing")
530 \end{code}
531
532 \begin{code}
533 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
534         -- Monadic so that we have a chance
535         -- to deal with bound type variables just before error
536         -- message construction
537
538         -- Bool:  True <=> this is a landmark context; do not
539         --                 discard it when trimming for display
540 \end{code}
541
542
543 %************************************************************************
544 %*                                                                      *
545         Operations over ImportAvails
546 %*                                                                      *
547 %************************************************************************
548
549 \begin{code}
550 -- | 'ImportAvails' summarises what was imported from where, irrespective of
551 -- whether the imported things are actually used or not.  It is used:
552 --
553 --  * when processing the export list,
554 --
555 --  * when constructing usage info for the interface file,
556 --
557 --  * to identify the list of directly imported modules for initialisation
558 --    purposes and for optimised overlap checking of family instances,
559 --
560 --  * when figuring out what things are really unused
561 --
562 data ImportAvails 
563    = ImportAvails {
564         imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
565           -- ^ Domain is all directly-imported modules
566           -- The 'ModuleName' is what the module was imported as, e.g. in
567           -- @
568           --     import Foo as Bar
569           -- @
570           -- it is @Bar@.
571           --
572           -- The 'Bool' means:
573           --
574           --  - @True@ => import was @import Foo ()@
575           --
576           --  - @False@ => import was some other form
577           --
578           -- Used
579           --
580           --   (a) to help construct the usage information in the interface
581           --       file; if we import somethign we need to recompile if the
582           --       export version changes
583           --
584           --   (b) to specify what child modules to initialise
585           --
586           -- We need a full ModuleEnv rather than a ModuleNameEnv here,
587           -- because we might be importing modules of the same name from
588           -- different packages. (currently not the case, but might be in the
589           -- future).
590
591         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
592           -- ^ Home-package modules needed by the module being compiled
593           --
594           -- It doesn't matter whether any of these dependencies
595           -- are actually /used/ when compiling the module; they
596           -- are listed if they are below it at all.  For
597           -- example, suppose M imports A which imports X.  Then
598           -- compiling M might not need to consult X.hi, but X
599           -- is still listed in M's dependencies.
600
601         imp_dep_pkgs :: [PackageId],
602           -- ^ Packages needed by the module being compiled, whether directly,
603           -- or via other modules in this package, or via modules imported
604           -- from other packages.
605
606         imp_orphs :: [Module],
607           -- ^ Orphan modules below us in the import tree (and maybe including
608           -- us for imported modules)
609
610         imp_finsts :: [Module]
611           -- ^ Family instance modules below us in the import tree (and maybe
612           -- including us for imported modules)
613       }
614
615 mkModDeps :: [(ModuleName, IsBootInterface)]
616           -> ModuleNameEnv (ModuleName, IsBootInterface)
617 mkModDeps deps = foldl add emptyUFM deps
618                where
619                  add env elt@(m,_) = addToUFM env m elt
620
621 emptyImportAvails :: ImportAvails
622 emptyImportAvails = ImportAvails { imp_mods     = emptyModuleEnv,
623                                    imp_dep_mods = emptyUFM,
624                                    imp_dep_pkgs = [],
625                                    imp_orphs    = [],
626                                    imp_finsts   = [] }
627
628 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
629 plusImportAvails
630   (ImportAvails { imp_mods = mods1,
631                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
632                   imp_orphs = orphs1, imp_finsts = finsts1 })
633   (ImportAvails { imp_mods = mods2,
634                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
635                   imp_orphs = orphs2, imp_finsts = finsts2 })
636   = ImportAvails { imp_mods     = plusModuleEnv_C (++) mods1 mods2,     
637                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
638                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
639                    imp_orphs    = orphs1 `unionLists` orphs2,
640                    imp_finsts   = finsts1 `unionLists` finsts2 }
641   where
642     plus_mod_dep (m1, boot1) (m2, boot2) 
643         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
644                 -- Check mod-names match
645           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
646 \end{code}
647
648 %************************************************************************
649 %*                                                                      *
650 \subsection{Where from}
651 %*                                                                      *
652 %************************************************************************
653
654 The @WhereFrom@ type controls where the renamer looks for an interface file
655
656 \begin{code}
657 data WhereFrom 
658   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
659   | ImportBySystem                      -- Non user import.
660
661 instance Outputable WhereFrom where
662   ppr (ImportByUser is_boot) | is_boot     = ptext (sLit "{- SOURCE -}")
663                              | otherwise   = empty
664   ppr ImportBySystem                       = ptext (sLit "{- SYSTEM -}")
665 \end{code}
666
667
668 %************************************************************************
669 %*                                                                      *
670                 Wanted constraints
671
672      These are forced to be in TcRnTypes because
673            TcLclEnv mentions WantedConstraints
674            WantedConstraint mentions CtLoc
675            CtLoc mentions ErrCtxt
676            ErrCtxt mentions TcM
677 %*                                                                      *
678 v%************************************************************************
679
680 \begin{code}
681 type Untouchables = TcTyVarSet  -- All MetaTyVars
682
683 type WantedConstraints = Bag WantedConstraint
684
685 data WantedConstraint
686   = WcEvVar  WantedEvVar
687   | WcImplic Implication
688   -- ToDo: add literals, methods
689
690 -- EvVar defined in module Var.lhs: 
691 -- Evidence variables include all *quantifiable* constraints
692 --   dictionaries
693 --   implicit parameters
694 --   coercion variables
695
696 data WantedEvVar   -- The sort of constraint over which one can lambda-abstract
697    = WantedEvVar 
698          EvVar       -- The variable itself; make a binding for it please
699          WantedLoc   -- How the constraint arose in the first place
700                      -- (used for error messages only)
701
702 type WantedLoc = CtLoc CtOrigin
703 type GivenLoc  = CtLoc SkolemInfo
704
705 data Implication
706   = Implic {  
707       ic_untch :: Untouchables, -- Untouchables: unification variables
708                                   -- free in the environment
709       ic_env   :: TcTypeEnv,    -- The type environment
710                                   -- Used only when generating error messages
711           -- Generally, ic_untch is a superset of tvsof(ic_env)
712           -- However, we don't zonk ic_env when zonking the Implication
713           -- Instead we do that when generating a skolem-escape error message
714
715       ic_skols  :: TcTyVarSet,   -- Introduced skolems 
716                                  -- See Note [Skolems in an implication]
717
718       ic_scoped :: [TcTyVar],    -- List of scoped variables to be unified 
719                                  -- bijectively to a subset of ic_tyvars
720                                  -- Note [Scoped pattern variable]
721
722       ic_given  :: [EvVar],      -- Given evidence variables
723                                  --   (order does not matter)
724
725       ic_wanted :: WantedConstraints,    -- Wanted constraints
726
727       ic_binds  :: EvBindsVar,   -- Points to the place to fill in the
728                                  -- abstraction and bindings
729
730       ic_loc   :: GivenLoc }
731
732 evVarsToWanteds :: WantedLoc -> [EvVar] -> WantedConstraints
733 evVarsToWanteds loc evs = listToBag [WcEvVar (WantedEvVar ev loc) | ev <- evs]
734
735 wantedEvVarLoc :: WantedEvVar -> WantedLoc 
736 wantedEvVarLoc (WantedEvVar _ loc) = loc 
737
738 wantedEvVarToVar :: WantedEvVar -> EvVar 
739 wantedEvVarToVar (WantedEvVar ev _) = ev 
740
741 wantedEvVarPred :: WantedEvVar -> PredType 
742 wantedEvVarPred (WantedEvVar ev _)  = evVarPred ev 
743
744 splitWanteds :: WantedConstraints -> (Bag WantedEvVar, Bag Implication)
745 splitWanteds wanted = partitionBagWith pick wanted
746   where
747     pick (WcEvVar v)  = Left v
748     pick (WcImplic i) = Right i
749 \end{code}
750
751 Note [Skolems in an implication]
752 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
753 The skolems in an implication are not there to perform a skolem escape
754 check.  That happens because all the environment variables are in the
755 untouchables, and therefore cannot be unified with anything at all,
756 let alone the skolems.
757
758 Instead, ic_skols is used only when considering floating a constraint
759 outside the implication in TcSimplify.floatEqualities or 
760 TcSimplify.approximateImplications
761
762 Note [Scoped pattern variables]
763 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
764    data T where K :: forall a,b. a -> b -> T
765
766    ...(case x of K (p::c) (q::d) -> ...)...
767
768 We create fresh MetaTvs for c,d, and later check that they are
769 bound bijectively to the skolems we created for a,b.  So the
770 implication constraint looks like
771             ic_skols  = {a',b'}  -- Skolem tvs created from a,b
772             ic_scoped = {c',d'}  -- Meta tvs created from c,d
773
774 \begin{code}
775 emptyWanteds :: WantedConstraints
776 emptyWanteds = emptyBag
777
778 andWanteds :: WantedConstraints -> WantedConstraints -> WantedConstraints
779 andWanteds = unionBags
780
781 extendWanteds :: WantedConstraints -> WantedConstraint -> WantedConstraints
782 extendWanteds = snocBag
783 \end{code}
784  
785 \begin{code}
786 pprEvVars :: [EvVar] -> SDoc    -- Print with their types
787 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
788
789 pprEvVarTheta :: [EvVar] -> SDoc
790 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
791                               
792 pprEvVarWithType :: EvVar -> SDoc
793 pprEvVarWithType v = ppr v <+> dcolon <+> pprPred (evVarPred v)
794
795 pprWantedsWithLocs :: Bag WantedConstraint -> SDoc
796 pprWantedsWithLocs = foldrBag (($$) . pprWantedWithLoc) empty 
797
798 pprWantedWithLoc :: WantedConstraint -> SDoc
799 pprWantedWithLoc (WcImplic i) = ppr i
800 pprWantedWithLoc (WcEvVar v)  = pprWantedEvVarWithLoc v
801
802 instance Outputable WantedConstraint where
803   ppr (WcEvVar v)  = ppr v
804   ppr (WcImplic i) = ppr i
805
806 -- Adding -ferror-spans makes the output more voluminous
807 instance Outputable WantedEvVar where
808   ppr wev | opt_ErrorSpans = pprWantedEvVarWithLoc wev
809           | otherwise      = pprWantedEvVar wev
810
811 pprWantedEvVarWithLoc, pprWantedEvVar :: WantedEvVar -> SDoc
812 pprWantedEvVarWithLoc (WantedEvVar v loc) = hang (pprEvVarWithType v) 
813                                                2 (pprArisingAt loc) 
814 pprWantedEvVar        (WantedEvVar v _)   = pprEvVarWithType v
815
816 instance Outputable Implication where
817   ppr (Implic { ic_untch = untch, ic_skols = skols, ic_given = given
818               , ic_wanted = wanted, ic_binds = binds, ic_loc = loc })
819    = ptext (sLit "Implic") <+> braces 
820      (sep [ ptext (sLit "Untouchables = ") <+> ppr untch
821           , ptext (sLit "Skolems = ") <+> ppr skols
822           , ptext (sLit "Given = ") <+> pprEvVars given
823           , ptext (sLit "Wanted = ") <+> ppr wanted
824           , ptext (sLit "Binds = ") <+> ppr binds
825           , pprSkolInfo (ctLocOrigin loc)
826           , ppr (ctLocSpan loc) ])
827 \end{code}
828
829 %************************************************************************
830 %*                                                                      *
831             CtLoc, CtOrigin
832 %*                                                                      *
833 %************************************************************************
834
835 The 'CtLoc' and 'CtOrigin' types gives information about where a
836 *wanted constraint* came from.  This is important for decent error
837 message reporting because dictionaries don't appear in the original
838 source code.  Doubtless this type will evolve...
839
840 \begin{code}
841 -------------------------------------------
842 data CtLoc orig = CtLoc orig SrcSpan [ErrCtxt]
843
844 ctLocSpan :: CtLoc o -> SrcSpan
845 ctLocSpan (CtLoc _ s _) = s
846
847 ctLocOrigin :: CtLoc o -> o
848 ctLocOrigin (CtLoc o _ _) = o
849
850 setCtLocOrigin :: CtLoc o -> o' -> CtLoc o'
851 setCtLocOrigin (CtLoc _ s c) o = CtLoc o s c
852
853 pprArising :: CtOrigin -> SDoc
854 pprArising (TypeEqOrigin {}) = empty
855 pprArising orig              = text "arising from" <+> ppr orig
856
857 pprArisingAt :: CtLoc CtOrigin -> SDoc
858 pprArisingAt (CtLoc o s _) = sep [pprArising o, text "at" <+> ppr s]
859
860 -------------------------------------------
861 -- CtOrigin gives the origin of *wanted* constraints
862 data CtOrigin
863   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
864   | AppOrigin                   -- An application of some kind
865
866   | SpecPragOrigin Name         -- Specialisation pragma for identifier
867
868   | TypeEqOrigin EqOrigin
869
870   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
871
872   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
873   | NegateOrigin                        -- Occurrence of syntactic negation
874
875   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
876   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
877   | SectionOrigin
878   | TupleOrigin                        -- (..,..)
879   | ExprSigOrigin       -- e :: ty
880   | PatSigOrigin        -- p :: ty
881   | PatOrigin           -- Instantiating a polytyped pattern at a constructor
882   | RecordUpdOrigin
883   | ViewPatOrigin
884
885   | ScOrigin            -- Typechecking superclasses of an instance declaration
886   | DerivOrigin         -- Typechecking deriving
887   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
888   | DefaultOrigin       -- Typechecking a default decl
889   | DoOrigin            -- Arising from a do expression
890   | ProcOrigin          -- Arising from a proc expression
891   | AnnOrigin           -- An annotation
892
893 data EqOrigin 
894   = UnifyOrigin 
895        { uo_actual   :: TcType
896        , uo_expected :: TcType }
897
898 instance Outputable CtOrigin where
899   ppr orig = pprO orig
900
901 pprO :: CtOrigin -> SDoc
902 pprO (OccurrenceOf name)   = hsep [ptext (sLit "a use of"), quotes (ppr name)]
903 pprO AppOrigin             = ptext (sLit "an application")
904 pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
905 pprO (IPOccOrigin name)    = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
906 pprO RecordUpdOrigin       = ptext (sLit "a record update")
907 pprO ExprSigOrigin         = ptext (sLit "an expression type signature")
908 pprO PatSigOrigin          = ptext (sLit "a pattern type signature")
909 pprO PatOrigin             = ptext (sLit "a pattern")
910 pprO ViewPatOrigin         = ptext (sLit "a view pattern")
911 pprO (LiteralOrigin lit)   = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
912 pprO (ArithSeqOrigin seq)  = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
913 pprO (PArrSeqOrigin seq)   = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
914 pprO SectionOrigin         = ptext (sLit "an operator section")
915 pprO TupleOrigin           = ptext (sLit "a tuple")
916 pprO NegateOrigin          = ptext (sLit "a use of syntactic negation")
917 pprO ScOrigin              = ptext (sLit "the superclasses of an instance declaration")
918 pprO DerivOrigin           = ptext (sLit "the 'deriving' clause of a data type declaration")
919 pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
920 pprO DefaultOrigin         = ptext (sLit "a 'default' declaration")
921 pprO DoOrigin              = ptext (sLit "a do statement")
922 pprO ProcOrigin            = ptext (sLit "a proc expression")
923 pprO (TypeEqOrigin eq)     = ptext (sLit "an equality") <+> ppr eq
924 pprO AnnOrigin             = ptext (sLit "an annotation")
925
926 instance Outputable EqOrigin where
927   ppr (UnifyOrigin t1 t2) = ppr t1 <+> char '~' <+> ppr t2
928 \end{code}