[project @ 2005-04-27 11:15:15 by simonmar]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcRnTypes.lhs
1 %
2 % (c) The GRASP Project, Glasgow University, 1992-2002
3 %
4 \begin{code}
5 module TcRnTypes(
6         TcRnIf, TcRn, TcM, RnM, IfM, IfL, IfG, -- The monad is opaque outside this module
7         TcRef,
8
9         -- The environment types
10         Env(..), 
11         TcGblEnv(..), TcLclEnv(..), 
12         IfGblEnv(..), IfLclEnv(..), 
13
14         -- Ranamer types
15         ErrCtxt,
16         ImportAvails(..), emptyImportAvails, plusImportAvails, 
17         plusAvail, pruneAvails,  
18         AvailEnv, emptyAvailEnv, unitAvailEnv, plusAvailEnv, 
19         mkAvailEnv, lookupAvailEnv, lookupAvailEnv_maybe, availEnvElts, addAvail,
20         WhereFrom(..), mkModDeps,
21
22         -- Typechecker types
23         TcTyThing(..), pprTcTyThingCategory, GadtRefinement,
24
25         -- Template Haskell
26         ThStage(..), topStage, topSpliceStage,
27         ThLevel, impLevel, topLevel,
28
29         -- Insts
30         Inst(..), InstOrigin(..), InstLoc(..), pprInstLoc, 
31         instLocSrcLoc, instLocSrcSpan,
32         LIE, emptyLIE, unitLIE, plusLIE, consLIE, 
33         plusLIEs, mkLIE, isEmptyLIE, lieToList, listToLIE,
34
35         -- Misc other types
36         TcId, TcIdSet, TcDictBinds
37   ) where
38
39 #include "HsVersions.h"
40
41 import HsSyn            ( PendingSplice, HsOverLit, LRuleDecl, LForeignDecl,
42                           ArithSeqInfo, DictBinds, LHsBinds, HsGroup )
43 import HscTypes         ( FixityEnv,
44                           HscEnv, TypeEnv, TyThing, 
45                           GenAvailInfo(..), AvailInfo, HscSource(..),
46                           availName, IsBootInterface, Deprecations )
47 import Packages         ( PackageId )
48 import Type             ( Type, TvSubstEnv, pprParendType, pprTyThingCategory )
49 import TcType           ( TcTyVarSet, TcType, TcTauType, TcThetaType, SkolemInfo,
50                           TcPredType, TcKind, tcCmpPred, tcCmpType, tcCmpTypes, pprSkolInfo )
51 import InstEnv          ( DFunId, InstEnv )
52 import IOEnv
53 import RdrName          ( GlobalRdrEnv, LocalRdrEnv )
54 import Name             ( Name )
55 import NameEnv
56 import NameSet          ( NameSet, unionNameSets, DefUses )
57 import OccName          ( OccEnv )
58 import Var              ( Id, TyVar )
59 import VarEnv           ( TidyEnv )
60 import Module
61 import SrcLoc           ( SrcSpan, SrcLoc, srcSpanStart )
62 import VarSet           ( IdSet )
63 import ErrUtils         ( Messages, Message )
64 import UniqSupply       ( UniqSupply )
65 import BasicTypes       ( IPName )
66 import Util             ( thenCmp )
67 import Bag
68 import Outputable
69 import Maybe            ( mapMaybe )
70 import ListSetOps       ( unionLists )
71 \end{code}
72
73
74 %************************************************************************
75 %*                                                                      *
76                Standard monad definition for TcRn
77     All the combinators for the monad can be found in TcRnMonad
78 %*                                                                      *
79 %************************************************************************
80
81 The monad itself has to be defined here, because it is mentioned by ErrCtxt
82
83 \begin{code}
84 type TcRef a     = IORef a
85 type TcId        = Id                   -- Type may be a TcType
86 type TcIdSet     = IdSet
87 type TcDictBinds = DictBinds TcId       -- Bag of dictionary bindings
88
89
90
91 type TcRnIf a b c = IOEnv (Env a b) c
92 type IfM lcl a  = TcRnIf IfGblEnv lcl a         -- Iface stuff
93 type IfG a  = IfM () a                          -- Top level
94 type IfL a  = IfM IfLclEnv a                    -- Nested
95 type TcRn a = TcRnIf TcGblEnv TcLclEnv a
96 type RnM  a = TcRn a            -- Historical
97 type TcM  a = TcRn a            -- Historical
98 \end{code}
99
100
101 %************************************************************************
102 %*                                                                      *
103                 The main environment types
104 %*                                                                      *
105 %************************************************************************
106
107 \begin{code}
108 data Env gbl lcl        -- Changes as we move into an expression
109   = Env {
110         env_top  :: HscEnv,     -- Top-level stuff that never changes
111                                 -- Includes all info about imported things
112
113         env_us   :: TcRef UniqSupply,   -- Unique supply for local varibles
114
115         env_gbl  :: gbl,        -- Info about things defined at the top level
116                                 -- of the module being compiled
117
118         env_lcl  :: lcl         -- Nested stuff; changes as we go into 
119                                 -- an expression
120     }
121
122 -- TcGblEnv describes the top-level of the module at the 
123 -- point at which the typechecker is finished work.
124 -- It is this structure that is handed on to the desugarer
125
126 data TcGblEnv
127   = TcGblEnv {
128         tcg_mod     :: Module,          -- Module being compiled
129         tcg_src     :: HscSource,       -- What kind of module 
130                                         -- (regular Haskell, hs-boot, ext-core)
131
132         tcg_rdr_env :: GlobalRdrEnv,    -- Top level envt; used during renaming
133         tcg_default :: Maybe [Type],    -- Types used for defaulting
134                                         -- Nothing => no 'default' decl
135
136         tcg_fix_env  :: FixityEnv,      -- Just for things in this module
137
138         tcg_type_env :: TypeEnv,        -- Global type env for the module we are compiling now
139                 -- All TyCons and Classes (for this module) end up in here right away,
140                 -- along with their derived constructors, selectors.
141                 --
142                 -- (Ids defined in this module start in the local envt, 
143                 --  though they move to the global envt during zonking)
144
145         tcg_type_env_var :: TcRef TypeEnv,      
146                 -- Used only to initialise the interface-file
147                 -- typechecker in initIfaceTcRn, so that it can see stuff
148                 -- bound in this module when dealing with hi-boot recursions
149                 -- Updated at intervals (e.g. after dealing with types and classes)
150         
151         tcg_inst_env :: InstEnv,        -- Instance envt for *home-package* modules
152                                         -- Includes the dfuns in tcg_insts
153                 -- Now a bunch of things about this module that are simply 
154                 -- accumulated, but never consulted until the end.  
155                 -- Nevertheless, it's convenient to accumulate them along 
156                 -- with the rest of the info from this module.
157         tcg_exports :: NameSet,         -- What is exported
158         tcg_imports :: ImportAvails,    -- Information about what was imported 
159                                         --    from where, including things bound
160                                         --    in this module
161
162         tcg_dus :: DefUses,     -- What is defined in this module and what is used.
163                                 -- The latter is used to generate 
164                                 --      (a) version tracking; no need to recompile if these
165                                 --              things have not changed version stamp
166                                 --      (b) unused-import info
167
168         tcg_keep :: TcRef NameSet,      -- Locally-defined top-level names to keep alive
169                 -- "Keep alive" means give them an Exported flag, so
170                 -- that the simplifier does not discard them as dead 
171                 -- code, and so that they are exposed in the interface file
172                 -- (but not to export to the user).
173                 --
174                 -- Some things, like dict-fun Ids and default-method Ids are 
175                 -- "born" with the Exported flag on, for exactly the above reason,
176                 -- but some we only discover as we go.  Specifically:
177                 --      * The to/from functions for generic data types
178                 --      * Top-level variables appearing free in the RHS of an orphan rule
179                 --      * Top-level variables appearing free in a TH bracket
180
181         tcg_inst_uses :: TcRef NameSet, -- Home-package Dfuns actually used 
182                 -- Used to generate version dependencies
183                 -- This records usages, rather like tcg_dus, but it has to
184                 -- be a mutable variable so it can be augmented 
185                 -- when we look up an instance.  These uses of dfuns are
186                 -- rather like the free variables of the program, but
187                 -- are implicit instead of explicit.
188
189         tcg_th_used :: TcRef Bool,      -- True <=> Template Haskell syntax used
190                 -- We need this so that we can generate a dependency on the
191                 -- Template Haskell package, becuase the desugarer is going to
192                 -- emit loads of references to TH symbols.  It's rather like 
193                 -- tcg_inst_uses; the reference is implicit rather than explicit,
194                 -- so we have to zap a mutable variable.
195
196                 -- The next fields accumulate the payload of the
197                 -- module The binds, rules and foreign-decl fiels are
198                 -- collected initially in un-zonked form and are
199                 -- finally zonked in tcRnSrcDecls
200
201         tcg_rn_decls :: Maybe (HsGroup Name),   -- renamed decls, maybe
202                 -- Nothing <=> Don't retain renamed decls
203
204         tcg_binds   :: LHsBinds Id,             -- Value bindings in this module
205         tcg_deprecs :: Deprecations,            -- ...Deprecations 
206         tcg_insts   :: [DFunId],                -- ...Instances
207         tcg_rules   :: [LRuleDecl Id],          -- ...Rules
208         tcg_fords   :: [LForeignDecl Id]        -- ...Foreign import & exports
209     }
210 \end{code}
211
212 %************************************************************************
213 %*                                                                      *
214                 The interface environments
215               Used when dealing with IfaceDecls
216 %*                                                                      *
217 %************************************************************************
218
219 \begin{code}
220 data IfGblEnv 
221   = IfGblEnv {
222         -- The type environment for the module being compiled,
223         -- in case the interface refers back to it via a reference that
224         -- was originally a hi-boot file.
225         -- We need the module name so we can test when it's appropriate
226         -- to look in this env.
227         if_rec_types :: Maybe (Module, IfG TypeEnv)
228                 -- Allows a read effect, so it can be in a mutable
229                 -- variable; c.f. handling the external package type env
230                 -- Nothing => interactive stuff, no loops possible
231     }
232
233 data IfLclEnv
234   = IfLclEnv {
235         -- The module for the current IfaceDecl
236         -- So if we see   f = \x -> x
237         -- it means M.f = \x -> x, where M is the if_mod
238         if_mod :: Module,
239
240         -- The field is used only for error reporting
241         -- if (say) there's a Lint error in it
242         if_loc :: SDoc,
243                 -- Where the interface came from:
244                 --      .hi file, or GHCi state, or ext core
245                 -- plus which bit is currently being examined
246
247         if_tv_env  :: OccEnv TyVar,     -- Nested tyvar bindings
248         if_id_env  :: OccEnv Id         -- Nested id binding
249     }
250 \end{code}
251
252
253 %************************************************************************
254 %*                                                                      *
255                 The local typechecker environment
256 %*                                                                      *
257 %************************************************************************
258
259 The Global-Env/Local-Env story
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261 During type checking, we keep in the tcg_type_env
262         * All types and classes
263         * All Ids derived from types and classes (constructors, selectors)
264
265 At the end of type checking, we zonk the local bindings,
266 and as we do so we add to the tcg_type_env
267         * Locally defined top-level Ids
268
269 Why?  Because they are now Ids not TcIds.  This final GlobalEnv is
270         a) fed back (via the knot) to typechecking the 
271            unfoldings of interface signatures
272         b) used in the ModDetails of this module
273
274 \begin{code}
275 data TcLclEnv           -- Changes as we move inside an expression
276                         -- Discarded after typecheck/rename; not passed on to desugarer
277   = TcLclEnv {
278         tcl_loc  :: SrcSpan,            -- Source span
279         tcl_ctxt :: ErrCtxt,            -- Error context
280         tcl_errs :: TcRef Messages,     -- Place to accumulate errors
281
282         tcl_th_ctxt    :: ThStage,      -- Template Haskell context
283
284         tcl_rdr :: LocalRdrEnv,         -- Local name envt
285                 -- Maintained during renaming, of course, but also during
286                 -- type checking, solely so that when renaming a Template-Haskell
287                 -- splice we have the right environment for the renamer.
288                 -- 
289                 --   Does *not* include global name envt; may shadow it
290                 --   Includes both ordinary variables and type variables;
291                 --   they are kept distinct because tyvar have a different
292                 --   occurrence contructor (Name.TvOcc)
293                 -- We still need the unsullied global name env so that
294                 --   we can look up record field names
295
296         tcl_env  :: NameEnv TcTyThing,  -- The local type environment: Ids and TyVars
297                                         -- defined in this module
298                                         
299         tcl_tyvars :: TcRef TcTyVarSet, -- The "global tyvars"
300                         -- Namely, the in-scope TyVars bound in tcl_env, 
301                         -- plus the tyvars mentioned in the types of Ids bound in tcl_lenv
302                         -- Why mutable? see notes with tcGetGlobalTyVars
303
304         tcl_lie   :: TcRef LIE,         -- Place to accumulate type constraints
305         tcl_gadt  :: GadtRefinement     -- The current type refinement for GADTs
306
307 -----------------------------------------------------------
308 -- Not yet; it's a new complication and I want to see whether it bites
309 --      tcl_given :: [Inst]             -- Insts available in the current context (see Note [Given Insts])
310 -----------------------------------------------------------
311     }
312
313 type GadtRefinement = TvSubstEnv        -- Binds rigid type variables to their refinements
314
315 {- Note [Given Insts]
316    ~~~~~~~~~~~~~~~~~~
317 Because of GADTs, we have to pass inwards the Insts provided by type signatures 
318 and existential contexts. Consider
319         data T a where { T1 :: b -> b -> T [b] }
320         f :: Eq a => T a -> Bool
321         f (T1 x y) = [x]==[y]
322
323 The constructor T1 binds an existential variable 'b', and we need Eq [b].
324 Well, we have it, because Eq a refines to Eq [b], but we can only spot that if we 
325 pass it inwards.
326
327 -}
328
329 ---------------------------
330 -- Template Haskell levels 
331 ---------------------------
332
333 type ThLevel = Int      
334         -- Indicates how many levels of brackets we are inside
335         --      (always >= 0)
336         -- Incremented when going inside a bracket,
337         -- decremented when going inside a splice
338
339 impLevel, topLevel :: ThLevel
340 topLevel = 1    -- Things defined at top level of this module
341 impLevel = 0    -- Imported things; they can be used inside a top level splice
342 --
343 -- For example: 
344 --      f = ...
345 --      g1 = $(map ...)         is OK
346 --      g2 = $(f ...)           is not OK; because we havn't compiled f yet
347
348
349 data ThStage
350   = Comp                                -- Ordinary compiling, at level topLevel
351   | Splice ThLevel                      -- Inside a splice
352   | Brack  ThLevel                      -- Inside brackets; 
353            (TcRef [PendingSplice])      --   accumulate pending splices here
354            (TcRef LIE)                  --   and type constraints here
355 topStage, topSpliceStage :: ThStage
356 topStage       = Comp
357 topSpliceStage = Splice (topLevel - 1)  -- Stage for the body of a top-level splice
358
359
360 ---------------------------
361 -- TcTyThing
362 ---------------------------
363
364 data TcTyThing
365   = AGlobal TyThing                     -- Used only in the return type of a lookup
366
367   | ATcId   TcId ThLevel                -- Ids defined in this module; may not be fully zonked
368
369   | ATyVar  Name TcType                 -- Type variables; tv -> type.  It can't just be a TyVar
370                                         -- that is mutated to point to the type it is bound to,
371                                         -- because that would make it a wobbly type, and we
372                                         -- want pattern-bound lexically-scoped type variables to
373                                         -- be able to stand for rigid types
374
375   | AThing  TcKind                      -- Used temporarily, during kind checking, for the
376                                         --      tycons and clases in this recursive group
377
378 instance Outputable TcTyThing where     -- Debugging only
379    ppr (AGlobal g)      = ppr g
380    ppr (ATcId g tl)     = text "Identifier" <> 
381                           ifPprDebug (brackets (ppr g <> comma <> ppr tl))
382    ppr (ATyVar tv ty)   = text "Type variable" <+> quotes (ppr tv) <+> pprParendType ty
383    ppr (AThing k)       = text "AThing" <+> ppr k
384
385 pprTcTyThingCategory :: TcTyThing -> SDoc
386 pprTcTyThingCategory (AGlobal thing) = pprTyThingCategory thing
387 pprTcTyThingCategory (ATyVar _ _)    = ptext SLIT("Type variable")
388 pprTcTyThingCategory (ATcId _ _)     = ptext SLIT("Local identifier")
389 pprTcTyThingCategory (AThing _)      = ptext SLIT("Kinded thing")
390 \end{code}
391
392 \begin{code}
393 type ErrCtxt = [TidyEnv -> TcM (TidyEnv, Message)]      
394                         -- Innermost first.  Monadic so that we have a chance
395                         -- to deal with bound type variables just before error
396                         -- message construction
397 \end{code}
398
399
400 %************************************************************************
401 %*                                                                      *
402         Operations over ImportAvails
403 %*                                                                      *
404 %************************************************************************
405
406 ImportAvails summarises what was imported from where, irrespective
407 of whether the imported things are actually used or not
408 It is used      * when processing the export list
409                 * when constructing usage info for the inteface file
410                 * to identify the list of directly imported modules
411                         for initialisation purposes
412                 * when figuring out what things are really unused
413
414 \begin{code}
415 data ImportAvails 
416    = ImportAvails {
417         imp_env :: ModuleEnv NameSet,
418                 -- All the things imported, classified by 
419                 -- the *module qualifier* for its import
420                 --   e.g.        import List as Foo
421                 -- would add a binding Foo |-> ...stuff from List...
422                 -- to imp_env.
423                 -- 
424                 -- We need to classify them like this so that we can figure out 
425                 -- "module M" export specifiers in an export list 
426                 -- (see 1.4 Report Section 5.1.1).  Ultimately, we want to find 
427                 -- everything that is unambiguously in scope as 'M.x'
428                 -- and where plain 'x' is (perhaps ambiguously) in scope.
429                 -- So the starting point is all things that are in scope as 'M.x',
430                 -- which is what this field tells us.
431
432         imp_mods :: ModuleEnv (Module, Maybe Bool, SrcSpan),
433                 -- Domain is all directly-imported modules
434                 -- Maybe value answers the question "is the import restricted?"
435                 --   Nothing    => unrestricted import (e.g., "import Foo")
436                 --   Just True  => restricted import, at least one entity (e.g., "import Foo(x)")
437                 --   Just False => fully restricted import (e.g., "import Foo ()")
438                 --
439                 --  A distinction is made between the first and the third in order
440                 --  to more precisely emit warnings about unused imports.
441                 --
442                 -- We need the Module in the range because we can't get
443                 --      the keys of a ModuleEnv
444                 -- Used 
445                 --   (a) to help construct the usage information in 
446                 --       the interface file; if we import everything we
447                 --       need to recompile if the module version changes
448                 --   (b) to specify what child modules to initialise
449
450         imp_dep_mods :: ModuleEnv (Module, IsBootInterface),
451                 -- Home-package modules needed by the module being compiled
452                 --
453                 -- It doesn't matter whether any of these dependencies
454                 -- are actually *used* when compiling the module; they
455                 -- are listed if they are below it at all.  For
456                 -- example, suppose M imports A which imports X.  Then
457                 -- compiling M might not need to consult X.hi, but X
458                 -- is still listed in M's dependencies.
459
460         imp_dep_pkgs :: [PackageId],
461                 -- Packages needed by the module being compiled, whether
462                 -- directly, or via other modules in this package, or via
463                 -- modules imported from other packages.
464
465         imp_orphs :: [Module]
466                 -- Orphan modules below us in the import tree
467       }
468
469 mkModDeps :: [(Module, IsBootInterface)]
470           -> ModuleEnv (Module, IsBootInterface)
471 mkModDeps deps = foldl add emptyModuleEnv deps
472                where
473                  add env elt@(m,_) = extendModuleEnv env m elt
474
475 emptyImportAvails :: ImportAvails
476 emptyImportAvails = ImportAvails { imp_env      = emptyModuleEnv, 
477                                    imp_mods     = emptyModuleEnv,
478                                    imp_dep_mods = emptyModuleEnv,
479                                    imp_dep_pkgs = [],
480                                    imp_orphs    = [] }
481
482 plusImportAvails ::  ImportAvails ->  ImportAvails ->  ImportAvails
483 plusImportAvails
484   (ImportAvails { imp_env = env1, imp_mods = mods1,
485                   imp_dep_mods = dmods1, imp_dep_pkgs = dpkgs1, imp_orphs = orphs1 })
486   (ImportAvails { imp_env = env2, imp_mods = mods2,
487                   imp_dep_mods = dmods2, imp_dep_pkgs = dpkgs2, imp_orphs = orphs2 })
488   = ImportAvails { imp_env      = plusModuleEnv_C unionNameSets env1 env2, 
489                    imp_mods     = mods1  `plusModuleEnv` mods2, 
490                    imp_dep_mods = plusModuleEnv_C plus_mod_dep dmods1 dmods2,   
491                    imp_dep_pkgs = dpkgs1 `unionLists` dpkgs2,
492                    imp_orphs    = orphs1 `unionLists` orphs2 }
493   where
494     plus_mod_dep (m1, boot1) (m2, boot2) 
495         = WARN( not (m1 == m2), (ppr m1 <+> ppr m2) $$ (ppr boot1 <+> ppr boot2) )
496                 -- Check mod-names match
497           (m1, boot1 && boot2)  -- If either side can "see" a non-hi-boot interface, use that
498 \end{code}
499
500 %************************************************************************
501 %*                                                                      *
502         Avails, AvailEnv, etc
503 %*                                                                      *
504 v%************************************************************************
505
506 \begin{code}
507 plusAvail (Avail n1)       (Avail n2)       = Avail n1
508 plusAvail (AvailTC n1 ns1) (AvailTC n2 ns2) = AvailTC n2 (ns1 `unionLists` ns2)
509 -- Added SOF 4/97
510 #ifdef DEBUG
511 plusAvail a1 a2 = pprPanic "RnEnv.plusAvail" (hsep [ppr a1,ppr a2])
512 #endif
513
514 -------------------------
515 pruneAvails :: (Name -> Bool)   -- Keep if this is True
516             -> [AvailInfo]
517             -> [AvailInfo]
518 pruneAvails keep avails
519   = mapMaybe del avails
520   where
521     del :: AvailInfo -> Maybe AvailInfo -- Nothing => nothing left!
522     del (Avail n) | keep n    = Just (Avail n)
523                   | otherwise = Nothing
524     del (AvailTC n ns) | null ns'  = Nothing
525                        | otherwise = Just (AvailTC n ns')
526                        where
527                          ns' = filter keep ns
528 \end{code}
529
530 ---------------------------------------
531         AvailEnv and friends
532 ---------------------------------------
533
534 \begin{code}
535 type AvailEnv = NameEnv AvailInfo       -- Maps a Name to the AvailInfo that contains it
536
537 emptyAvailEnv :: AvailEnv
538 emptyAvailEnv = emptyNameEnv
539
540 unitAvailEnv :: AvailInfo -> AvailEnv
541 unitAvailEnv a = unitNameEnv (availName a) a
542
543 plusAvailEnv :: AvailEnv -> AvailEnv -> AvailEnv
544 plusAvailEnv = plusNameEnv_C plusAvail
545
546 lookupAvailEnv_maybe :: AvailEnv -> Name -> Maybe AvailInfo
547 lookupAvailEnv_maybe = lookupNameEnv
548
549 lookupAvailEnv :: AvailEnv -> Name -> AvailInfo
550 lookupAvailEnv env n = case lookupNameEnv env n of
551                          Just avail -> avail
552                          Nothing    -> pprPanic "lookupAvailEnv" (ppr n)
553
554 availEnvElts = nameEnvElts
555
556 addAvail :: AvailEnv -> AvailInfo -> AvailEnv
557 addAvail avails avail = extendNameEnv_C plusAvail avails (availName avail) avail
558
559 mkAvailEnv :: [AvailInfo] -> AvailEnv
560         -- 'avails' may have several items with the same availName
561         -- E.g  import Ix( Ix(..), index )
562         -- will give Ix(Ix,index,range) and Ix(index)
563         -- We want to combine these; addAvail does that
564 mkAvailEnv avails = foldl addAvail emptyAvailEnv avails
565 \end{code}
566
567 %************************************************************************
568 %*                                                                      *
569 \subsection{Where from}
570 %*                                                                      *
571 %************************************************************************
572
573 The @WhereFrom@ type controls where the renamer looks for an interface file
574
575 \begin{code}
576 data WhereFrom 
577   = ImportByUser IsBootInterface        -- Ordinary user import (perhaps {-# SOURCE #-})
578   | ImportBySystem                      -- Non user import.
579
580 instance Outputable WhereFrom where
581   ppr (ImportByUser is_boot) | is_boot     = ptext SLIT("{- SOURCE -}")
582                              | otherwise   = empty
583   ppr ImportBySystem                       = ptext SLIT("{- SYSTEM -}")
584 \end{code}
585
586
587 %************************************************************************
588 %*                                                                      *
589 \subsection[Inst-types]{@Inst@ types}
590 %*                                                                      *
591 v%************************************************************************
592
593 An @Inst@ is either a dictionary, an instance of an overloaded
594 literal, or an instance of an overloaded value.  We call the latter a
595 ``method'' even though it may not correspond to a class operation.
596 For example, we might have an instance of the @double@ function at
597 type Int, represented by
598
599         Method 34 doubleId [Int] origin
600
601 \begin{code}
602 data Inst
603   = Dict
604         Name
605         TcPredType
606         InstLoc
607
608   | Method
609         Id
610
611         TcId    -- The overloaded function
612                         -- This function will be a global, local, or ClassOpId;
613                         --   inside instance decls (only) it can also be an InstId!
614                         -- The id needn't be completely polymorphic.
615                         -- You'll probably find its name (for documentation purposes)
616                         --        inside the InstOrigin
617
618         [TcType]        -- The types to which its polymorphic tyvars
619                         --      should be instantiated.
620                         -- These types must saturate the Id's foralls.
621
622         TcThetaType     -- The (types of the) dictionaries to which the function
623                         -- must be applied to get the method
624
625         TcTauType       -- The tau-type of the method
626
627         InstLoc
628
629         -- INVARIANT 1: in (Method u f tys theta tau loc)
630         --      type of (f tys dicts(from theta)) = tau
631
632         -- INVARIANT 2: tau must not be of form (Pred -> Tau)
633         --   Reason: two methods are considered equal if the 
634         --           base Id matches, and the instantiating types
635         --           match.  The TcThetaType should then match too.
636         --   This only bites in the call to tcInstClassOp in TcClassDcl.mkMethodBind
637
638   | LitInst
639         Name
640         (HsOverLit Name)        -- The literal from the occurrence site
641                                 -- INVARIANT: never a rebindable-syntax literal
642                                 -- Reason: tcSyntaxName does unification, and we
643                                 --         don't want to deal with that during tcSimplify,
644                                 --         when resolving LitInsts
645         TcType          -- The type at which the literal is used
646         InstLoc
647 \end{code}
648
649 @Insts@ are ordered by their class/type info, rather than by their
650 unique.  This allows the context-reduction mechanism to use standard finite
651 maps to do their stuff.
652
653 \begin{code}
654 instance Ord Inst where
655   compare = cmpInst
656
657 instance Eq Inst where
658   (==) i1 i2 = case i1 `cmpInst` i2 of
659                  EQ    -> True
660                  other -> False
661
662 cmpInst (Dict _ pred1 _)          (Dict _ pred2 _)          = pred1 `tcCmpPred` pred2
663 cmpInst (Dict _ _ _)              other                     = LT
664
665 cmpInst (Method _ _ _ _ _ _)      (Dict _ _ _)              = GT
666 cmpInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _) = (id1 `compare` id2) `thenCmp` (tys1 `tcCmpTypes` tys2)
667 cmpInst (Method _ _ _ _ _ _)      other                     = LT
668
669 cmpInst (LitInst _ _ _ _)         (Dict _ _ _)              = GT
670 cmpInst (LitInst _ _ _ _)         (Method _ _ _ _ _ _)      = GT
671 cmpInst (LitInst _ lit1 ty1 _)    (LitInst _ lit2 ty2 _)    = (lit1 `compare` lit2) `thenCmp` (ty1 `tcCmpType` ty2)
672 \end{code}
673
674
675 %************************************************************************
676 %*                                                                      *
677 \subsection[Inst-collections]{LIE: a collection of Insts}
678 %*                                                                      *
679 %************************************************************************
680
681 \begin{code}
682 type LIE = Bag Inst
683
684 isEmptyLIE        = isEmptyBag
685 emptyLIE          = emptyBag
686 unitLIE inst      = unitBag inst
687 mkLIE insts       = listToBag insts
688 plusLIE lie1 lie2 = lie1 `unionBags` lie2
689 consLIE inst lie  = inst `consBag` lie
690 plusLIEs lies     = unionManyBags lies
691 lieToList         = bagToList
692 listToLIE         = listToBag
693 \end{code}
694
695
696 %************************************************************************
697 %*                                                                      *
698 \subsection[Inst-origin]{The @InstOrigin@ type}
699 %*                                                                      *
700 %************************************************************************
701
702 The @InstOrigin@ type gives information about where a dictionary came from.
703 This is important for decent error message reporting because dictionaries
704 don't appear in the original source code.  Doubtless this type will evolve...
705
706 It appears in TcMonad because there are a couple of error-message-generation
707 functions that deal with it.
708
709 \begin{code}
710 data InstLoc = InstLoc InstOrigin SrcSpan ErrCtxt
711
712 instLocSrcLoc :: InstLoc -> SrcLoc
713 instLocSrcLoc (InstLoc _ src_span _) = srcSpanStart src_span
714
715 instLocSrcSpan :: InstLoc -> SrcSpan
716 instLocSrcSpan (InstLoc _ src_span _) = src_span
717
718 data InstOrigin
719   = SigOrigin SkolemInfo        -- Pattern, class decl, inst decl etc;
720                                 -- Places that bind type variables and introduce
721                                 -- available constraints
722
723   | IPBindOrigin (IPName Name)  -- Binding site of an implicit parameter
724
725         -------------------------------------------------------
726         -- The rest are all occurrences: Insts that are 'wanted'
727         -------------------------------------------------------
728   | OccurrenceOf Name           -- Occurrence of an overloaded identifier
729
730   | IPOccOrigin  (IPName Name)  -- Occurrence of an implicit parameter
731
732   | LiteralOrigin (HsOverLit Name)      -- Occurrence of a literal
733
734   | ArithSeqOrigin (ArithSeqInfo Name) -- [x..], [x..y] etc
735   | PArrSeqOrigin  (ArithSeqInfo Name) -- [:x..y:] and [:x,y..z:]
736
737   | InstSigOrigin       -- A dict occurrence arising from instantiating
738                         -- a polymorphic type during a subsumption check
739
740   | RecordUpdOrigin
741   | InstScOrigin        -- Typechecking superclasses of an instance declaration
742   | DerivOrigin         -- Typechecking deriving
743   | DefaultOrigin       -- Typechecking a default decl
744   | DoOrigin            -- Arising from a do expression
745   | ProcOrigin          -- Arising from a proc expression
746 \end{code}
747
748 \begin{code}
749 pprInstLoc :: InstLoc -> SDoc
750 pprInstLoc (InstLoc orig locn _)
751   = hsep [text "arising from", pp_orig orig, text "at", ppr locn]
752   where
753     pp_orig (OccurrenceOf name)  = hsep [ptext SLIT("use of"), quotes (ppr name)]
754     pp_orig (IPOccOrigin name)   = hsep [ptext SLIT("use of implicit parameter"), quotes (ppr name)]
755     pp_orig (IPBindOrigin name)  = hsep [ptext SLIT("binding for implicit parameter"), quotes (ppr name)]
756     pp_orig RecordUpdOrigin      = ptext SLIT("a record update")
757     pp_orig (LiteralOrigin lit)  = hsep [ptext SLIT("the literal"), quotes (ppr lit)]
758     pp_orig (ArithSeqOrigin seq) = hsep [ptext SLIT("the arithmetic sequence"), quotes (ppr seq)]
759     pp_orig (PArrSeqOrigin seq)  = hsep [ptext SLIT("the parallel array sequence"), quotes (ppr seq)]
760     pp_orig InstSigOrigin        = ptext SLIT("instantiating a type signature")
761     pp_orig InstScOrigin         = ptext SLIT("the superclasses of an instance declaration")
762     pp_orig DerivOrigin          = ptext SLIT("the 'deriving' clause of a data type declaration")
763     pp_orig DefaultOrigin        = ptext SLIT("a 'default' declaration")
764     pp_orig DoOrigin             = ptext SLIT("a do statement")
765     pp_orig ProcOrigin           = ptext SLIT("a proc expression")
766     pp_orig (SigOrigin info)     = pprSkolInfo info
767 \end{code}