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