be37c16940f96802c1b72f9cc985d56e9daa6004
[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, 
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(..), 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   ) where
39
40 #include "HsVersions.h"
41
42 import HsSyn hiding (LIE)
43 import HscTypes
44 import Packages
45 import Type
46 import TcType
47 import TcGadt
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 UniqFM
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
69 import Data.Maybe
70 import Data.List
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76                Standard monad definition for TcRn
77     All the combinators for the monad can be found in TcRnMonad
78 %*                                                                      *
79 %************************************************************************
80
81 The monad itself has to be defined here, because it is mentioned by ErrCtxt
82
83 \begin{code}
84 type TcRef a     = IORef a
85 type TcId        = Id                   -- Type may be a TcType
86 type TcIdSet     = IdSet
87 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
88
89 type TcRnIf a b c = IOEnv (Env a b) c
90 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
91
92 type IfG a  = IfM () a                          -- Top level
93 type IfL a  = IfM IfLclEnv a                    -- Nested
94 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
95 type RnM  a = TcRn a            -- Historical
96 type TcM  a = TcRn a            -- Historical
97 \end{code}
98
99
100 %************************************************************************
101 %*                                                                      *
102                 The main environment types
103 %*                                                                      *
104 %************************************************************************
105
106 \begin{code}
107 data Env gbl lcl        -- Changes as we move into an expression
108   = Env {
109         env_top  :: HscEnv,     -- Top-level stuff that never changes
110                                 -- Includes all info about imported things
111
112         env_us   :: {-# UNPACK #-} !(IORef UniqSupply), 
113                                 -- Unique supply for local varibles
114
115         env_gbl  :: gbl,        -- Info about things defined at the top level
116                                 -- of the module being compiled
117
118         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
119                                 -- an expression
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                 -- The next fields accumulate the payload of the
212                 -- module The binds, rules and foreign-decl fiels are
213                 -- collected initially in un-zonked form and are
214                 -- finally zonked in tcRnSrcDecls
215
216         tcg_rn_imports :: Maybe [LImportDecl Name],
217         tcg_rn_exports :: Maybe [Located (IE Name)],
218         tcg_rn_decls :: Maybe (HsGroup Name),   -- renamed decls, maybe
219                 -- Nothing <=> Don't retain renamed decls
220
221         tcg_binds     :: LHsBinds Id,       -- Value bindings in this module
222         tcg_deprecs   :: Deprecations,      -- ...Deprecations 
223         tcg_insts     :: [Instance],        -- ...Instances
224         tcg_fam_insts :: [FamInst],         -- ...Family instances
225         tcg_rules     :: [LRuleDecl Id],    -- ...Rules
226         tcg_fords     :: [LForeignDecl Id], -- ...Foreign import & exports
227
228         tcg_doc :: Maybe (HsDoc Name), -- Maybe Haddock documentation
229         tcg_hmi :: HaddockModInfo Name -- Haddock module information
230     }
231
232 type RecFieldEnv = NameEnv [Name]       -- Maps a constructor name *in this module*
233                                         -- to the fields for that constructor
234         -- This is used when dealing with ".." notation in record 
235         -- construction and pattern matching.
236         -- The FieldEnv deals *only* with constructors defined in
237         -- *thie* module.  For imported modules, we get the same info
238         -- from the TypeEnv
239 \end{code}
240
241 %************************************************************************
242 %*                                                                      *
243                 The interface environments
244               Used when dealing with IfaceDecls
245 %*                                                                      *
246 %************************************************************************
247
248 \begin{code}
249 data IfGblEnv 
250   = IfGblEnv {
251         -- The type environment for the module being compiled,
252         -- in case the interface refers back to it via a reference that
253         -- was originally a hi-boot file.
254         -- We need the module name so we can test when it's appropriate
255         -- to look in this env.
256         if_rec_types :: Maybe (Module, IfG TypeEnv)
257                 -- Allows a read effect, so it can be in a mutable
258                 -- variable; c.f. handling the external package type env
259                 -- Nothing => interactive stuff, no loops possible
260     }
261
262 data IfLclEnv
263   = IfLclEnv {
264         -- The module for the current IfaceDecl
265         -- So if we see   f = \x -> x
266         -- it means M.f = \x -> x, where M is the if_mod
267         if_mod :: Module,
268
269         -- The field is used only for error reporting
270         -- if (say) there's a Lint error in it
271         if_loc :: SDoc,
272                 -- Where the interface came from:
273                 --      .hi file, or GHCi state, or ext core
274                 -- plus which bit is currently being examined
275
276         if_tv_env  :: UniqFM TyVar,     -- Nested tyvar bindings
277         if_id_env  :: UniqFM Id         -- Nested id binding
278     }
279 \end{code}
280
281
282 %************************************************************************
283 %*                                                                      *
284                 The local typechecker environment
285 %*                                                                      *
286 %************************************************************************
287
288 The Global-Env/Local-Env story
289 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
290 During type checking, we keep in the tcg_type_env
291         * All types and classes
292         * All Ids derived from types and classes (constructors, selectors)
293
294 At the end of type checking, we zonk the local bindings,
295 and as we do so we add to the tcg_type_env
296         * Locally defined top-level Ids
297
298 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
299         a) fed back (via the knot) to typechecking the 
300            unfoldings of interface signatures
301         b) used in the ModDetails of this module
302
303 \begin{code}
304 data TcLclEnv           -- Changes as we move inside an expression
305                         -- Discarded after typecheck/rename; not passed on to desugarer
306   = TcLclEnv {
307         tcl_loc  :: SrcSpan,            -- Source span
308         tcl_ctxt :: ErrCtxt,            -- Error context
309         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
310
311         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
312         tcl_arrow_ctxt :: ArrowCtxt,    -- Arrow-notation context
313
314         tcl_rdr :: LocalRdrEnv,         -- Local name envt
315                 -- Maintained during renaming, of course, but also during
316                 -- type checking, solely so that when renaming a Template-Haskell
317                 -- splice we have the right environment for the renamer.
318                 --
319                 -- Used only for names bound within a value binding (bound by
320                 -- lambda, case, where, let etc), but *not* for top-level names.
321                 -- 
322                 -- Does *not* include global name envt; may shadow it
323                 -- Includes both ordinary variables and type variables;
324                 -- they are kept distinct because tyvar have a different
325                 -- occurrence contructor (Name.TvOcc)
326                 -- 
327                 -- We still need the unsullied global name env so that
328                 --   we can look up record field names
329
330         tcl_env  :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
331                                         -- defined in this module
332                                         
333         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
334                         -- Namely, the in-scope TyVars bound in tcl_env, 
335                         -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
336                         -- Why mutable? see notes with tcGetGlobalTyVars
337
338         tcl_lie   :: TcRef LIE          -- Place to accumulate type constraints
339     }
340
341
342 {- Note [Given Insts]
343    ~~~~~~~~~~~~~~~~~~
344 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
345 and existential contexts. Consider
346         data T a where { T1 :: b -> b -> T [b] }
347         f :: Eq a => T a -> Bool
348         f (T1 x y) = [x]==[y]
349
350 The constructor T1 binds an existential variable 'b', and we need Eq [b].
351 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
352 pass it inwards.
353
354 -}
355
356 ---------------------------
357 -- Template Haskell levels 
358 ---------------------------
359
360 type ThLevel = Int      
361         -- Indicates how many levels of brackets we are inside
362         --      (always >= 0)
363         -- Incremented when going inside a bracket,
364         -- decremented when going inside a splice
365         -- NB: ThLevel is one greater than the 'n' in Fig 2 of the
366         --     original "Template meta-programmign for Haskell" paper
367
368 impLevel, topLevel :: ThLevel
369 topLevel = 1    -- Things defined at top level of this module
370 impLevel = 0    -- Imported things; they can be used inside a top level splice
371 --
372 -- For example: 
373 --      f = ...
374 --      g1 = $(map ...)         is OK
375 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
376
377
378 data ThStage
379   = Comp                                -- Ordinary compiling, at level topLevel
380   | Splice ThLevel                      -- Inside a splice
381   | Brack  ThLevel                      -- Inside brackets; 
382            (TcRef [PendingSplice])      --   accumulate pending splices here
383            (TcRef LIE)                  --   and type constraints here
384 topStage, topSpliceStage :: ThStage
385 topStage       = Comp
386 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
387
388 ---------------------------
389 -- Arrow-notation context
390 ---------------------------
391
392 {-
393 In arrow notation, a variable bound by a proc (or enclosed let/kappa)
394 is not in scope to the left of an arrow tail (-<) or the head of (|..|).
395 For example
396
397         proc x -> (e1 -< e2)
398
399 Here, x is not in scope in e1, but it is in scope in e2.  This can get
400 a bit complicated:
401
402         let x = 3 in
403         proc y -> (proc z -> e1) -< e2
404
405 Here, x and z are in scope in e1, but y is not.  We implement this by
406 recording the environment when passing a proc (using newArrowScope),
407 and returning to that (using escapeArrowScope) on the left of -< and the
408 head of (|..|).
409 -}
410
411 data ArrowCtxt
412   = NoArrowCtxt
413   | ArrowCtxt (Env TcGblEnv TcLclEnv)
414
415 -- Record the current environment (outside a proc)
416 newArrowScope :: TcM a -> TcM a
417 newArrowScope
418   = updEnv $ \env ->
419         env { env_lcl = (env_lcl env) { tcl_arrow_ctxt = ArrowCtxt env } }
420
421 -- Return to the stored environment (from the enclosing proc)
422 escapeArrowScope :: TcM a -> TcM a
423 escapeArrowScope
424   = updEnv $ \ env -> case tcl_arrow_ctxt (env_lcl env) of
425         NoArrowCtxt -> env
426         ArrowCtxt env' -> env'
427
428 ---------------------------
429 -- TcTyThing
430 ---------------------------
431
432 data TcTyThing
433   = AGlobal TyThing             -- Used only in the return type of a lookup
434
435   | ATcId   {           -- Ids defined in this module; may not be fully zonked
436         tct_id :: TcId,         
437         tct_co :: Maybe HsWrapper,      -- Nothing <=>  Do not apply a GADT type refinement
438                                         --              I am wobbly, or have no free
439                                         --              type variables
440                                         -- Just co <=>  Apply any type refinement to me,
441                                         --              and record it in the coercion
442         tct_type  :: TcType,    -- Type of (coercion applied to id)
443         tct_level :: ThLevel }
444
445   | ATyVar  Name TcType         -- The type to which the lexically scoped type vaiable
446                                 -- is currently refined. We only need the Name
447                                 -- for error-message purposes
448
449   | AThing  TcKind              -- Used temporarily, during kind checking, for the
450                                 --      tycons and clases in this recursive group
451
452 instance Outputable TcTyThing where     -- Debugging only
453    ppr (AGlobal g)      = ppr g
454    ppr elt@(ATcId {})   = text "Identifier" <> 
455                           ifPprDebug (brackets (ppr (tct_id elt) <> dcolon <> ppr (tct_type elt) <> comma
456                                  <+> ppr (tct_level elt) <+> ppr (tct_co elt)))
457    ppr (ATyVar tv _)    = text "Type variable" <+> quotes (ppr tv)
458    ppr (AThing k)       = text "AThing" <+> ppr k
459
460 pprTcTyThingCategory :: TcTyThing -> SDoc
461 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
462 pprTcTyThingCategory (ATyVar {})     = ptext SLIT("Type variable")
463 pprTcTyThingCategory (ATcId {})      = ptext SLIT("Local identifier")
464 pprTcTyThingCategory (AThing {})     = ptext SLIT("Kinded thing")
465 \end{code}
466
467 \begin{code}
468 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
469                         -- Innermost first.  Monadic so that we have a chance
470                         -- to deal with bound type variables just before error
471                         -- message construction
472 \end{code}
473
474
475 %************************************************************************
476 %*                                                                      *
477         Operations over ImportAvails
478 %*                                                                      *
479 %************************************************************************
480
481 ImportAvails summarises what was imported from where, irrespective
482 of whether the imported things are actually used or not
483 It is used      * when processing the export list
484                 * when constructing usage info for the inteface file
485                 * to identify the list of directly imported modules
486                         for initialisation purposes and
487                         for optimsed overlap checking of family instances
488                 * when figuring out what things are really unused
489
490 \begin{code}
491 data ImportAvails 
492    = ImportAvails {
493         imp_mods :: ModuleEnv (Module, Bool, SrcSpan),
494                 -- Domain is all directly-imported modules
495                 -- Bool means:
496                 --   True => import was "import Foo ()"
497                 --   False  => import was some other form
498                 --
499                 -- We need the Module in the range because we can't get
500                 --      the keys of a ModuleEnv
501                 -- Used 
502                 --   (a) to help construct the usage information in 
503                 --       the interface file; if we import somethign we
504                 --       need to recompile if the export version changes
505                 --   (b) to specify what child modules to initialise
506                 --
507                 -- We need a full ModuleEnv rather than a ModuleNameEnv
508                 -- here, because we might be importing modules of the
509                 -- same name from different packages. (currently not the case,
510                 -- but might be in the future).
511
512         imp_dep_mods :: ModuleNameEnv (ModuleName, IsBootInterface),
513                 -- Home-package modules needed by the module being compiled
514                 --
515                 -- It doesn't matter whether any of these dependencies
516                 -- are actually *used* when compiling the module; they
517                 -- are listed if they are below it at all.  For
518                 -- example, suppose M imports A which imports X.  Then
519                 -- compiling M might not need to consult X.hi, but X
520                 -- is still listed in M's dependencies.
521
522         imp_dep_pkgs :: [PackageId],
523                 -- Packages needed by the module being compiled, whether
524                 -- directly, or via other modules in this package, or via
525                 -- modules imported from other packages.
526
527         imp_orphs :: [Module],
528                 -- Orphan modules below us in the import tree (and maybe
529                 -- including us for imported modules) 
530
531         imp_finsts :: [Module]
532                 -- Family instance modules below us in the import tree  (and
533                 -- maybe including us for imported modules)
534       }
535
536 mkModDeps :: [(ModuleName, IsBootInterface)]
537           -> ModuleNameEnv (ModuleName, IsBootInterface)
538 mkModDeps deps = foldl add emptyUFM deps
539                where
540                  add env elt@(m,_) = addToUFM env m elt
541
542 emptyImportAvails :: ImportAvails
543 emptyImportAvails = ImportAvails { imp_mods     = emptyModuleEnv,
544                                    imp_dep_mods = emptyUFM,
545                                    imp_dep_pkgs = [],
546                                    imp_orphs    = [],
547                                    imp_finsts   = [] }
548
549 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
550 plusImportAvails
551   (ImportAvails { imp_mods = mods1,
552                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, 
553                   imp_orphs = orphs1, imp_finsts = finsts1 })
554   (ImportAvails { imp_mods = mods2,
555                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2,
556                   imp_orphs = orphs2, imp_finsts = finsts2 })
557   = ImportAvails { imp_mods     = mods1  `plusModuleEnv` mods2, 
558                    imp_dep_mods = plusUFM_C plus_mod_dep dmods1 dmods2, 
559                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
560                    imp_orphs    = orphs1 `unionLists` orphs2,
561                    imp_finsts   = finsts1 `unionLists` finsts2 }
562   where
563     plus_mod_dep (m1, boot1) (m2, boot2) 
564         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
565                 -- Check mod-names match
566           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
567 \end{code}
568
569 %************************************************************************
570 %*                                                                      *
571 \subsection{Where from}
572 %*                                                                      *
573 %************************************************************************
574
575 The @WhereFrom@ type controls where the renamer looks for an interface file
576
577 \begin{code}
578 data WhereFrom 
579   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
580   | ImportBySystem                      -- Non user import.
581
582 instance Outputable WhereFrom where
583   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
584                              | otherwise   = empty
585   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
586 \end{code}
587
588
589 %************************************************************************
590 %*                                                                      *
591 \subsection[Inst-types]{@Inst@ types}
592 %*                                                                      *
593 v%************************************************************************
594
595 An @Inst@ is either a dictionary, an instance of an overloaded
596 literal, or an instance of an overloaded value.  We call the latter a
597 ``method'' even though it may not correspond to a class operation.
598 For example, we might have an instance of the @double@ function at
599 type Int, represented by
600
601         Method 34 doubleId [Int] origin
602
603 \begin{code}
604 data Inst
605   = Dict {
606         tci_name :: Name,
607         tci_pred :: TcPredType,
608         tci_loc  :: InstLoc 
609     }
610
611   | ImplicInst {        -- An implication constraint
612                         -- forall tvs. (reft, given) => wanted
613         tci_name   :: Name,
614         tci_tyvars :: [TcTyVar],    -- Quantified type variables
615                                     -- Includes coercion variables
616                                     --   mentioned in tci_reft
617         tci_reft   :: Refinement,
618         tci_given  :: [Inst],       -- Only Dicts
619                                     --   (no Methods, LitInsts, ImplicInsts)
620         tci_wanted :: [Inst],       -- Only Dicts and ImplicInsts
621                                     --   (no Methods or LitInsts)
622
623         tci_loc    :: InstLoc
624     }
625         -- NB: the tci_given are not necessarily rigid,
626         --     although they will be if the tci_reft is non-trivial
627         -- NB: the tci_reft is already applied to tci_given and tci_wanted
628
629   | Method {
630         tci_id :: TcId,         -- The Id for the Inst
631
632         tci_oid :: TcId,        -- The overloaded function
633                 -- This function will be a global, local, or ClassOpId;
634                 --   inside instance decls (only) it can also be an InstId!
635                 -- The id needn't be completely polymorphic.
636                 -- You'll probably find its name (for documentation purposes)
637                 --        inside the InstOrigin
638
639         tci_tys :: [TcType],    -- The types to which its polymorphic tyvars
640                                 --      should be instantiated.
641                                 -- These types must saturate the Id's foralls.
642
643         tci_theta :: TcThetaType,       
644                         -- The (types of the) dictionaries to which the function
645                         -- must be applied to get the method
646
647         tci_loc :: InstLoc 
648     }
649         -- INVARIANT 1: in (Method m f tys theta tau loc)
650         --      type of m = type of (f tys dicts(from theta))
651
652         -- INVARIANT 2: type of m must not be of form (Pred -> Tau)
653         --   Reason: two methods are considered equal if the 
654         --           base Id matches, and the instantiating types
655         --           match.  The TcThetaType should then match too.
656         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
657
658   | LitInst {
659         tci_name :: Name,
660         tci_lit  :: HsOverLit Name,     -- The literal from the occurrence site
661                         -- INVARIANT: never a rebindable-syntax literal
662                         -- Reason: tcSyntaxName does unification, and we
663                         --         don't want to deal with that during tcSimplify,
664                         --         when resolving LitInsts
665
666         tci_ty :: TcType,       -- The type at which the literal is used
667         tci_loc :: InstLoc
668     }
669 \end{code}
670
671 @Insts@ are ordered by their class/type info, rather than by their
672 unique.  This allows the context-reduction mechanism to use standard finite
673 maps to do their stuff.  It's horrible that this code is here, rather
674 than with the Avails handling stuff in TcSimplify
675
676 \begin{code}
677 instance Ord Inst where
678   compare = cmpInst
679
680 instance Eq Inst where
681   (==) i1 i2 = case i1 `cmpInst` i2 of
682                  EQ    -> True
683                  other -> False
684
685 cmpInst d1@(Dict {})    d2@(Dict {})    = tci_pred d1 `tcCmpPred` tci_pred d2
686 cmpInst (Dict {})       other           = LT
687
688 cmpInst (Method {})     (Dict {})       = GT
689 cmpInst m1@(Method {})  m2@(Method {})  = (tci_oid m1 `compare` tci_oid m2) `thenCmp`
690                                           (tci_tys m1 `tcCmpTypes` tci_tys m2)
691 cmpInst (Method {})     other           = LT
692
693 cmpInst (LitInst {})    (Dict {})       = GT
694 cmpInst (LitInst {})    (Method {})     = GT
695 cmpInst l1@(LitInst {}) l2@(LitInst {}) = (tci_lit l1 `compare` tci_lit l2) `thenCmp`
696                                           (tci_ty l1 `tcCmpType` tci_ty l2)
697 cmpInst (LitInst {})    other           = LT
698
699         -- Implication constraints are compared by *name*
700         -- not by type; that is, we make no attempt to do CSE on them
701 cmpInst (ImplicInst {})    (Dict {})          = GT
702 cmpInst (ImplicInst {})    (Method {})        = GT
703 cmpInst (ImplicInst {})    (LitInst {})       = GT
704 cmpInst i1@(ImplicInst {}) i2@(ImplicInst {}) = tci_name i1 `compare` tci_name i2
705 \end{code}
706
707
708 %************************************************************************
709 %*                                                                      *
710 \subsection[Inst-collections]{LIE: a collection of Insts}
711 %*                                                                      *
712 %************************************************************************
713
714 \begin{code}
715 -- FIXME: Rename this. It clashes with (Located (IE ...))
716 type LIE = Bag Inst
717
718 isEmptyLIE        = isEmptyBag
719 emptyLIE          = emptyBag
720 unitLIE inst      = unitBag inst
721 mkLIE insts       = listToBag insts
722 plusLIE lie1 lie2 = lie1 `unionBags` lie2
723 plusLIEs lies     = unionManyBags lies
724 lieToList         = bagToList
725 listToLIE         = listToBag
726
727 consLIE inst lie  = lie `snocBag` inst
728 -- Putting the new Inst at the *end* of the bag is a half-hearted attempt
729 -- to ensure that we tend to report the *leftmost* type-constraint error
730 -- E.g.         f :: [a]
731 --              f = [1,2,3]
732 -- we'd like to complain about the '1', not the '3'.
733 --
734 -- "Half-hearted" because the rest of the type checker makes no great
735 -- claims for retaining order in the constraint set.  Still, this 
736 -- seems to improve matters slightly.  Exampes: mdofail001, tcfail015
737 \end{code}
738
739
740 %************************************************************************
741 %*                                                                      *
742 \subsection[Inst-origin]{The @InstOrigin@ type}
743 %*                                                                      *
744 %************************************************************************
745
746 The @InstOrigin@ type gives information about where a dictionary came from.
747 This is important for decent error message reporting because dictionaries
748 don't appear in the original source code.  Doubtless this type will evolve...
749
750 It appears in TcMonad because there are a couple of error-message-generation
751 functions that deal with it.
752
753 \begin{code}
754 -------------------------------------------
755 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
756
757 instLoc :: Inst -> InstLoc
758 instLoc inst = tci_loc inst
759
760 instSpan :: Inst -> SrcSpan
761 instSpan wanted = instLocSpan (instLoc wanted)
762
763 instLocSpan :: InstLoc -> SrcSpan
764 instLocSpan (InstLoc _ s _) = s
765
766 instLocOrigin :: InstLoc -> InstOrigin
767 instLocOrigin (InstLoc o _ _) = o
768
769 pprInstArising :: Inst -> SDoc
770 pprInstArising loc = ptext SLIT("arising from") <+> pprInstLoc (tci_loc loc)
771
772 pprInstLoc :: InstLoc -> SDoc
773 pprInstLoc (InstLoc orig span _) = sep [ppr orig, text "at" <+> ppr span]
774
775 -------------------------------------------
776 data InstOrigin
777   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
778                                 -- Places that bind type variables and introduce
779                                 -- available constraints
780
781   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
782
783         -------------------------------------------------------
784         -- The rest are all occurrences: Insts that are 'wanted'
785         -------------------------------------------------------
786   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
787
788   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
789
790   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
791
792   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
793   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
794
795   | InstSigOrigin       -- A dict occurrence arising from instantiating
796                         -- a polymorphic type during a subsumption check
797
798   | RecordUpdOrigin
799   | InstScOrigin        -- Typechecking superclasses of an instance declaration
800   | DerivOrigin         -- Typechecking deriving
801   | StandAloneDerivOrigin -- Typechecking stand-alone deriving
802   | DefaultOrigin       -- Typechecking a default decl
803   | DoOrigin            -- Arising from a do expression
804   | ProcOrigin          -- Arising from a proc expression
805   | ImplicOrigin SDoc   -- An implication constraint
806
807 instance Outputable InstOrigin where
808     ppr (OccurrenceOf name)   = hsep [ptext SLIT("a use of"), quotes (ppr name)]
809     ppr (IPOccOrigin name)    = hsep [ptext SLIT("a use of implicit parameter"), quotes (ppr name)]
810     ppr (IPBindOrigin name)   = hsep [ptext SLIT("a binding for implicit parameter"), quotes (ppr name)]
811     ppr RecordUpdOrigin       = ptext SLIT("a record update")
812     ppr (LiteralOrigin lit)   = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
813     ppr (ArithSeqOrigin seq)  = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
814     ppr (PArrSeqOrigin seq)   = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
815     ppr InstSigOrigin         = ptext SLIT("instantiating a type signature")
816     ppr InstScOrigin          = ptext SLIT("the superclasses of an instance declaration")
817     ppr DerivOrigin           = ptext SLIT("the 'deriving' clause of a data type declaration")
818     ppr StandAloneDerivOrigin = ptext SLIT("a 'deriving' declaration")
819     ppr DefaultOrigin         = ptext SLIT("a 'default' declaration")
820     ppr DoOrigin              = ptext SLIT("a do statement")
821     ppr ProcOrigin            = ptext SLIT("a proc expression")
822     ppr (ImplicOrigin doc)    = doc
823     ppr (SigOrigin info)      = pprSkolInfo info
824 \end{code}