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