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