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