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