6e0740641d7da89adf584dcbf8a7de30631ce582
[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 (hsep [ppr sty clas, pprParendGenType sty ty, show_uniq sty u])
384
385 ppr_inst sty ppr_orig (Method u id tys rho orig loc)
386   = hang (ppr_orig orig loc)
387          4 (hsep [ppr sty id, ptext SLIT("at"), interppSP sty tys, show_uniq sty u])
388
389 show_uniq PprDebug u = ppr PprDebug u
390 show_uniq sty      u = empty
391 \end{code}
392
393 Printing in error messages
394
395 \begin{code}
396 noInstanceErr inst sty = hang (ptext SLIT("No instance for:")) 4 (ppr sty inst)
397 \end{code}
398
399 %************************************************************************
400 %*                                                                      *
401 \subsection[InstEnv-types]{Type declarations}
402 %*                                                                      *
403 %************************************************************************
404
405 \begin{code}
406 type InstanceMapper = Class -> (ClassInstEnv, ClassOp -> SpecEnv)
407 \end{code}
408
409 A @ClassInstEnv@ lives inside a class, and identifies all the instances
410 of that class.  The @Id@ inside a ClassInstEnv mapping is the dfun for
411 that instance.  
412
413 There is an important consistency constraint between the @MatchEnv@s
414 in and the dfun @Id@s inside them: the free type variables of the
415 @Type@ key in the @MatchEnv@ must be a subset of the universally-quantified
416 type variables of the dfun.  Thus, the @ClassInstEnv@ for @Eq@ might
417 contain the following entry:
418 @
419         [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
420 @
421 The "a" in the pattern must be one of the forall'd variables in
422 the dfun type.
423
424 \begin{code}
425 lookupInst :: Inst s 
426            -> TcM s ([Inst s], 
427                      TcDictBinds s)     -- The new binding
428
429 -- Dictionaries
430
431 lookupInst dict@(Dict _ clas ty orig loc)
432   = case lookupMEnv matchTy (get_inst_env clas orig) ty of
433       Nothing   -> tcAddSrcLoc loc               $
434                    tcAddErrCtxt (pprOrigin orig loc) $
435                    failTc (noInstanceErr dict)
436
437       Just (dfun_id, tenv) 
438         -> let
439                 (tyvars, rho) = splitForAllTy (idType dfun_id)
440                 ty_args       = map (assoc "lookupInst" tenv) tyvars
441                 -- tenv should bind all the tyvars
442            in
443            tcInstType tenv rho          `thenNF_Tc` \ dfun_rho ->
444            let
445                 (theta, tau) = splitRhoTy dfun_rho
446            in
447            newDictsAtLoc orig loc theta `thenNF_Tc` \ (dicts, dict_ids) ->
448            let 
449                 rhs = mkHsDictApp (mkHsTyApp (HsVar (RealId dfun_id)) ty_args) dict_ids
450            in
451            returnTc (dicts, VarMonoBind (instToId dict) rhs)
452                              
453
454 -- Methods
455
456 lookupInst inst@(Method _ id tys rho orig loc)
457   = tcSplitRhoTy rho                    `thenNF_Tc` \ (theta, _) ->
458     newDictsAtLoc orig loc theta        `thenNF_Tc` \ (dicts, dict_ids) ->
459     returnTc (dicts, VarMonoBind (instToId inst) (mkHsDictApp (mkHsTyApp (HsVar id) tys) dict_ids))
460
461 -- Literals
462
463 lookupInst inst@(LitInst u (OverloadedIntegral i) ty orig loc)
464   | i >= toInteger minInt && i <= toInteger maxInt
465   =     -- It's overloaded but small enough to fit into an Int
466     tcLookupGlobalValueByKey fromIntClassOpKey  `thenNF_Tc` \ from_int ->
467     newMethodAtLoc orig loc from_int [ty]               `thenNF_Tc` \ (method_inst, method_id) ->
468     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) int_lit))
469
470   | otherwise 
471   =     -- Alas, it is overloaded and a big literal!
472     tcLookupGlobalValueByKey fromIntegerClassOpKey      `thenNF_Tc` \ from_integer ->
473     newMethodAtLoc orig loc from_integer [ty]           `thenNF_Tc` \ (method_inst, method_id) ->
474     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) (HsLitOut (HsInt i) integerTy)))
475   where
476     intprim_lit    = HsLitOut (HsIntPrim i) intPrimTy
477     int_lit        = HsApp (HsVar (RealId intDataCon)) intprim_lit
478
479 lookupInst inst@(LitInst u (OverloadedFractional f) ty orig loc)
480   = tcLookupGlobalValueByKey fromRationalClassOpKey     `thenNF_Tc` \ from_rational ->
481
482         -- The type Rational isn't wired in so we have to conjure it up
483     tcLookupTyConByKey rationalTyConKey `thenNF_Tc` \ rational_tycon ->
484     let
485         rational_ty  = mkSynTy rational_tycon []
486         rational_lit = HsLitOut (HsFrac f) rational_ty
487     in
488     newMethodAtLoc orig loc from_rational [ty]          `thenNF_Tc` \ (method_inst, method_id) ->
489     returnTc ([method_inst], VarMonoBind (instToId inst) (HsApp (HsVar method_id) rational_lit))
490 \end{code}
491
492 There is a second, simpler interface, when you want an instance of a
493 class at a given nullary type constructor.  It just returns the
494 appropriate dictionary if it exists.  It is used only when resolving
495 ambiguous dictionaries.
496
497 \begin{code}
498 lookupSimpleInst :: ClassInstEnv
499                  -> Class
500                  -> Type                        -- Look up (c,t)
501                  -> TcM s [(Class,Type)]        -- Here are the needed (c,t)s
502
503 lookupSimpleInst class_inst_env clas ty
504   = case (lookupMEnv matchTy class_inst_env ty) of
505       Nothing          -> failTc (noSimpleInst clas ty)
506       Just (dfun,tenv) -> returnTc [(c,instantiateTy tenv t) | (c,t) <- theta]
507                        where
508                           (_, theta, _) = splitSigmaTy (idType dfun)
509
510 noSimpleInst clas ty sty
511   = sep [ptext SLIT("No instance for class"), ppr sty clas,
512            ptext SLIT("at type"), ppr sty ty]
513 \end{code}
514
515
516 @mkInstSpecEnv@ is used to construct the @SpecEnv@ for a dfun.
517 It does it by filtering the class's @InstEnv@.  All pretty shady stuff.
518
519 \begin{code}
520 mkInstSpecEnv clas inst_ty inst_tvs inst_theta = panic "mkInstSpecEnv"
521 \end{code}
522
523 \begin{pseudocode}
524 mkInstSpecEnv :: Class                  -- class
525               -> Type                   -- instance type
526               -> [TyVarTemplate]        -- instance tyvars
527               -> ThetaType              -- superclasses dicts
528               -> SpecEnv                -- specenv for dfun of instance
529
530 mkInstSpecEnv clas inst_ty inst_tvs inst_theta
531   = mkSpecEnv (catMaybes (map maybe_spec_info matches))
532   where
533     matches = matchMEnv matchTy (classInstEnv clas) inst_ty
534
535     maybe_spec_info (_, match_info, MkInstTemplate dfun _ [])
536       = Just (SpecInfo (map (assocMaybe match_info) inst_tvs) (length inst_theta) dfun)
537     maybe_spec_info (_, match_info, _)
538       = Nothing
539 \end{pseudocode}
540
541
542 \begin{code}
543 addClassInst
544     :: ClassInstEnv             -- Incoming envt
545     -> Type                     -- The instance type: inst_ty
546     -> Id                       -- Dict fun id to apply. Free tyvars of inst_ty must
547                                 -- be the same as the forall'd tyvars of the dfun id.
548     -> MaybeErr
549           ClassInstEnv          -- Success
550           (Type, Id)            -- Offending overlap
551
552 addClassInst inst_env inst_ty dfun_id = insertMEnv matchTy inst_env inst_ty dfun_id
553 \end{code}
554
555
556
557 %************************************************************************
558 %*                                                                      *
559 \subsection[Inst-origin]{The @InstOrigin@ type}
560 %*                                                                      *
561 %************************************************************************
562
563 The @InstOrigin@ type gives information about where a dictionary came from.
564 This is important for decent error message reporting because dictionaries
565 don't appear in the original source code.  Doubtless this type will evolve...
566
567 \begin{code}
568 data InstOrigin s
569   = OccurrenceOf (TcIdOcc s)    -- Occurrence of an overloaded identifier
570   | OccurrenceOfCon Id          -- Occurrence of a data constructor
571
572   | RecordUpdOrigin
573
574   | DataDeclOrigin              -- Typechecking a data declaration
575
576   | InstanceDeclOrigin          -- Typechecking an instance decl
577
578   | LiteralOrigin       HsLit   -- Occurrence of a literal
579
580   | ArithSeqOrigin      RenamedArithSeqInfo -- [x..], [x..y] etc
581
582   | SignatureOrigin             -- A dict created from a type signature
583
584   | DoOrigin                    -- The monad for a do expression
585
586   | ClassDeclOrigin             -- Manufactured during a class decl
587
588 --      NO MORE!
589 --  | DerivingOrigin    InstanceMapper
590 --                      Class
591 --                      TyCon
592
593         -- During "deriving" operations we have an ever changing
594         -- mapping of classes to instances, so we record it inside the
595         -- origin information.  This is a bit of a hack, but it works
596         -- fine.  (Simon is to blame [WDP].)
597
598   | InstanceSpecOrigin  InstanceMapper
599                         Class   -- in a SPECIALIZE instance pragma
600                         Type
601
602         -- When specialising instances the instance info attached to
603         -- each class is not yet ready, so we record it inside the
604         -- origin information.  This is a bit of a hack, but it works
605         -- fine.  (Patrick is to blame [WDP].)
606
607 --  | DefaultDeclOrigin         -- Related to a `default' declaration
608
609   | ValSpecOrigin       Name    -- in a SPECIALIZE pragma for a value
610
611         -- Argument or result of a ccall
612         -- Dictionaries with this origin aren't actually mentioned in the
613         -- translated term, and so need not be bound.  Nor should they
614         -- be abstracted over.
615
616   | CCallOrigin         String                  -- CCall label
617                         (Maybe RenamedHsExpr)   -- Nothing if it's the result
618                                                 -- Just arg, for an argument
619
620   | LitLitOrigin        String  -- the litlit
621
622   | UnknownOrigin       -- Help! I give up...
623 \end{code}
624
625 \begin{code}
626 -- During deriving and instance specialisation operations
627 -- we can't get the instances of the class from inside the
628 -- class, because the latter ain't ready yet.  Instead we
629 -- find a mapping from classes to envts inside the dict origin.
630
631 get_inst_env :: Class -> InstOrigin s -> ClassInstEnv
632 -- get_inst_env clas (DerivingOrigin inst_mapper _ _)
633 --  = fst (inst_mapper clas)
634 get_inst_env clas (InstanceSpecOrigin inst_mapper _ _)
635   = fst (inst_mapper clas)
636 get_inst_env clas other_orig = classInstEnv clas
637
638
639 pprOrigin :: InstOrigin s -> SrcLoc -> Error
640
641 pprOrigin orig locn sty
642   = hsep [text "arising from", pp_orig, text "at", ppr sty locn]
643   where
644     pp_orig 
645       = case orig of
646           OccurrenceOf id ->
647             hsep [ptext SLIT("use of"), ppr sty id]
648           OccurrenceOfCon id ->
649             hsep [ptext SLIT("use of"), ppr sty id]
650           LiteralOrigin lit ->
651             hsep [ptext SLIT("the literal"), ppr sty lit]
652           InstanceDeclOrigin ->
653             ptext SLIT("an instance declaration")
654           ArithSeqOrigin seq ->
655             hsep [ptext SLIT("the arithmetic sequence:"), ppr sty seq]
656           SignatureOrigin ->
657             ptext SLIT("a type signature")
658           DoOrigin ->
659             ptext SLIT("a do statement")
660           ClassDeclOrigin ->
661             ptext SLIT("a class declaration")
662           InstanceSpecOrigin _ clas ty ->
663             hsep [text "a SPECIALIZE instance pragma; class",
664                        ppr sty clas, text "type:", ppr sty ty]
665           ValSpecOrigin name ->
666             hsep [ptext SLIT("a SPECIALIZE user-pragma for"), ppr sty name]
667           CCallOrigin clabel Nothing{-ccall result-} ->
668             hsep [ptext SLIT("the result of the _ccall_ to"), text clabel]
669           CCallOrigin clabel (Just arg_expr) ->
670             hsep [ptext SLIT("an argument in the _ccall_ to"), text clabel <> comma, text "namely", ppr sty arg_expr]
671           LitLitOrigin s ->
672             hcat [ptext SLIT("the ``literal-literal''"), text s]
673           UnknownOrigin ->
674             ptext SLIT("...oops -- I don't know where the overloading came from!")
675 \end{code}