Remove very dead Java backend code.
[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(..), inTouchableRange, isNoUntouchables,
32
33         WantedConstraints(..), insolubleWC, emptyWC, isEmptyWC,
34         andWC, addFlats, addImplics, mkFlatWC,
35
36         EvVarX(..), mkEvVarX, evVarOf, evVarX, evVarOfPred,
37         WantedEvVar, wantedToFlavored,
38         keepWanted,
39
40         Implication(..),
41         CtLoc(..), ctLocSpan, ctLocOrigin, setCtLocOrigin,
42         CtOrigin(..), EqOrigin(..), 
43         WantedLoc, GivenLoc, GivenKind(..), pushErrCtxt,
44
45         SkolemInfo(..),
46
47         CtFlavor(..), pprFlavorArising, isWanted, 
48         isGivenOrSolved, isGiven_maybe,
49         isDerived,
50         FlavoredEvVar,
51
52         -- Pretty printing
53         pprEvVarTheta, pprWantedEvVar, pprWantedsWithLocs,
54         pprEvVars, pprEvVarWithType,
55         pprArising, pprArisingAt,
56
57         -- Misc other types
58         TcId, TcIdSet, TcTyVarBind(..), TcTyVarBinds
59         
60   ) where
61
62 #include "HsVersions.h"
63
64 import HsSyn
65 import HscTypes
66 import Type
67 import Id       ( evVarPred )
68 import Class    ( Class )
69 import DataCon  ( DataCon, dataConUserType )
70 import TcType
71 import Annotations
72 import InstEnv
73 import FamInstEnv
74 import IOEnv
75 import RdrName
76 import Name
77 import NameEnv
78 import NameSet
79 import Var
80 import VarEnv
81 import Module
82 import SrcLoc
83 import VarSet
84 import ErrUtils
85 import UniqFM
86 import UniqSupply
87 import Unique
88 import BasicTypes
89 import Bag
90 import Outputable
91 import ListSetOps
92 import FastString
93
94 import Data.Set (Set)
95 \end{code}
96
97
98 %************************************************************************
99 %*                                                                      *
100                Standard monad definition for TcRn
101     All the combinators for the monad can be found in TcRnMonad
102 %*                                                                      *
103 %************************************************************************
104
105 The monad itself has to be defined here, because it is mentioned by ErrCtxt
106
107 \begin{code}
108 type TcRef a     = IORef a
109 type TcId        = Id                   -- Type may be a TcType  DV: WHAT??????????
110 type TcIdSet     = IdSet
111
112
113 type TcRnIf a b c = IOEnv (Env a b) c
114 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
115
116 type IfG a  = IfM () a                          -- Top level
117 type IfL a  = IfM IfLclEnv a                    -- Nested
118 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
119 type RnM  a = TcRn a            -- Historical
120 type TcM  a = TcRn a            -- Historical
121 \end{code}
122
123 Representation of type bindings to uninstantiated meta variables used during
124 constraint solving.
125
126 \begin{code}
127 data TcTyVarBind = TcTyVarBind TcTyVar TcType
128
129 type TcTyVarBinds = Bag TcTyVarBind
130
131 instance Outputable TcTyVarBind where
132   ppr (TcTyVarBind tv ty) = ppr tv <+> text ":=" <+> ppr ty
133 \end{code}
134
135
136 %************************************************************************
137 %*                                                                      *
138                 The main environment types
139 %*                                                                      *
140 %************************************************************************
141
142 \begin{code}
143 data Env gbl lcl        -- Changes as we move into an expression
144   = Env {
145         env_top  :: HscEnv,     -- Top-level stuff that never changes
146                                 -- Includes all info about imported things
147
148         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
149                                 -- Unique supply for local varibles
150
151         env_gbl  :: gbl,        -- Info about things defined at the top level
152                                 -- of the module being compiled
153
154         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
155     }
156
157 -- TcGblEnv describes the top-level of the module at the 
158 -- point at which the typechecker is finished work.
159 -- It is this structure that is handed on to the desugarer
160
161 data TcGblEnv
162   = TcGblEnv {
163         tcg_mod     :: Module,         -- ^ Module being compiled
164         tcg_src     :: HscSource,
165           -- ^ What kind of module (regular Haskell, hs-boot, ext-core)
166
167         tcg_rdr_env :: GlobalRdrEnv,   -- ^ Top level envt; used during renaming
168         tcg_default :: Maybe [Type],
169           -- ^ Types used for defaulting. @Nothing@ => no @default@ decl
170
171         tcg_fix_env   :: FixityEnv,     -- ^ Just for things in this module
172         tcg_field_env :: RecFieldEnv,   -- ^ Just for things in this module
173
174         tcg_type_env :: TypeEnv,
175           -- ^ Global type env for the module we are compiling now.  All
176           -- TyCons and Classes (for this module) end up in here right away,
177           -- along with their derived constructors, selectors.
178           --
179           -- (Ids defined in this module start in the local envt, though they
180           --  move to the global envt during zonking)
181
182         tcg_type_env_var :: TcRef TypeEnv,
183                 -- Used only to initialise the interface-file
184                 -- typechecker in initIfaceTcRn, so that it can see stuff
185                 -- bound in this module when dealing with hi-boot recursions
186                 -- Updated at intervals (e.g. after dealing with types and classes)
187         
188         tcg_inst_env     :: InstEnv,
189           -- ^ Instance envt for /home-package/ modules; Includes the dfuns in
190           -- tcg_insts
191         tcg_fam_inst_env :: FamInstEnv, -- ^ Ditto for family instances
192
193                 -- Now a bunch of things about this module that are simply 
194                 -- accumulated, but never consulted until the end.  
195                 -- Nevertheless, it's convenient to accumulate them along 
196                 -- with the rest of the info from this module.
197         tcg_exports :: [AvailInfo],     -- ^ What is exported
198         tcg_imports :: ImportAvails,
199           -- ^ Information about what was imported from where, including
200           -- things bound in this module.
201
202         tcg_dus :: DefUses,
203           -- ^ What is defined in this module and what is used.
204           -- The latter is used to generate
205           --
206           --  (a) version tracking; no need to recompile if these things have
207           --      not changed version stamp
208           --
209           --  (b) unused-import info
210
211         tcg_keep :: TcRef NameSet,
212           -- ^ Locally-defined top-level names to keep alive.
213           --
214           -- "Keep alive" means give them an Exported flag, so that the
215           -- simplifier does not discard them as dead code, and so that they
216           -- are exposed in the interface file (but not to export to the
217           -- user).
218           --
219           -- Some things, like dict-fun Ids and default-method Ids are "born"
220           -- with the Exported flag on, for exactly the above reason, but some
221           -- we only discover as we go.  Specifically:
222           --
223           --   * The to/from functions for generic data types
224           --
225           --   * Top-level variables appearing free in the RHS of an orphan
226           --     rule
227           --
228           --   * Top-level variables appearing free in a TH bracket
229
230         tcg_th_used :: TcRef Bool,
231           -- ^ @True@ <=> Template Haskell syntax used.
232           --
233           -- We need this so that we can generate a dependency on the
234           -- Template Haskell package, becuase the desugarer is going
235           -- to emit loads of references to TH symbols.  The reference
236           -- is implicit rather than explicit, so we have to zap a
237           -- mutable variable.
238
239         tcg_dfun_n  :: TcRef OccSet,
240           -- ^ Allows us to choose unique DFun names.
241
242         -- The next fields accumulate the payload of the module
243         -- The binds, rules and foreign-decl fiels are collected
244         -- initially in un-zonked form and are finally zonked in tcRnSrcDecls
245
246         tcg_rn_exports :: Maybe [Located (IE Name)],
247         tcg_rn_imports :: [LImportDecl Name],
248                 -- Keep the renamed imports regardless.  They are not 
249                 -- voluminous and are needed if you want to report unused imports
250
251         tcg_used_rdrnames :: TcRef (Set RdrName),
252                 -- The set of used *imported* (not locally-defined) RdrNames
253                 -- Used only to report unused import declarations
254
255         tcg_rn_decls :: Maybe (HsGroup Name),
256           -- ^ Renamed decls, maybe.  @Nothing@ <=> Don't retain renamed
257           -- decls.
258
259         tcg_ev_binds  :: Bag EvBind,        -- Top-level evidence bindings
260         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
261         tcg_sigs      :: NameSet,           -- ...Top-level names that *lack* a signature
262         tcg_imp_specs :: [LTcSpecPrag],     -- ...SPECIALISE prags for imported Ids
263         tcg_warns     :: Warnings,          -- ...Warnings and deprecations
264         tcg_anns      :: [Annotation],      -- ...Annotations
265         tcg_insts     :: [Instance],        -- ...Instances
266         tcg_fam_insts :: [FamInst],         -- ...Family instances
267         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
268         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
269         tcg_vects     :: [LVectDecl Id],    -- ...Vectorisation declarations
270
271         tcg_doc_hdr   :: Maybe LHsDocString, -- ^ Maybe Haddock header docs
272         tcg_hpc       :: AnyHpcUsage,        -- ^ @True@ if any part of the
273                                              --  prog uses hpc instrumentation.
274
275         tcg_main      :: Maybe Name          -- ^ The Name of the main
276                                              -- function, if this module is
277                                              -- the main module.
278     }
279
280 data RecFieldEnv 
281   = RecFields (NameEnv [Name])  -- Maps a constructor name *in this module*
282                                 -- to the fields for that constructor
283               NameSet           -- Set of all fields declared *in this module*;
284                                 -- used to suppress name-shadowing complaints
285                                 -- when using record wild cards
286                                 -- E.g.  let fld = e in C {..}
287         -- This is used when dealing with ".." notation in record 
288         -- construction and pattern matching.
289         -- The FieldEnv deals *only* with constructors defined in *this*
290         -- module.  For imported modules, we get the same info from the
291         -- TypeEnv
292 \end{code}
293
294 %************************************************************************
295 %*                                                                      *
296                 The interface environments
297               Used when dealing with IfaceDecls
298 %*                                                                      *
299 %************************************************************************
300
301 \begin{code}
302 data IfGblEnv 
303   = IfGblEnv {
304         -- The type environment for the module being compiled,
305         -- in case the interface refers back to it via a reference that
306         -- was originally a hi-boot file.
307         -- We need the module name so we can test when it's appropriate
308         -- to look in this env.
309         if_rec_types :: Maybe (Module, IfG TypeEnv)
310                 -- Allows a read effect, so it can be in a mutable
311                 -- variable; c.f. handling the external package type env
312                 -- Nothing => interactive stuff, no loops possible
313     }
314
315 data IfLclEnv
316   = IfLclEnv {
317         -- The module for the current IfaceDecl
318         -- So if we see   f = \x -> x
319         -- it means M.f = \x -> x, where M is the if_mod
320         if_mod :: Module,
321
322         -- The field is used only for error reporting
323         -- if (say) there's a Lint error in it
324         if_loc :: SDoc,
325                 -- Where the interface came from:
326                 --      .hi file, or GHCi state, or ext core
327                 -- plus which bit is currently being examined
328
329         if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
330                                         -- (and coercions)
331         if_id_env  :: UniqFM Id         -- Nested id binding
332     }
333 \end{code}
334
335
336 %************************************************************************
337 %*                                                                      *
338                 The local typechecker environment
339 %*                                                                      *
340 %************************************************************************
341
342 The Global-Env/Local-Env story
343 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
344 During type checking, we keep in the tcg_type_env
345         * All types and classes
346         * All Ids derived from types and classes (constructors, selectors)
347
348 At the end of type checking, we zonk the local bindings,
349 and as we do so we add to the tcg_type_env
350         * Locally defined top-level Ids
351
352 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
353         a) fed back (via the knot) to typechecking the 
354            unfoldings of interface signatures
355         b) used in the ModDetails of this module
356
357 \begin{code}
358 data TcLclEnv           -- Changes as we move inside an expression
359                         -- Discarded after typecheck/rename; not passed on to desugarer
360   = TcLclEnv {
361         tcl_loc  :: SrcSpan,            -- Source span
362         tcl_ctxt :: [ErrCtxt],          -- Error context, innermost on top
363         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
364
365         tcl_th_ctxt    :: ThStage,            -- Template Haskell context
366         tcl_arrow_ctxt :: ArrowCtxt,          -- Arrow-notation context
367
368         tcl_rdr :: LocalRdrEnv,         -- Local name envt
369                 -- Maintained during renaming, of course, but also during
370                 -- type checking, solely so that when renaming a Template-Haskell
371                 -- splice we have the right environment for the renamer.
372                 -- 
373                 --   Does *not* include global name envt; may shadow it
374                 --   Includes both ordinary variables and type variables;
375                 --   they are kept distinct because tyvar have a different
376                 --   occurrence contructor (Name.TvOcc)
377                 -- We still need the unsullied global name env so that
378                 --   we can look up record field names
379
380         tcl_env  :: TcTypeEnv,    -- The local type environment: Ids and
381                                   -- TyVars defined in this module
382                                         
383         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
384                         -- Namely, the in-scope TyVars bound in tcl_env, 
385                         -- plus the tyvars mentioned in the types of Ids bound
386                         -- in tcl_lenv. 
387                         -- Why mutable? see notes with tcGetGlobalTyVars
388
389         tcl_lie   :: TcRef WantedConstraints,    -- Place to accumulate type constraints
390
391         -- TcMetaTyVars have 
392         tcl_meta  :: TcRef Unique,  -- The next free unique for TcMetaTyVars
393                                     -- Guaranteed to be allocated linearly
394         tcl_untch :: Unique         -- Any TcMetaTyVar with 
395                                     --     unique >= tcl_untch is touchable
396                                     --     unique <  tcl_untch is untouchable
397     }
398
399 type TcTypeEnv = NameEnv TcTyThing
400
401
402 {- Note [Given Insts]
403    ~~~~~~~~~~~~~~~~~~
404 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
405 and existential contexts. Consider
406         data T a where { T1 :: b -> b -> T [b] }
407         f :: Eq a => T a -> Bool
408         f (T1 x y) = [x]==[y]
409
410 The constructor T1 binds an existential variable 'b', and we need Eq [b].
411 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
412 pass it inwards.
413
414 -}
415
416 ---------------------------
417 -- Template Haskell stages and levels 
418 ---------------------------
419
420 data ThStage    -- See Note [Template Haskell state diagram] in TcSplice
421   = Splice      -- Top-level splicing
422                 -- This code will be run *at compile time*;
423                 --   the result replaces the splice
424                 -- Binding level = 0
425  
426   | Comp        -- Ordinary Haskell code
427                 -- Binding level = 1
428
429   | Brack                       -- Inside brackets 
430       ThStage                   --   Binding level = level(stage) + 1
431       (TcRef [PendingSplice])   --   Accumulate pending splices here
432       (TcRef WantedConstraints) --     and type constraints here
433
434 topStage, topAnnStage, topSpliceStage :: ThStage
435 topStage       = Comp
436 topAnnStage    = Splice
437 topSpliceStage = Splice
438
439 instance Outputable ThStage where
440    ppr Splice        = text "Splice"
441    ppr Comp          = text "Comp"
442    ppr (Brack s _ _) = text "Brack" <> parens (ppr s)
443
444 type ThLevel = Int      
445         -- See Note [Template Haskell levels] in TcSplice
446         -- Incremented when going inside a bracket,
447         -- decremented when going inside a splice
448         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
449         --     original "Template meta-programming for Haskell" paper
450
451 impLevel, outerLevel :: ThLevel
452 impLevel = 0    -- Imported things; they can be used inside a top level splice
453 outerLevel = 1  -- Things defined outside brackets
454 -- NB: Things at level 0 are not *necessarily* imported.
455 --      eg  $( \b -> ... )   here b is bound at level 0
456 --
457 -- For example: 
458 --      f = ...
459 --      g1 = $(map ...)         is OK
460 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
461
462 thLevel :: ThStage -> ThLevel
463 thLevel Splice        = 0
464 thLevel Comp          = 1
465 thLevel (Brack s _ _) = thLevel s + 1
466
467 ---------------------------
468 -- Arrow-notation context
469 ---------------------------
470
471 {-
472 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
473 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
474 For example
475
476         proc x -> (e1 -< e2)
477
478 Here, x is not in scope in e1, but it is in scope in e2.  This can get
479 a bit complicated:
480
481         let x = 3 in
482         proc y -> (proc z -> e1) -< e2
483
484 Here, x and z are in scope in e1, but y is not.  We implement this by
485 recording the environment when passing a proc (using newArrowScope),
486 and returning to that (using escapeArrowScope) on the left of -< and the
487 head of (|..|).
488 -}
489
490 data ArrowCtxt
491   = NoArrowCtxt
492   | ArrowCtxt (Env TcGblEnv TcLclEnv)
493
494 -- Record the current environment (outside a proc)
495 newArrowScope :: TcM a -> TcM a
496 newArrowScope
497   = updEnv $ \env ->
498         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
499
500 -- Return to the stored environment (from the enclosing proc)
501 escapeArrowScope :: TcM a -> TcM a
502 escapeArrowScope
503   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
504         NoArrowCtxt -> env
505         ArrowCtxt env' -> env'
506
507 ---------------------------
508 -- TcTyThing
509 ---------------------------
510
511 data TcTyThing
512   = AGlobal TyThing             -- Used only in the return type of a lookup
513
514   | ATcId   {           -- Ids defined in this module; may not be fully zonked
515         tct_id    :: TcId,              
516         tct_level :: ThLevel }
517
518   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
519                                 -- is currently refined. We only need the Name
520                                 -- for error-message purposes; it is the corresponding
521                                 -- Name in the domain of the envt
522
523   | AThing  TcKind              -- Used temporarily, during kind checking, for the
524                                 --      tycons and clases in this recursive group
525
526 instance Outputable TcTyThing where     -- Debugging only
527    ppr (AGlobal g)      = pprTyThing g
528    ppr elt@(ATcId {})   = text "Identifier" <> 
529                           brackets (ppr (tct_id elt) <> dcolon 
530                                  <> ppr (varType (tct_id elt)) <> comma
531                                  <+> ppr (tct_level elt))
532    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
533    ppr (AThing k)       = text "AThing" <+> ppr k
534
535 pprTcTyThingCategory :: TcTyThing -> SDoc
536 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
537 pprTcTyThingCategory (ATyVar {})     = ptext (sLit "Type variable")
538 pprTcTyThingCategory (ATcId {})      = ptext (sLit "Local identifier")
539 pprTcTyThingCategory (AThing {})     = ptext (sLit "Kinded thing")
540 \end{code}
541
542 \begin{code}
543 type ErrCtxt = (Bool, TidyEnv -> TcM (TidyEnv, Message))
544         -- Monadic so that we have a chance
545         -- to deal with bound type variables just before error
546         -- message construction
547
548         -- Bool:  True <=> this is a landmark context; do not
549         --                 discard it when trimming for display
550 \end{code}
551
552
553 %************************************************************************
554 %*                                                                      *
555         Operations over ImportAvails
556 %*                                                                      *
557 %************************************************************************
558
559 \begin{code}
560 -- | 'ImportAvails' summarises what was imported from where, irrespective of
561 -- whether the imported things are actually used or not.  It is used:
562 --
563 --  * when processing the export list,
564 --
565 --  * when constructing usage info for the interface file,
566 --
567 --  * to identify the list of directly imported modules for initialisation
568 --    purposes and for optimised overlap checking of family instances,
569 --
570 --  * when figuring out what things are really unused
571 --
572 data ImportAvails 
573    = ImportAvails {
574         imp_mods :: ModuleEnv [(ModuleName, Bool, SrcSpan)],
575           -- ^ Domain is all directly-imported modules
576           -- The 'ModuleName' is what the module was imported as, e.g. in
577           -- @
578           --     import Foo as Bar
579           -- @
580           -- it is @Bar@.
581           --
582           -- The 'Bool' means:
583           --
584           --  - @True@ => import was @import Foo ()@
585           --
586           --  - @False@ => import was some other form
587           --
588           -- Used
589           --
590           --   (a) to help construct the usage information in the interface
591           --       file; if we import somethign we need to recompile if the
592           --       export version changes
593           --
594           --   (b) to specify what child modules to initialise
595           --
596           -- We need a full ModuleEnv rather than a ModuleNameEnv here,
597           -- because we might be importing modules of the same name from
598           -- different packages. (currently not the case, but might be in the
599           -- future).
600
601         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
602           -- ^ Home-package modules needed by the module being compiled
603           --
604           -- It doesn't matter whether any of these dependencies
605           -- are actually /used/ when compiling the module; they
606           -- are listed if they are below it at all.  For
607           -- example, suppose M imports A which imports X.  Then
608           -- compiling M might not need to consult X.hi, but X
609           -- is still listed in M's dependencies.
610
611         imp_dep_pkgs :: [PackageId],
612           -- ^ Packages needed by the module being compiled, whether directly,
613           -- or via other modules in this package, or via modules imported
614           -- from other packages.
615
616         imp_orphs :: [Module],
617           -- ^ Orphan modules below us in the import tree (and maybe including
618           -- us for imported modules)
619
620         imp_finsts :: [Module]
621           -- ^ Family instance modules below us in the import tree (and maybe
622           -- including us for imported modules)
623       }
624
625 mkModDeps :: [(ModuleName, IsBootInterface)]
626           -> ModuleNameEnv (ModuleName, IsBootInterface)
627 mkModDeps deps = foldl add emptyUFM deps
628                where
629                  add env elt@(m,_) = addToUFM env m elt
630
631 emptyImportAvails :: ImportAvails
632 emptyImportAvails = ImportAvails { imp_mods     = emptyModuleEnv,
633                                    imp_dep_mods = emptyUFM,
634                                    imp_dep_pkgs = [],
635                                    imp_orphs    = [],
636                                    imp_finsts   = [] }
637
638 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
639 plusImportAvails
640   (ImportAvails { imp_mods = mods1,
641                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
642                   imp_orphs = orphs1, imp_finsts = finsts1 })
643   (ImportAvails { imp_mods = mods2,
644                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
645                   imp_orphs = orphs2, imp_finsts = finsts2 })
646   = ImportAvails { imp_mods     = plusModuleEnv_C (++) mods1 mods2,
647                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
648                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
649                    imp_orphs    = orphs1 `unionLists` orphs2,
650                    imp_finsts   = finsts1 `unionLists` finsts2 }
651   where
652     plus_mod_dep (m1, boot1) (m2, boot2) 
653         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
654                 -- Check mod-names match
655           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
656 \end{code}
657
658 %************************************************************************
659 %*                                                                      *
660 \subsection{Where from}
661 %*                                                                      *
662 %************************************************************************
663
664 The @WhereFrom@ type controls where the renamer looks for an interface file
665
666 \begin{code}
667 data WhereFrom 
668   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
669   | ImportBySystem                      -- Non user import.
670
671 instance Outputable WhereFrom where
672   ppr (ImportByUser is_boot) | is_boot     = ptext (sLit "{- SOURCE -}")
673                              | otherwise   = empty
674   ppr ImportBySystem                       = ptext (sLit "{- SYSTEM -}")
675 \end{code}
676
677
678 %************************************************************************
679 %*                                                                      *
680                 Wanted constraints
681      These are forced to be in TcRnTypes because
682            TcLclEnv mentions WantedConstraints
683            WantedConstraint mentions CtLoc
684            CtLoc mentions ErrCtxt
685            ErrCtxt mentions TcM
686 %*                                                                      *
687 v%************************************************************************
688
689 \begin{code}
690 data WantedConstraints
691   = WC { wc_flat  :: Bag WantedEvVar   -- Unsolved constraints, all wanted
692        , wc_impl  :: Bag Implication
693        , wc_insol :: Bag FlavoredEvVar -- Insoluble constraints, can be
694                                        -- wanted, given, or derived
695                                        -- See Note [Insoluble constraints]
696     }
697
698 emptyWC :: WantedConstraints
699 emptyWC = WC { wc_flat = emptyBag, wc_impl = emptyBag, wc_insol = emptyBag }
700
701 mkFlatWC :: Bag WantedEvVar -> WantedConstraints
702 mkFlatWC wevs = WC { wc_flat = wevs, wc_impl = emptyBag, wc_insol = emptyBag }
703
704 isEmptyWC :: WantedConstraints -> Bool
705 isEmptyWC (WC { wc_flat = f, wc_impl = i, wc_insol = n })
706   = isEmptyBag f && isEmptyBag i && isEmptyBag n
707
708 insolubleWC :: WantedConstraints -> Bool
709 -- True if there are any insoluble constraints in the wanted bag
710 insolubleWC wc = not (isEmptyBag (wc_insol wc))
711                || anyBag ic_insol (wc_impl wc)
712
713 andWC :: WantedConstraints -> WantedConstraints -> WantedConstraints
714 andWC (WC { wc_flat = f1, wc_impl = i1, wc_insol = n1 })
715       (WC { wc_flat = f2, wc_impl = i2, wc_insol = n2 })
716   = WC { wc_flat  = f1 `unionBags` f2
717        , wc_impl  = i1 `unionBags` i2
718        , wc_insol = n1 `unionBags` n2 }
719
720 addFlats :: WantedConstraints -> Bag WantedEvVar -> WantedConstraints
721 addFlats wc wevs = wc { wc_flat = wc_flat wc `unionBags` wevs }
722
723 addImplics :: WantedConstraints -> Bag Implication -> WantedConstraints
724 addImplics wc implic = wc { wc_impl = wc_impl wc `unionBags` implic }
725
726 instance Outputable WantedConstraints where
727   ppr (WC {wc_flat = f, wc_impl = i, wc_insol = n})
728    = ptext (sLit "WC") <+> braces (vcat
729         [ if isEmptyBag f then empty else
730           ptext (sLit "wc_flat =")  <+> pprBag pprWantedEvVar f
731         , if isEmptyBag i then empty else
732           ptext (sLit "wc_impl =")  <+> pprBag ppr i
733         , if isEmptyBag n then empty else
734           ptext (sLit "wc_insol =") <+> pprBag ppr n ])
735
736 pprBag :: (a -> SDoc) -> Bag a -> SDoc
737 pprBag pp b = foldrBag (($$) . pp) empty b
738 \end{code}
739  
740
741 \begin{code}
742 data Untouchables = NoUntouchables
743                   | TouchableRange
744                           Unique  -- Low end
745                           Unique  -- High end
746  -- A TcMetaTyvar is *touchable* iff its unique u satisfies
747  --   u >= low
748  --   u < high
749
750 instance Outputable Untouchables where
751   ppr NoUntouchables = ptext (sLit "No untouchables")
752   ppr (TouchableRange low high) = ptext (sLit "Touchable range:") <+> 
753                                   ppr low <+> char '-' <+> ppr high
754
755 isNoUntouchables :: Untouchables -> Bool
756 isNoUntouchables NoUntouchables      = True
757 isNoUntouchables (TouchableRange {}) = False
758
759 inTouchableRange :: Untouchables -> TcTyVar -> Bool
760 inTouchableRange NoUntouchables _ = True
761 inTouchableRange (TouchableRange low high) tv 
762   = uniq >= low && uniq < high
763   where
764     uniq = varUnique tv
765
766 -- EvVar defined in module Var.lhs:
767 -- Evidence variables include all *quantifiable* constraints
768 --   dictionaries
769 --   implicit parameters
770 --   coercion variables
771 \end{code}
772
773 %************************************************************************
774 %*                                                                      *
775                 Implication constraints
776 %*                                                                      *
777 %************************************************************************
778
779 \begin{code}
780 data Implication
781   = Implic {  
782       ic_untch :: Untouchables, -- Untouchables: unification variables
783                                 -- free in the environment
784       ic_env   :: TcTypeEnv,    -- The type environment
785                                 -- Used only when generating error messages
786           -- Generally, ic_untch is a superset of tvsof(ic_env)
787           -- However, we don't zonk ic_env when zonking the Implication
788           -- Instead we do that when generating a skolem-escape error message
789
790       ic_skols  :: TcTyVarSet,   -- Introduced skolems 
791                                  -- See Note [Skolems in an implication]
792
793       ic_given  :: [EvVar],      -- Given evidence variables
794                                  --   (order does not matter)
795       ic_loc   :: GivenLoc,      -- Binding location of the implication,
796                                  --   which is also the location of all the
797                                  --   given evidence variables
798
799       ic_wanted :: WantedConstraints,  -- The wanted
800       ic_insol  :: Bool,               -- True iff insolubleWC ic_wanted is true
801
802       ic_binds  :: EvBindsVar   -- Points to the place to fill in the
803                                 -- abstraction and bindings
804     }
805
806 instance Outputable Implication where
807   ppr (Implic { ic_untch = untch, ic_skols = skols, ic_given = given
808               , ic_wanted = wanted
809               , ic_binds = binds, ic_loc = loc })
810    = ptext (sLit "Implic") <+> braces 
811      (sep [ ptext (sLit "Untouchables = ") <+> ppr untch
812           , ptext (sLit "Skolems = ") <+> ppr skols
813           , ptext (sLit "Given = ") <+> pprEvVars given
814           , ptext (sLit "Wanted = ") <+> ppr wanted
815           , ptext (sLit "Binds = ") <+> ppr binds
816           , pprSkolInfo (ctLocOrigin loc)
817           , ppr (ctLocSpan loc) ])
818 \end{code}
819
820 Note [Skolems in an implication]
821 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
822 The skolems in an implication are not there to perform a skolem escape
823 check.  That happens because all the environment variables are in the
824 untouchables, and therefore cannot be unified with anything at all,
825 let alone the skolems.
826
827 Instead, ic_skols is used only when considering floating a constraint
828 outside the implication in TcSimplify.floatEqualities or 
829 TcSimplify.approximateImplications
830
831 Note [Insoluble constraints]
832 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
833 Some of the errors that we get during canonicalization are best
834 reported when all constraints have been simplified as much as
835 possible. For instance, assume that during simplification the
836 following constraints arise:
837    
838  [Wanted]   F alpha ~  uf1 
839  [Wanted]   beta ~ uf1 beta 
840
841 When canonicalizing the wanted (beta ~ uf1 beta), if we eagerly fail
842 we will simply see a message:
843     'Can't construct the infinite type  beta ~ uf1 beta' 
844 and the user has no idea what the uf1 variable is.
845
846 Instead our plan is that we will NOT fail immediately, but:
847     (1) Record the "frozen" error in the ic_insols field
848     (2) Isolate the offending constraint from the rest of the inerts 
849     (3) Keep on simplifying/canonicalizing
850
851 At the end, we will hopefully have substituted uf1 := F alpha, and we
852 will be able to report a more informative error:
853     'Can't construct the infinite type beta ~ F alpha beta'
854
855 %************************************************************************
856 %*                                                                      *
857             EvVarX, WantedEvVar, FlavoredEvVar
858 %*                                                                      *
859 %************************************************************************
860
861 \begin{code}
862 data EvVarX a = EvVarX EvVar a
863      -- An evidence variable with accompanying info
864
865 type WantedEvVar   = EvVarX WantedLoc     -- The location where it arose
866 type FlavoredEvVar = EvVarX CtFlavor
867
868 instance Outputable (EvVarX a) where
869   ppr (EvVarX ev _) = pprEvVarWithType ev
870   -- If you want to see the associated info,
871   -- use a more specific printing function
872
873 mkEvVarX :: EvVar -> a -> EvVarX a
874 mkEvVarX = EvVarX
875
876 evVarOf :: EvVarX a -> EvVar
877 evVarOf (EvVarX ev _) = ev
878
879 evVarX :: EvVarX a -> a
880 evVarX (EvVarX _ a) = a
881
882 evVarOfPred :: EvVarX a -> PredType
883 evVarOfPred wev = evVarPred (evVarOf wev)
884
885 wantedToFlavored :: WantedEvVar -> FlavoredEvVar
886 wantedToFlavored (EvVarX v wl) = EvVarX v (Wanted wl)
887
888 keepWanted :: Bag FlavoredEvVar -> Bag WantedEvVar
889 keepWanted flevs
890   = foldrBag keep_wanted emptyBag flevs
891     -- Important: use fold*r*Bag to preserve the order of the evidence variables.
892   where
893     keep_wanted :: FlavoredEvVar -> Bag WantedEvVar -> Bag WantedEvVar
894     keep_wanted (EvVarX ev (Wanted wloc)) r = consBag (EvVarX ev wloc) r
895     keep_wanted _                         r = r
896 \end{code}
897
898
899 \begin{code}
900 pprEvVars :: [EvVar] -> SDoc    -- Print with their types
901 pprEvVars ev_vars = vcat (map pprEvVarWithType ev_vars)
902
903 pprEvVarTheta :: [EvVar] -> SDoc
904 pprEvVarTheta ev_vars = pprTheta (map evVarPred ev_vars)
905                               
906 pprEvVarWithType :: EvVar -> SDoc
907 pprEvVarWithType v = ppr v <+> dcolon <+> pprPredTy (evVarPred v)
908
909 pprWantedsWithLocs :: WantedConstraints -> SDoc
910 pprWantedsWithLocs wcs
911   =  vcat [ pprBag pprWantedEvVarWithLoc (wc_flat wcs)
912           , pprBag ppr (wc_impl wcs)
913           , pprBag ppr (wc_insol wcs) ]
914
915 pprWantedEvVarWithLoc, pprWantedEvVar :: WantedEvVar -> SDoc
916 pprWantedEvVarWithLoc (EvVarX v loc) = hang (pprEvVarWithType v)
917                                           2 (pprArisingAt loc)
918 pprWantedEvVar        (EvVarX v _)   = pprEvVarWithType v
919 \end{code}
920
921 %************************************************************************
922 %*                                                                      *
923             CtLoc
924 %*                                                                      *
925 %************************************************************************
926
927 \begin{code}
928 data CtFlavor
929   = Given GivenLoc GivenKind -- We have evidence for this constraint in TcEvBinds
930   | Derived WantedLoc        -- Derived's are just hints for unifications 
931   | Wanted WantedLoc         -- We have no evidence bindings for this constraint. 
932
933 data GivenKind
934   = GivenOrig   -- Originates in some given, such as signature or pattern match
935   | GivenSolved -- Is given as result of being solved, maybe provisionally on
936                 -- some other wanted constraints. 
937
938 instance Outputable CtFlavor where
939   ppr (Given _ GivenOrig)   = ptext (sLit "[G]")
940   ppr (Given _ GivenSolved) = ptext (sLit "[S]") -- Print [S] for Given/Solved's
941   ppr (Wanted {})           = ptext (sLit "[W]")
942   ppr (Derived {})          = ptext (sLit "[D]") 
943
944 pprFlavorArising :: CtFlavor -> SDoc
945 pprFlavorArising (Derived wl)   = pprArisingAt wl
946 pprFlavorArising (Wanted  wl)   = pprArisingAt wl
947 pprFlavorArising (Given gl _)   = pprArisingAt gl
948
949 isWanted :: CtFlavor -> Bool
950 isWanted (Wanted {}) = True
951 isWanted _           = False
952
953 isGivenOrSolved :: CtFlavor -> Bool
954 isGivenOrSolved (Given {}) = True
955 isGivenOrSolved _ = False
956
957 isGiven_maybe :: CtFlavor -> Maybe GivenKind 
958 isGiven_maybe (Given _ gk) = Just gk
959 isGiven_maybe _            = Nothing
960
961 isDerived :: CtFlavor -> Bool 
962 isDerived (Derived {}) = True
963 isDerived _            = False
964 \end{code}
965
966 %************************************************************************
967 %*                                                                      *
968             CtLoc
969 %*                                                                      *
970 %************************************************************************
971
972 The 'CtLoc' gives information about where a constraint came from.
973 This is important for decent error message reporting because
974 dictionaries don't appear in the original source code.
975 type will evolve...
976
977 \begin{code}
978 data CtLoc orig = CtLoc orig SrcSpan [ErrCtxt]
979
980 type WantedLoc = CtLoc CtOrigin      -- Instantiation for wanted constraints
981 type GivenLoc  = CtLoc SkolemInfo    -- Instantiation for given constraints
982
983 ctLocSpan :: CtLoc o -> SrcSpan
984 ctLocSpan (CtLoc _ s _) = s
985
986 ctLocOrigin :: CtLoc o -> o
987 ctLocOrigin (CtLoc o _ _) = o
988
989 setCtLocOrigin :: CtLoc o -> o' -> CtLoc o'
990 setCtLocOrigin (CtLoc _ s c) o = CtLoc o s c
991
992 pushErrCtxt :: orig -> ErrCtxt -> CtLoc orig -> CtLoc orig
993 pushErrCtxt o err (CtLoc _ s errs) = CtLoc o s (err:errs)
994
995 pprArising :: CtOrigin -> SDoc
996 -- Used for the main, top-level error message
997 -- We've done special processing for TypeEq and FunDep origins
998 pprArising (TypeEqOrigin {}) = empty
999 pprArising FunDepOrigin      = empty
1000 pprArising orig              = text "arising from" <+> ppr orig
1001
1002 pprArisingAt :: Outputable o => CtLoc o -> SDoc
1003 pprArisingAt (CtLoc o s _) = sep [ text "arising from" <+> ppr o
1004                                  , text "at" <+> ppr s]
1005 \end{code}
1006
1007 %************************************************************************
1008 %*                                                                      *
1009                 SkolemInfo
1010 %*                                                                      *
1011 %************************************************************************
1012
1013 \begin{code}
1014 -- SkolemInfo gives the origin of *given* constraints
1015 --   a) type variables are skolemised
1016 --   b) an implication constraint is generated
1017 data SkolemInfo
1018   = SigSkol UserTypeCtxt        -- A skolem that is created by instantiating
1019             Type                -- a programmer-supplied type signature
1020                                 -- Location of the binding site is on the TyVar
1021
1022         -- The rest are for non-scoped skolems
1023   | ClsSkol Class       -- Bound at a class decl
1024   | InstSkol            -- Bound at an instance decl
1025   | DataSkol            -- Bound at a data type declaration
1026   | FamInstSkol         -- Bound at a family instance decl
1027   | PatSkol             -- An existential type variable bound by a pattern for
1028       DataCon           -- a data constructor with an existential type.
1029       (HsMatchContext Name)     
1030              -- e.g.   data T = forall a. Eq a => MkT a
1031              --        f (MkT x) = ...
1032              -- The pattern MkT x will allocate an existential type
1033              -- variable for 'a'.  
1034
1035   | ArrowSkol           -- An arrow form (see TcArrows)
1036
1037   | IPSkol [IPName Name]  -- Binding site of an implicit parameter
1038
1039   | RuleSkol RuleName   -- The LHS of a RULE
1040
1041   | InferSkol [(Name,TcType)]
1042                         -- We have inferred a type for these (mutually-recursivive)
1043                         -- polymorphic Ids, and are now checking that their RHS
1044                         -- constraints are satisfied.
1045
1046   | BracketSkol         -- Template Haskell bracket
1047
1048   | UnkSkol             -- Unhelpful info (until I improve it)
1049
1050 instance Outputable SkolemInfo where
1051   ppr = pprSkolInfo
1052
1053 pprSkolInfo :: SkolemInfo -> SDoc
1054 -- Complete the sentence "is a rigid type variable bound by..."
1055 pprSkolInfo (SigSkol (FunSigCtxt f) ty)
1056                             = hang (ptext (sLit "the type signature for"))
1057                                  2 (ppr f <+> dcolon <+> ppr ty)
1058 pprSkolInfo (SigSkol cx ty) = hang (pprUserTypeCtxt cx <> colon)
1059                                  2 (ppr ty)
1060 pprSkolInfo (IPSkol ips)    = ptext (sLit "the implicit-parameter bindings for")
1061                               <+> pprWithCommas ppr ips
1062 pprSkolInfo (ClsSkol cls)   = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
1063 pprSkolInfo InstSkol        = ptext (sLit "the instance declaration")
1064 pprSkolInfo DataSkol        = ptext (sLit "the data type declaration")
1065 pprSkolInfo FamInstSkol     = ptext (sLit "the family instance declaration")
1066 pprSkolInfo BracketSkol     = ptext (sLit "a Template Haskell bracket")
1067 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
1068 pprSkolInfo ArrowSkol       = ptext (sLit "the arrow form")
1069 pprSkolInfo (PatSkol dc mc)  = sep [ ptext (sLit "a pattern with constructor")
1070                                    , nest 2 $ ppr dc <+> dcolon
1071                                               <+> ppr (dataConUserType dc) <> comma
1072                                   , ptext (sLit "in") <+> pprMatchContext mc ]
1073 pprSkolInfo (InferSkol ids) = sep [ ptext (sLit "the inferred type of")
1074                                   , vcat [ ppr name <+> dcolon <+> ppr ty
1075                                          | (name,ty) <- ids ]]
1076
1077 -- UnkSkol
1078 -- For type variables the others are dealt with by pprSkolTvBinding.  
1079 -- For Insts, these cases should not happen
1080 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
1081 \end{code}
1082
1083
1084 %************************************************************************
1085 %*                                                                      *
1086             CtOrigin
1087 %*                                                                      *
1088 %************************************************************************
1089
1090 \begin{code}
1091 -- CtOrigin gives the origin of *wanted* constraints
1092 data CtOrigin
1093   = OccurrenceOf Name           -- Occurrence of an overloaded identifier
1094   | AppOrigin                   -- An application of some kind
1095
1096   | SpecPragOrigin Name         -- Specialisation pragma for identifier
1097
1098   | TypeEqOrigin EqOrigin
1099
1100   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
1101
1102   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
1103   | NegateOrigin                        -- Occurrence of syntactic negation
1104
1105   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
1106   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
1107   | SectionOrigin
1108   | TupleOrigin                        -- (..,..)
1109   | ExprSigOrigin       -- e :: ty
1110   | PatSigOrigin        -- p :: ty
1111   | PatOrigin           -- Instantiating a polytyped pattern at a constructor
1112   | RecordUpdOrigin
1113   | ViewPatOrigin
1114
1115   | ScOrigin            -- Typechecking superclasses of an instance declaration
1116   | DerivOrigin         -- Typechecking deriving
1117   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
1118   | DefaultOrigin       -- Typechecking a default decl
1119   | DoOrigin            -- Arising from a do expression
1120   | MCompOrigin         -- Arising from a monad comprehension
1121   | IfOrigin            -- Arising from an if statement
1122   | ProcOrigin          -- Arising from a proc expression
1123   | AnnOrigin           -- An annotation
1124   | FunDepOrigin
1125
1126 data EqOrigin 
1127   = UnifyOrigin 
1128        { uo_actual   :: TcType
1129        , uo_expected :: TcType }
1130
1131 instance Outputable CtOrigin where
1132   ppr orig = pprO orig
1133
1134 pprO :: CtOrigin -> SDoc
1135 pprO (OccurrenceOf name)   = hsep [ptext (sLit "a use of"), quotes (ppr name)]
1136 pprO AppOrigin             = ptext (sLit "an application")
1137 pprO (SpecPragOrigin name) = hsep [ptext (sLit "a specialisation pragma for"), quotes (ppr name)]
1138 pprO (IPOccOrigin name)    = hsep [ptext (sLit "a use of implicit parameter"), quotes (ppr name)]
1139 pprO RecordUpdOrigin       = ptext (sLit "a record update")
1140 pprO ExprSigOrigin         = ptext (sLit "an expression type signature")
1141 pprO PatSigOrigin          = ptext (sLit "a pattern type signature")
1142 pprO PatOrigin             = ptext (sLit "a pattern")
1143 pprO ViewPatOrigin         = ptext (sLit "a view pattern")
1144 pprO IfOrigin              = ptext (sLit "an if statement")
1145 pprO (LiteralOrigin lit)   = hsep [ptext (sLit "the literal"), quotes (ppr lit)]
1146 pprO (ArithSeqOrigin seq)  = hsep [ptext (sLit "the arithmetic sequence"), quotes (ppr seq)]
1147 pprO (PArrSeqOrigin seq)   = hsep [ptext (sLit "the parallel array sequence"), quotes (ppr seq)]
1148 pprO SectionOrigin         = ptext (sLit "an operator section")
1149 pprO TupleOrigin           = ptext (sLit "a tuple")
1150 pprO NegateOrigin          = ptext (sLit "a use of syntactic negation")
1151 pprO ScOrigin              = ptext (sLit "the superclasses of an instance declaration")
1152 pprO DerivOrigin           = ptext (sLit "the 'deriving' clause of a data type declaration")
1153 pprO StandAloneDerivOrigin = ptext (sLit "a 'deriving' declaration")
1154 pprO DefaultOrigin         = ptext (sLit "a 'default' declaration")
1155 pprO DoOrigin              = ptext (sLit "a do statement")
1156 pprO MCompOrigin           = ptext (sLit "a statement in a monad comprehension")
1157 pprO ProcOrigin            = ptext (sLit "a proc expression")
1158 pprO (TypeEqOrigin eq)     = ptext (sLit "an equality") <+> ppr eq
1159 pprO AnnOrigin             = ptext (sLit "an annotation")
1160 pprO FunDepOrigin          = ptext (sLit "a functional dependency")
1161
1162 instance Outputable EqOrigin where
1163   ppr (UnifyOrigin t1 t2) = ppr t1 <+> char '~' <+> ppr t2
1164 \end{code}
1165