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