[project @ 1997-06-18 23:52:36 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / Inst.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
3 %
4 \section[Inst]{The @Inst@ type: dictionaries or method instances}
5
6 \begin{code}
7 #include "HsVersions.h"
8
9 module Inst (
10         Inst(..),       -- Visible only to TcSimplify
11
12         InstOrigin(..), OverloadedLit(..),
13         SYN_IE(LIE), emptyLIE, unitLIE, plusLIE, consLIE, zonkLIE, plusLIEs,
14
15         SYN_IE(InstanceMapper),
16
17         newDicts, newDictsAtLoc, newMethod, newMethodWithGivenTy, newOverloadedLit,
18
19         instType, tyVarsOfInst, lookupInst, lookupSimpleInst,
20
21         isDict, isTyVarDict, 
22
23         zonkInst, instToId,
24
25         matchesInst,
26         instBindingRequired, instCanBeGeneralised,
27         
28         pprInst
29     ) where
30
31 IMP_Ubiq()
32 IMPORT_1_3(Ratio(Rational))
33
34 import HsSyn    ( HsLit(..), HsExpr(..), HsBinds, Fixity, MonoBinds(..),
35                   InPat, OutPat, Stmt, DoOrListComp, Match, GRHSsAndBinds,
36                   ArithSeqInfo, HsType, Fake )
37 import RnHsSyn  ( SYN_IE(RenamedArithSeqInfo), SYN_IE(RenamedHsExpr) )
38 import TcHsSyn  ( TcIdOcc(..), SYN_IE(TcExpr), SYN_IE(TcIdBndr), 
39                   SYN_IE(TcDictBinds), SYN_IE(TcMonoBinds),
40                   mkHsTyApp, mkHsDictApp, tcIdTyVars )
41
42 import TcMonad
43 import TcEnv    ( tcLookupGlobalValueByKey, tcLookupTyConByKey )
44 import TcType   ( SYN_IE(TcType), SYN_IE(TcRhoType), TcMaybe, SYN_IE(TcTyVarSet),
45                   tcInstType, zonkTcType, tcSplitForAllTy, tcSplitRhoTy )
46
47 import Bag      ( emptyBag, unitBag, unionBags, unionManyBags, 
48                   listToBag, consBag, Bag )
49 import Class    ( classInstEnv,
50                   SYN_IE(Class), GenClass, SYN_IE(ClassInstEnv), SYN_IE(ClassOp)
51                 )
52 import ErrUtils ( addErrLoc, SYN_IE(Error) )
53 import Id       ( GenId, idType, mkInstId, SYN_IE(Id) )
54 import PrelInfo ( isCcallishClass, isNoDictClass )
55 import MatchEnv ( lookupMEnv, insertMEnv )
56 import Name     ( OccName(..), Name, mkLocalName, 
57                   mkSysLocalName, occNameString, getOccName )
58 import Outputable
59 import PprType  ( GenClass, TyCon, GenType, GenTyVar, pprParendGenType )        
60 import Pretty
61 import SpecEnv  ( SpecEnv )
62 import SrcLoc   ( SrcLoc, noSrcLoc )
63 import Type     ( GenType, eqSimpleTy, instantiateTy,
64                   isTyVarTy, mkDictTy, splitForAllTy, splitSigmaTy,
65                   splitRhoTy, matchTy, tyVarsOfType, tyVarsOfTypes,
66                   mkSynTy, SYN_IE(Type)
67                 )
68 import TyVar    ( unionTyVarSets, GenTyVar )
69 import TysPrim    ( intPrimTy )
70 import TysWiredIn ( intDataCon, integerTy )
71 import Unique   ( showUnique, fromRationalClassOpKey, rationalTyConKey,
72                   fromIntClassOpKey, fromIntegerClassOpKey, Unique
73                 )
74 import Util     ( panic, zipEqual, zipWithEqual, assoc, assertPanic, pprTrace{-ToDo:rm-} )
75 #if __GLASGOW_HASKELL__ >= 202
76 import Maybes
77 #endif
78 \end{code}
79
80 %************************************************************************
81 %*                                                                      *
82 \subsection[Inst-collections]{LIE: a collection of Insts}
83 %*                                                                      *
84 %************************************************************************
85
86 \begin{code}
87 type LIE s = Bag (Inst s)
88
89 emptyLIE          = emptyBag
90 unitLIE inst      = unitBag inst
91 plusLIE lie1 lie2 = lie1 `unionBags` lie2
92 consLIE inst lie  = inst `consBag` lie
93 plusLIEs lies     = unionManyBags lies
94
95 zonkLIE :: LIE s -> NF_TcM s (LIE s)
96 zonkLIE lie = mapBagNF_Tc zonkInst lie
97 \end{code}
98
99 %************************************************************************
100 %*                                                                      *
101 \subsection[Inst-types]{@Inst@ types}
102 %*                                                                      *
103 %************************************************************************
104
105 An @Inst@ is either a dictionary, an instance of an overloaded
106 literal, or an instance of an overloaded value.  We call the latter a
107 ``method'' even though it may not correspond to a class operation.
108 For example, we might have an instance of the @double@ function at
109 type Int, represented by
110
111         Method 34 doubleId [Int] origin
112
113 \begin{code}
114 data Inst s
115   = Dict
116         Unique
117         Class           -- The type of the dict is (c t), where
118         (TcType s)      -- c is the class and t the type;
119         (InstOrigin s)
120         SrcLoc
121
122   | Method
123         Unique
124
125         (TcIdOcc s)     -- The overloaded function
126                         -- This function will be a global, local, or ClassOpId;
127                         --   inside instance decls (only) it can also be an InstId!
128                         -- The id needn't be completely polymorphic.
129                         -- You'll probably find its name (for documentation purposes)
130                         --        inside the InstOrigin
131
132         [TcType s]      -- The types to which its polymorphic tyvars
133                         --      should be instantiated.
134                         -- These types must saturate the Id's foralls.
135
136         (TcRhoType s)   -- Cached: (type-of-id applied to inst_tys)
137                         -- If this type is (theta => tau) then the type of the Method
138                         -- is tau, and the method can be built by saying 
139                         --      id inst_tys dicts
140                         -- where dicts are constructed from theta
141
142         (InstOrigin s)
143         SrcLoc
144
145   | LitInst
146         Unique
147         OverloadedLit
148         (TcType s)      -- The type at which the literal is used
149         (InstOrigin s)  -- Always a literal; but more convenient to carry this around
150         SrcLoc
151
152 data OverloadedLit
153   = OverloadedIntegral   Integer        -- The number
154   | OverloadedFractional Rational       -- The number
155
156 getInstOrigin (Dict   u clas ty     origin loc) = origin
157 getInstOrigin (Method u clas ty rho origin loc) = origin
158 getInstOrigin (LitInst u lit ty     origin loc) = origin
159 \end{code}
160
161 Construction
162 ~~~~~~~~~~~~
163
164 \begin{code}
165 newDicts :: InstOrigin s
166          -> [(Class, TcType s)]
167          -> NF_TcM s (LIE s, [TcIdOcc s])
168 newDicts orig theta
169   = tcGetSrcLoc                         `thenNF_Tc` \ loc ->
170     newDictsAtLoc orig loc theta        `thenNF_Tc` \ (dicts, ids) ->
171     returnNF_Tc (listToBag dicts, ids)
172 {-
173     tcGetUniques (length theta)         `thenNF_Tc` \ new_uniqs ->
174     let
175         mk_dict u (clas, ty) = Dict u clas ty orig loc
176         dicts = zipWithEqual "newDicts" mk_dict new_uniqs theta
177     in
178     returnNF_Tc (listToBag dicts, map instToId dicts)
179 -}
180
181 -- Local function, similar to newDicts, 
182 -- but with slightly different interface
183 newDictsAtLoc :: InstOrigin s
184               -> SrcLoc
185               -> [(Class, TcType s)]
186               -> NF_TcM s ([Inst s], [TcIdOcc s])
187 newDictsAtLoc orig loc theta =
188  tcGetUniques (length theta)            `thenNF_Tc` \ new_uniqs ->
189  let
190   mk_dict u (clas, ty) = Dict u clas ty orig loc
191   dicts = zipWithEqual "newDictsAtLoc" mk_dict new_uniqs theta
192  in
193  returnNF_Tc (dicts, map instToId dicts)
194
195 newMethod :: InstOrigin s
196           -> TcIdOcc s
197           -> [TcType s]
198           -> NF_TcM s (LIE s, TcIdOcc s)
199 newMethod orig id tys
200   =     -- Get the Id type and instantiate it at the specified types
201     (case id of
202        RealId id -> let (tyvars, rho) = splitForAllTy (idType id)
203                     in
204                     (if length tyvars /= length tys then pprTrace "newMethod" (ppr PprDebug (idType id)) else \x->x) $
205                     tcInstType (zip{-Equal "newMethod"-} tyvars tys) rho
206        TcId   id -> tcSplitForAllTy (idType id)         `thenNF_Tc` \ (tyvars, rho) -> 
207                     returnNF_Tc (instantiateTy (zipEqual "newMethod(2)" tyvars tys) rho)
208     )                                           `thenNF_Tc` \ rho_ty ->
209          -- Our friend does the rest
210     newMethodWithGivenTy orig id tys rho_ty
211
212
213 newMethodWithGivenTy orig id tys rho_ty
214   = tcGetSrcLoc         `thenNF_Tc` \ loc ->
215     tcGetUnique         `thenNF_Tc` \ new_uniq ->
216     let
217         meth_inst = Method new_uniq id tys rho_ty orig loc
218     in
219     returnNF_Tc (unitLIE meth_inst, instToId meth_inst)
220
221 newMethodAtLoc :: InstOrigin s -> SrcLoc -> Id -> [TcType s] -> NF_TcM s (Inst s, TcIdOcc s)
222 newMethodAtLoc orig loc real_id tys     -- Local function, similar to newMethod but with 
223                                         -- slightly different interface
224   =     -- Get the Id type and instantiate it at the specified types
225     let
226          (tyvars,rho) = splitForAllTy (idType real_id)
227     in
228     tcInstType (zipEqual "newMethodAtLoc" tyvars tys) rho `thenNF_Tc` \ rho_ty ->
229     tcGetUnique                                           `thenNF_Tc` \ new_uniq ->
230     let
231         meth_inst = Method new_uniq (RealId real_id) tys rho_ty orig loc
232     in
233     returnNF_Tc (meth_inst, instToId meth_inst)
234
235 newOverloadedLit :: InstOrigin s
236                  -> OverloadedLit
237                  -> TcType s
238                  -> NF_TcM s (LIE s, TcIdOcc s)
239 newOverloadedLit orig lit ty
240   = tcGetSrcLoc                 `thenNF_Tc` \ loc ->
241     tcGetUnique                 `thenNF_Tc` \ new_uniq ->
242     let
243         lit_inst = LitInst new_uniq lit ty orig loc
244     in
245     returnNF_Tc (unitLIE lit_inst, instToId lit_inst)
246 \end{code}
247
248
249 \begin{code}
250 instToId :: Inst s -> TcIdOcc s
251 instToId (Dict u clas ty orig loc)
252   = TcId (mkInstId u (mkDictTy clas ty) (mkLocalName u str loc))
253   where
254     str = VarOcc (SLIT("d.") _APPEND_ (occNameString (getOccName clas)))
255
256 instToId (Method u id tys rho_ty orig loc)
257   = TcId (mkInstId u tau_ty (mkLocalName u occ loc))
258   where
259     occ = getOccName id
260     (_, tau_ty) = splitRhoTy rho_ty     
261                 -- I hope we don't need tcSplitRhoTy...
262                 -- NB The method Id has just the tau type
263     
264 instToId (LitInst u list ty orig loc)
265   = TcId (mkInstId u ty (mkSysLocalName u SLIT("lit") loc))
266 \end{code}
267
268 \begin{code}
269 instType :: Inst s -> TcType s
270 instType (Dict _ clas ty _ _)     = mkDictTy clas ty
271 instType (LitInst _ _ ty _ _)     = ty
272 instType (Method _ id tys ty _ _) = ty
273 \end{code}
274
275
276 Zonking
277 ~~~~~~~
278 Zonking makes sure that the instance types are fully zonked,
279 but doesn't do the same for the Id in a Method.  There's no
280 need, and it's a lot of extra work.
281
282 \begin{code}
283 zonkInst :: Inst s -> NF_TcM s (Inst s)
284 zonkInst (Dict u clas ty orig loc)
285   = zonkTcType  ty                      `thenNF_Tc` \ new_ty ->
286     returnNF_Tc (Dict u clas new_ty orig loc)
287
288 zonkInst (Method u id tys rho orig loc)                 -- Doesn't zonk the id!
289   = mapNF_Tc zonkTcType tys             `thenNF_Tc` \ new_tys ->
290     zonkTcType rho                      `thenNF_Tc` \ new_rho ->
291     returnNF_Tc (Method u id new_tys new_rho orig loc)
292
293 zonkInst (LitInst u lit ty orig loc)
294   = zonkTcType ty                       `thenNF_Tc` \ new_ty ->
295     returnNF_Tc (LitInst u lit new_ty orig loc)
296 \end{code}
297
298
299 \begin{code}
300 tyVarsOfInst :: Inst s -> TcTyVarSet s
301 tyVarsOfInst (Dict _ _ ty _ _)        = tyVarsOfType  ty
302 tyVarsOfInst (Method _ id tys rho _ _) = tyVarsOfTypes tys `unionTyVarSets` tcIdTyVars id
303                                          -- The id might not be a RealId; in the case of
304                                          -- locally-overloaded class methods, for example
305 tyVarsOfInst (LitInst _ _ ty _ _)     = tyVarsOfType  ty
306 \end{code}
307
308 @matchesInst@ checks when two @Inst@s are instances of the same
309 thing at the same type, even if their uniques differ.
310
311 \begin{code}
312 matchesInst :: Inst s -> Inst s -> Bool
313
314 matchesInst (Dict _ clas1 ty1 _ _) (Dict _ clas2 ty2 _ _)
315   = clas1 == clas2 && ty1 `eqSimpleTy` ty2
316
317 matchesInst (Method _ id1 tys1 _ _ _) (Method _ id2 tys2 _ _ _)
318   =  id1 == id2
319   && and (zipWith eqSimpleTy tys1 tys2)
320   && length tys1 == length tys2
321
322 matchesInst (LitInst _ lit1 ty1 _ _) (LitInst _ lit2 ty2 _ _)
323   = lit1 `eq` lit2 && ty1 `eqSimpleTy` ty2
324   where
325     (OverloadedIntegral   i1) `eq` (OverloadedIntegral   i2) = i1 == i2
326     (OverloadedFractional f1) `eq` (OverloadedFractional f2) = f1 == f2
327     _                         `eq` _                         = False
328
329 matchesInst other1 other2 = False
330 \end{code}
331
332
333 Predicates
334 ~~~~~~~~~~
335 \begin{code}
336 isDict :: Inst s -> Bool
337 isDict (Dict _ _ _ _ _) = True
338 isDict other            = False
339
340 isTyVarDict :: Inst s -> Bool
341 isTyVarDict (Dict _ _ ty _ _) = isTyVarTy ty
342 isTyVarDict other             = False
343 \end{code}
344
345 Two predicates which deal with the case where class constraints don't
346 necessarily result in bindings.  The first tells whether an @Inst@
347 must be witnessed by an actual binding; the second tells whether an
348 @Inst@ can be generalised over.
349
350 \begin{code}
351 instBindingRequired :: Inst s -> Bool
352 instBindingRequired (Dict _ clas _ _ _) = not (isNoDictClass clas)
353 instBindingRequired other               = True
354
355 instCanBeGeneralised :: Inst s -> Bool
356 instCanBeGeneralised (Dict _ clas _ _ _) = not (isCcallishClass clas)
357 instCanBeGeneralised other               = True
358 \end{code}
359
360
361 Printing
362 ~~~~~~~~
363 ToDo: improve these pretty-printing things.  The ``origin'' is really only
364 relevant in error messages.
365
366 \begin{code}
367 instance Outputable (Inst s) where
368     ppr sty inst = pprQuote sty (\ sty -> ppr_inst sty (\ o l -> empty) inst)
369
370 pprInst sty inst = ppr_inst sty (\ o l -> pprOrigin o l sty) inst
371
372 ppr_inst sty ppr_orig (LitInst u lit ty orig loc)
373   = hang (ppr_orig orig loc)
374          4 (hsep [case lit of
375                       OverloadedIntegral   i -> integer i
376                       OverloadedFractional f -> rational f,
377                    ptext SLIT("at"),
378                    ppr sty ty,
379                    show_uniq sty u])
380
381 ppr_inst sty ppr_orig (Dict u clas ty orig loc)
382   = hang (ppr_orig orig loc)
383          4 (pprQuote sty $ \ sty -> 
384             hsep [ppr sty clas, pprParendGenType sty ty, show_uniq sty u])
385
386 ppr_inst sty ppr_orig (Method u id tys rho orig loc)
387   = hang (ppr_orig orig loc)
388          4 (hsep [ppr sty id, ptext SLIT("at"), 
389                   pprQuote sty $ \ sty -> interppSP sty tys,
390                   show_uniq sty u])
391
392 show_uniq PprDebug u = ppr PprDebug u
393 show_uniq sty      u = empty
394 \end{code}
395
396 Printing in error messages
397
398 \begin{code}
399 noInstanceErr inst sty = hang (ptext SLIT("No instance for:")) 4 (ppr sty inst)
400 \end{code}
401
402 %************************************************************************
403 %*                                                                      *
404 \subsection[InstEnv-types]{Type declarations}
405 %*                                                                      *
406 %************************************************************************
407
408 \begin{code}
409 type InstanceMapper = Class -> (ClassInstEnv, ClassOp -> SpecEnv)
410 \end{code}
411
412 A @ClassInstEnv@ lives inside a class, and identifies all the instances
413 of that class.  The @Id@ inside a ClassInstEnv mapping is the dfun for
414 that instance.  
415
416 There is an important consistency constraint between the @MatchEnv@s
417 in and the dfun @Id@s inside them: the free type variables of the
418 @Type@ key in the @MatchEnv@ must be a subset of the universally-quantified
419 type variables of the dfun.  Thus, the @ClassInstEnv@ for @Eq@ might
420 contain the following entry:
421 @
422         [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
423 @
424 The "a" in the pattern must be one of the forall'd variables in
425 the dfun type.
426
427 \begin{code}
428 lookupInst :: Inst s 
429            -> TcM s ([Inst s], 
430                      TcDictBinds s)     -- The new binding
431
432 -- Dictionaries
433
434 lookupInst dict@(Dict _ clas ty orig loc)
435   = case lookupMEnv matchTy (get_inst_env clas orig) ty of
436       Nothing   -> tcAddSrcLoc loc               $
437                    tcAddErrCtxt (pprOrigin orig loc) $
438                    failTc (noInstanceErr dict)
439
440       Just (dfun_id, tenv) 
441         -> let
442                 (tyvars, rho) = splitForAllTy (idType dfun_id)
443                 ty_args       = map (assoc "lookupInst" tenv) tyvars
444                 -- tenv should bind all the tyvars
445            in
446            tcInstType tenv rho          `thenNF_Tc` \ dfun_rho ->
447            let
448                 (theta, tau) = splitRhoTy dfun_rho
449            in
450            newDictsAtLoc orig loc theta `thenNF_Tc` \ (dicts, dict_ids) ->
451            let 
452                 rhs = mkHsDictApp (mkHsTyApp (HsVar (RealId dfun_id)) ty_args) dict_ids
453            in
454            returnTc (dicts, VarMonoBind (instToId dict) rhs)
455                              
456
457 -- Methods
458
459 lookupInst inst@(Method _ id tys rho orig loc)
460   = tcSplitRhoTy rho                    `thenNF_Tc` \ (theta, _) ->
461     newDictsAtLoc orig loc theta        `thenNF_Tc` \ (dicts, dict_ids) ->
462     returnTc (dicts, VarMonoBind (instToId inst) (mkHsDictApp (mkHsTyApp (HsVar id) tys) dict_ids))
463
464 -- Literals
465
466 lookupInst inst@(LitInst u (OverloadedIntegral i) ty orig loc)
467   | i >= toInteger minInt && i <= toInteger maxInt
468   =     -- It's overloaded but small enough to fit into an Int
469     tcLookupGlobalValueByKey fromIntClassOpKey  `thenNF_Tc` \ from_int ->
470     newMethodAtLoc orig loc from_int [ty]               `thenNF_Tc` \ (method_inst, method_id) ->
471     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) int_lit))
472
473   | otherwise 
474   =     -- Alas, it is overloaded and a big literal!
475     tcLookupGlobalValueByKey fromIntegerClassOpKey      `thenNF_Tc` \ from_integer ->
476     newMethodAtLoc orig loc from_integer [ty]           `thenNF_Tc` \ (method_inst, method_id) ->
477     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) (HsLitOut (HsInt i) integerTy)))
478   where
479     intprim_lit    = HsLitOut (HsIntPrim i) intPrimTy
480     int_lit        = HsApp (HsVar (RealId intDataCon)) intprim_lit
481
482 lookupInst inst@(LitInst u (OverloadedFractional f) ty orig loc)
483   = tcLookupGlobalValueByKey fromRationalClassOpKey     `thenNF_Tc` \ from_rational ->
484
485         -- The type Rational isn't wired in so we have to conjure it up
486     tcLookupTyConByKey rationalTyConKey `thenNF_Tc` \ rational_tycon ->
487     let
488         rational_ty  = mkSynTy rational_tycon []
489         rational_lit = HsLitOut (HsFrac f) rational_ty
490     in
491     newMethodAtLoc orig loc from_rational [ty]          `thenNF_Tc` \ (method_inst, method_id) ->
492     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) rational_lit))
493 \end{code}
494
495 There is a second, simpler interface, when you want an instance of a
496 class at a given nullary type constructor.  It just returns the
497 appropriate dictionary if it exists.  It is used only when resolving
498 ambiguous dictionaries.
499
500 \begin{code}
501 lookupSimpleInst :: ClassInstEnv
502                  -> Class
503                  -> Type                        -- Look up (c,t)
504                  -> TcM s [(Class,Type)]        -- Here are the needed (c,t)s
505
506 lookupSimpleInst class_inst_env clas ty
507   = case (lookupMEnv matchTy class_inst_env ty) of
508       Nothing          -> failTc (noSimpleInst clas ty)
509       Just (dfun,tenv) -> returnTc [(c,instantiateTy tenv t) | (c,t) <- theta]
510                        where
511                           (_, theta, _) = splitSigmaTy (idType dfun)
512
513 noSimpleInst clas ty sty
514   = sep [ptext SLIT("No instance for class"), ppr sty clas,
515            ptext SLIT("at type"), ppr sty ty]
516 \end{code}
517
518
519 @mkInstSpecEnv@ is used to construct the @SpecEnv@ for a dfun.
520 It does it by filtering the class's @InstEnv@.  All pretty shady stuff.
521
522 \begin{code}
523 mkInstSpecEnv clas inst_ty inst_tvs inst_theta = panic "mkInstSpecEnv"
524 \end{code}
525
526 \begin{pseudocode}
527 mkInstSpecEnv :: Class                  -- class
528               -> Type                   -- instance type
529               -> [TyVarTemplate]        -- instance tyvars
530               -> ThetaType              -- superclasses dicts
531               -> SpecEnv                -- specenv for dfun of instance
532
533 mkInstSpecEnv clas inst_ty inst_tvs inst_theta
534   = mkSpecEnv (catMaybes (map maybe_spec_info matches))
535   where
536     matches = matchMEnv matchTy (classInstEnv clas) inst_ty
537
538     maybe_spec_info (_, match_info, MkInstTemplate dfun _ [])
539       = Just (SpecInfo (map (assocMaybe match_info) inst_tvs) (length inst_theta) dfun)
540     maybe_spec_info (_, match_info, _)
541       = Nothing
542 \end{pseudocode}
543
544
545 \begin{code}
546 addClassInst
547     :: ClassInstEnv             -- Incoming envt
548     -> Type                     -- The instance type: inst_ty
549     -> Id                       -- Dict fun id to apply. Free tyvars of inst_ty must
550                                 -- be the same as the forall'd tyvars of the dfun id.
551     -> MaybeErr
552           ClassInstEnv          -- Success
553           (Type, Id)            -- Offending overlap
554
555 addClassInst inst_env inst_ty dfun_id = insertMEnv matchTy inst_env inst_ty dfun_id
556 \end{code}
557
558
559
560 %************************************************************************
561 %*                                                                      *
562 \subsection[Inst-origin]{The @InstOrigin@ type}
563 %*                                                                      *
564 %************************************************************************
565
566 The @InstOrigin@ type gives information about where a dictionary came from.
567 This is important for decent error message reporting because dictionaries
568 don't appear in the original source code.  Doubtless this type will evolve...
569
570 \begin{code}
571 data InstOrigin s
572   = OccurrenceOf (TcIdOcc s)    -- Occurrence of an overloaded identifier
573   | OccurrenceOfCon Id          -- Occurrence of a data constructor
574
575   | RecordUpdOrigin
576
577   | DataDeclOrigin              -- Typechecking a data declaration
578
579   | InstanceDeclOrigin          -- Typechecking an instance decl
580
581   | LiteralOrigin       HsLit   -- Occurrence of a literal
582
583   | ArithSeqOrigin      RenamedArithSeqInfo -- [x..], [x..y] etc
584
585   | SignatureOrigin             -- A dict created from a type signature
586
587   | DoOrigin                    -- The monad for a do expression
588
589   | ClassDeclOrigin             -- Manufactured during a class decl
590
591 --      NO MORE!
592 --  | DerivingOrigin    InstanceMapper
593 --                      Class
594 --                      TyCon
595
596         -- During "deriving" operations we have an ever changing
597         -- mapping of classes to instances, so we record it inside the
598         -- origin information.  This is a bit of a hack, but it works
599         -- fine.  (Simon is to blame [WDP].)
600
601   | InstanceSpecOrigin  InstanceMapper
602                         Class   -- in a SPECIALIZE instance pragma
603                         Type
604
605         -- When specialising instances the instance info attached to
606         -- each class is not yet ready, so we record it inside the
607         -- origin information.  This is a bit of a hack, but it works
608         -- fine.  (Patrick is to blame [WDP].)
609
610 --  | DefaultDeclOrigin         -- Related to a `default' declaration
611
612   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
613
614         -- Argument or result of a ccall
615         -- Dictionaries with this origin aren't actually mentioned in the
616         -- translated term, and so need not be bound.  Nor should they
617         -- be abstracted over.
618
619   | CCallOrigin         String                  -- CCall label
620                         (Maybe RenamedHsExpr)   -- Nothing if it's the result
621                                                 -- Just arg, for an argument
622
623   | LitLitOrigin        String  -- the litlit
624
625   | UnknownOrigin       -- Help! I give up...
626 \end{code}
627
628 \begin{code}
629 -- During deriving and instance specialisation operations
630 -- we can't get the instances of the class from inside the
631 -- class, because the latter ain't ready yet.  Instead we
632 -- find a mapping from classes to envts inside the dict origin.
633
634 get_inst_env :: Class -> InstOrigin s -> ClassInstEnv
635 -- get_inst_env clas (DerivingOrigin inst_mapper _ _)
636 --  = fst (inst_mapper clas)
637 get_inst_env clas (InstanceSpecOrigin inst_mapper _ _)
638   = fst (inst_mapper clas)
639 get_inst_env clas other_orig = classInstEnv clas
640
641
642 pprOrigin :: InstOrigin s -> SrcLoc -> Error
643
644 pprOrigin orig locn sty
645   = hsep [text "arising from", pp_orig, text "at", ppr sty locn]
646   where
647     pp_orig 
648       = case orig of
649           OccurrenceOf id ->
650             hsep [ptext SLIT("use of"), ppr sty id]
651           OccurrenceOfCon id ->
652             hsep [ptext SLIT("use of"), ppr sty id]
653           LiteralOrigin lit ->
654             hsep [ptext SLIT("the literal"), ppr sty lit]
655           InstanceDeclOrigin ->
656             ptext SLIT("an instance declaration")
657           ArithSeqOrigin seq ->
658             hsep [ptext SLIT("the arithmetic sequence:"), ppr sty seq]
659           SignatureOrigin ->
660             ptext SLIT("a type signature")
661           DoOrigin ->
662             ptext SLIT("a do statement")
663           ClassDeclOrigin ->
664             ptext SLIT("a class declaration")
665           InstanceSpecOrigin _ clas ty ->
666             hsep [text "a SPECIALIZE instance pragma; class",
667                        ppr sty clas, text "type:", ppr sty ty]
668           ValSpecOrigin name ->
669             hsep [ptext SLIT("a SPECIALIZE user-pragma for"), ppr sty name]
670           CCallOrigin clabel Nothing{-ccall result-} ->
671             hsep [ptext SLIT("the result of the _ccall_ to"), text clabel]
672           CCallOrigin clabel (Just arg_expr) ->
673             hsep [ptext SLIT("an argument in the _ccall_ to"), text clabel <> comma, text "namely", ppr sty arg_expr]
674           LitLitOrigin s ->
675             hcat [ptext SLIT("the ``literal-literal''"), text s]
676           UnknownOrigin ->
677             ptext SLIT("...oops -- I don't know where the overloading came from!")
678 \end{code}