2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1995
4 \section[Inst]{The @Inst@ type: dictionaries or method instances}
7 #include "HsVersions.h"
10 Inst(..), InstOrigin(..), OverloadedLit(..),
12 mkDict, mkMethod, mkLitInst,
14 --UNUSED: getInstLocalName,
15 getInstOrigin, getDictClassAndType,
16 --UNUSED: instantiateInst,
18 apply_to_Inst, -- not for general use, please
19 extractTyVarsFromInst, extractConstrainedTyVarsFromInst,
22 --UNUSED: isNullaryTyConDict,
23 instBindingRequired, instCanBeGeneralised,
25 -- and to make the interface self-sufficient...
26 Class, ClassOp, ArithSeqInfo, RenamedArithSeqInfo(..),
27 Literal, InPat, RenamedPat(..), Expr, RenamedExpr(..),
28 Id, Name, SrcLoc, Subst, PrimKind,
29 TyVar, TyVarTemplate, TyCon, UniType, Unique, InstTemplate,
30 InstanceMapper(..), ClassInstEnv(..), MatchEnv(..)
32 IF_ATTACK_PRAGMAS(COMMA isTyVarTy)
37 import Id ( eqId, applySubstToId,
38 getInstNamePieces, getIdUniType,
43 import Maybes ( Maybe(..) )
46 import SrcLoc ( mkUnknownSrcLoc, SrcLoc )
47 import Subst ( applySubstToTy, Subst )
52 %************************************************************************
54 \subsection[Inst-types]{@Inst@ types}
56 %************************************************************************
58 An @Inst@ is either a dictionary, an instance of an overloaded
59 literal, or an instance of an overloaded value. We call the latter a
60 ``method'' even though it may not correspond to a class operation.
61 For example, we might have an instance of the @double@ function at
62 type Int, represented by
64 Method 34 doubleId [Int] origin
70 Class -- The type of the dict is (c t), where
71 UniType -- c is the class and t the unitype;
76 Id -- (I expect) be a global, local, or ClassOpId.
77 -- Inside instance decls (only) it can also be an InstId!
78 -- The id needn't be completely polymorphic,
79 [UniType] -- The types to which its polymorphic tyvars
80 -- should be instantiated
81 -- These types may not saturate the Id's foralls.
87 UniType -- the type at which the literal is used
88 InstOrigin -- always a literal; but more convenient to carry this around
95 = OverloadedIntegral Integer -- the number
96 Id Id -- cached fromInt, fromInteger
97 | OverloadedFractional Rational -- the number
98 Id -- cached fromRational
101 getInstLocalName (Dict _ clas _ _) = getLocalName clas
102 getInstLocalName (Method _ id _ _) = getLocalName id
105 -- this is used for error messages
106 getDictClassAndType :: Inst -> (Class, UniType)
107 getDictClassAndType (Dict _ clas ty _) = (clas, ty)
109 getInstUniType :: Inst -> UniType
110 getInstUniType (Dict _ clas ty _) = mkDictTy clas ty
111 getInstUniType (LitInst _ _ ty _) = ty
112 getInstUniType (Method _ id tys _)
113 = instantiateTauTy (tyvars `zip` tys) tau_ty
115 (tyvars, theta, tau_ty) = splitType (getIdUniType id)
116 -- Note that we ignore the overloading; this is
117 -- an INSTANCE of an overloaded operation
120 @applySubstToInst@ doesn't make any assumptions, but @instantiateInst@
121 assumes that the @Id@ in a @Method@ is fully polymorphic (ie has no free
126 instantiateInst :: [(TyVarTemplate, UniType)] -> Inst -> Inst
128 instantiateInst tenv (Dict uniq clas ty orig)
129 = Dict uniq clas (instantiateTy tenv ty) orig
131 instantiateInst tenv (Method uniq id tys orig)
132 = --False:ASSERT(idHasNoFreeTyVars id)
133 Method uniq id (map (instantiateTy tenv) tys) orig
135 instantiateInst tenv (LitInst u lit ty orig)
136 = LitInst u lit (instantiateTy tenv ty) orig
139 -----------------------------------------------------------------
140 -- too bad we can't use apply_to_Inst
142 applySubstToInst subst (Dict uniq clas ty orig)
143 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
144 (s2, Dict uniq clas new_ty orig) }
146 applySubstToInst subst (Method uniq id tys orig)
147 -- NB: *must* zap "id" in the typechecker
148 = case (applySubstToId subst id) of { (s2, new_id) ->
149 case (mapAccumL applySubstToTy s2 tys) of { (s3, new_tys) ->
150 (s3, Method uniq new_id new_tys orig) }}
152 applySubstToInst subst (LitInst u lit ty orig)
153 = case (applySubstToTy subst ty) of { (s2, new_ty) ->
154 (s2, LitInst u lit new_ty orig) }
156 -----------------------------------------------------------------
157 apply_to_Inst :: (UniType -> UniType) -> Inst -> Inst
159 apply_to_Inst ty_fn (Dict uniq clas ty orig)
160 = Dict uniq clas (ty_fn ty) orig
162 apply_to_Inst ty_fn (Method uniq id tys orig)
163 = --FALSE: ASSERT(idHasNoFreeTyVars id)
164 Method uniq id (map ty_fn tys) orig
166 apply_to_Inst ty_fn (LitInst u lit ty orig)
167 = LitInst u lit (ty_fn ty) orig
171 extractTyVarsFromInst, extractConstrainedTyVarsFromInst :: Inst -> [TyVar]
173 extractTyVarsFromInst (Dict _ _ ty _) = extractTyVarsFromTy ty
174 extractTyVarsFromInst (Method _ _ tys _) = extractTyVarsFromTys tys
175 extractTyVarsFromInst (LitInst _ _ ty _) = extractTyVarsFromTy ty
177 extractConstrainedTyVarsFromInst (Dict _ _ ty _) = extractTyVarsFromTy ty
178 extractConstrainedTyVarsFromInst (LitInst _ _ ty _) = extractTyVarsFromTy ty
180 -- `Method' is different!
181 extractConstrainedTyVarsFromInst (Method _ m tys _)
182 = foldr unionLists [] (zipWith xxx tvs tys)
184 (tvs,theta,tau_ty) = splitType (getIdUniType m)
187 = foldr unionLists [] [extractTyVarTemplatesFromTy t | (_,t) <- theta ]
189 xxx tv ty | tv `elem` constrained_tvs = extractTyVarsFromTy ty
193 @matchesInst@ checks when two @Inst@s are instances of the same
194 thing at the same type, even if their uniques differ.
197 matchesInst :: Inst -> Inst -> Bool
198 matchesInst (Dict _ clas1 ty1 _) (Dict _ clas2 ty2 _)
199 = clas1 == clas2 && ty1 == ty2
200 matchesInst (Method _ id1 tys1 _) (Method _ id2 tys2 _)
201 = id1 `eqId` id2 && tys1 == tys2
202 matchesInst (LitInst _ lit1 ty1 _) (LitInst _ lit2 ty2 _)
203 = lit1 `eq` lit2 && ty1 == ty2
205 (OverloadedIntegral i1 _ _) `eq` (OverloadedIntegral i2 _ _) = i1 == i2
206 (OverloadedFractional f1 _) `eq` (OverloadedFractional f2 _) = f1 == f2
209 matchesInst other1 other2 = False
214 isTyVarDict :: Inst -> Bool
215 isTyVarDict (Dict _ _ ty _) = isTyVarTy ty
216 isTyVarDict other = False
219 isNullaryTyConDict :: Inst -> Bool
220 isNullaryTyConDict (Dict _ _ ty _)
221 = case (getUniDataTyCon_maybe ty) of
222 Just (tycon, [], _) -> True -- NB null args to tycon
227 Two predicates which deal with the case where
228 class constraints don't necessarily result in bindings.
229 The first tells whether an @Inst@ must be witnessed by an
230 actual binding; the second tells whether an @Inst@ can be
234 instBindingRequired :: Inst -> Bool
235 instBindingRequired inst
236 = case get_origin_really inst of
237 CCallOrigin _ _ _ -> False -- No binding required
238 LitLitOrigin _ _ -> False
241 instCanBeGeneralised :: Inst -> Bool
242 instCanBeGeneralised inst
243 = case get_origin_really inst of
244 CCallOrigin _ _ _ -> False -- Can't be generalised
245 LitLitOrigin _ _ -> False -- Can't be generalised
249 ToDo: improve these pretty-printing things. The ``origin'' is really only
250 relevant in error messages.
253 -- ToDo: this instance might be nukable (maybe not: used for error msgs)
255 instance Outputable Inst where
256 ppr PprForUser (LitInst _ lit _ _)
258 OverloadedIntegral i _ _ -> ppInteger i
259 #if __GLASGOW_HASKELL__ <= 22
260 OverloadedFractional f _ -> ppDouble (fromRational f) -- ToDo: better
262 OverloadedFractional f _ -> ppRational f
266 = ppIntersperse (ppChar '.') (map ppPStr (getInstNamePieces True inst))
270 %************************************************************************
272 \subsection[Inst-origin]{The @InstOrigin@ type}
274 %************************************************************************
276 The @InstOrigin@ type gives information about where a dictionary came from.
277 This is important for decent error message reporting because dictionaries
278 don't appear in the original source code. Doubtless this type will evolve...
282 = OccurrenceOf Id -- Occurrence of an overloaded identifier
285 | InstanceDeclOrigin SrcLoc -- Typechecking an instance decl
287 | LiteralOrigin Literal -- Occurrence of a literal
288 SrcLoc -- (now redundant? ToDo)
290 | ArithSeqOrigin RenamedArithSeqInfo -- [x..], [x..y] etc
293 | SignatureOrigin -- A dict created from a type signature
294 -- I don't expect this ever to appear in
295 -- an error message so I can't be bothered
296 -- to give it a source location...
298 | ClassDeclOrigin SrcLoc -- Manufactured during a class decl
300 | DerivingOrigin InstanceMapper
302 Bool -- True <=> deriving for *functions*;
303 -- do *not* look at the TyCon! [WDP 94/09]
307 -- During "deriving" operations we have an ever changing
308 -- mapping of classes to instances, so we record it inside the
309 -- origin information. This is a bit of a hack, but it works
310 -- fine. (Simon is to blame [WDP].)
312 | InstanceSpecOrigin InstanceMapper
313 Class -- in a SPECIALIZE instance pragma
317 -- When specialising instances the instance info attached to
318 -- each class is not yet ready, so we record it inside the
319 -- origin information. This is a bit of a hack, but it works
320 -- fine. (Patrick is to blame [WDP].)
322 | DefaultDeclOrigin SrcLoc -- Related to a `default' declaration
324 | ValSpecOrigin Name -- in a SPECIALIZE pragma for a value
327 -- Argument or result of a ccall
328 -- Dictionaries with this origin aren't actually mentioned in the
329 -- translated term, and so need not be bound. Nor should they
330 -- be abstracted over.
332 String -- CCall label
333 (Maybe RenamedExpr) -- Nothing if it's the result
334 -- Just arg, for an argument
336 | LitLitOrigin SrcLoc
339 | UnknownOrigin -- Help! I give up...
343 get_origin_really (Dict u clas ty origin) = origin
344 get_origin_really (Method u clas ty origin) = origin
345 get_origin_really (LitInst u lit ty origin) = origin
348 = let origin = get_origin_really inst
351 get_orig :: InstOrigin -> (SrcLoc, PprStyle -> Pretty)
353 get_orig (OccurrenceOf id loc)
354 = (loc, \ sty -> ppBesides [ppPStr SLIT("at a use of an overloaded identifier: `"),
355 ppr sty id, ppChar '\''])
356 get_orig (InstanceDeclOrigin loc)
357 = (loc, \ sty -> ppStr "in an instance declaration")
358 get_orig (LiteralOrigin lit loc)
359 = (loc, \ sty -> ppCat [ppStr "at an overloaded literal:", ppr sty lit])
360 get_orig (ArithSeqOrigin seq loc)
361 = (loc, \ sty -> ppCat [ppStr "at an arithmetic sequence:", ppr sty seq])
362 get_orig SignatureOrigin
363 = (mkUnknownSrcLoc, \ sty -> ppStr "in a type signature")
364 get_orig (ClassDeclOrigin loc)
365 = (loc, \ sty -> ppStr "in a class declaration")
366 get_orig (DerivingOrigin _ clas is_function tycon loc)
367 = (loc, \ sty -> ppBesides [ppStr "in a `deriving' clause; class \"",
370 then ppStr "\"; type: functions"
371 else ppBeside (ppStr "\"; offending type \"") (ppr sty tycon),
373 get_orig (InstanceSpecOrigin _ clas ty loc)
374 = (loc, \ sty -> ppBesides [ppStr "in a SPECIALIZE instance pragma; class \"",
375 ppr sty clas, ppStr "\" type: ", ppr sty ty])
376 get_orig (DefaultDeclOrigin loc)
377 = (loc, \ sty -> ppStr "in a `default' declaration")
378 get_orig (ValSpecOrigin name loc)
379 = (loc, \ sty -> ppBesides [ppStr "in a SPECIALIZE user-pragma for `",
380 ppr sty name, ppStr "'"])
381 get_orig (CCallOrigin loc clabel Nothing{-ccall result-})
382 = (loc, \ sty -> ppBesides [ppStr "in the result of the _ccall_ to `",
383 ppStr clabel, ppStr "'"])
384 get_orig (CCallOrigin loc clabel (Just arg_expr))
385 = (loc, \ sty -> ppBesides [ppStr "in an argument in the _ccall_ to `",
386 ppStr clabel, ppStr "', namely: ", ppr sty arg_expr])
387 get_orig (LitLitOrigin loc s)
388 = (loc, \ sty -> ppBesides [ppStr "in this ``literal-literal'': ", ppStr s])
389 get_orig UnknownOrigin
390 = (mkUnknownSrcLoc, \ sty -> ppStr "in... oops -- I don't know where the overloading came from!")