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