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