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