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