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