2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1995
4 \section[InstEnv]{Instance environments}
7 #include "HsVersions.h"
10 -- these types could use some abstractification (??? ToDo)
11 ClassInstEnv(..), -- OLD: IdInstEnv(..),
13 MethodInstInfo(..), -- needs to be exported? (ToDo)
14 InstanceMapper(..), -- widely-used synonym
16 -- instMethod, instTemplate, -- no need to export
17 addClassInst, {- NOT USED addConstMethInst, -}
19 lookupClassInstAtSimpleType,
22 MatchEnv(..), -- mk more abstract (??? ToDo)
24 -- mkMEnv, lookupMEnv, insertMEnv, -- no need to export
26 -- and to make the interface self-sufficient...
27 Class, ClassOp, CoreExpr, Expr, TypecheckedPat, Id,
28 Inst, InstOrigin, Maybe, MaybeErr, TyVarTemplate, TyCon,
29 UniType, SplitUniqSupply, SpecInfo
32 IMPORT_Trace -- ToDo: rm (debugging)
34 import AbsPrel ( intTyCon, --wordTyCon, addrTyCon,
35 floatTyCon, doubleTyCon, charDataCon, intDataCon,
36 wordDataCon, addrDataCon, floatDataCon,
38 intPrimTyCon, doublePrimTyCon
40 import AbsSyn -- TypecheckedExpr, etc.
45 import Maybes -- most of it
46 import Outputable ( isExported )
47 import PlainCore -- PlainCoreExpr, etc.
49 import PrimKind -- rather grubby import (ToDo?)
54 %************************************************************************
56 \subsection[InstEnv-types]{Type declarations}
58 %************************************************************************
62 = Class -> (ClassInstEnv, ClassOp -> SpecEnv)
64 type ClassInstEnv = MatchEnv UniType InstTemplate -- Instances of dicts
65 --OLD: type IdInstEnv = MatchEnv [UniType] InstTemplate -- Instances of ids
69 Id -- A fully polymorphic Id; it is the function
70 -- which produces the Id instance or dict from
71 -- the pieces specified by the rest of the
72 -- template. Its SrcLoc tells where the
73 -- instance was defined.
74 [UniType] -- Apply it to these types, suitably instantiated
75 [InstTy] -- and instances of these things
77 type MethodInstInfo = (Id, [UniType], InstTemplate) -- Specifies a method instance
80 There is an important consistency constraint between the @MatchEnv@s
81 in and the @InstTemplate@s inside them: the @UniType@(s) which is/are
82 the key for the @MatchEnv@ must contain only @TyVarTemplates@, and
83 these must be a superset of the @TyVarTemplates@ mentioned in the
84 corresponding @InstTemplate@.
86 Reason: the lookup process matches the key against the desired value,
87 returning a substitution which is used to instantiate the template.
91 = DictTy Class UniType
92 | MethodTy Id [UniType]
95 MkInstTemplate f tvs insts
97 says that, given a particular mapping of type variables tvs to some
98 types tys, the value which is the required instance is
100 f tys (insts [tys/tvs])
103 @instMethod@ is used if there is no instance for a method; then it is
104 expressed in terms of the corresponding dictionary (or possibly, in a
105 wired-in case only, dictionaries).
108 instMethod :: SplitUniqSupply
111 -> (TypecheckedExpr, [Inst])
113 instMethod uniqs orig id tys
114 = (mkDictApp (mkTyApp (Var id) tys) dicts,
117 (tyvars, theta, tau_ty) = splitType (getIdUniType id)
118 tenv = tyvars `zipEqual` tys
119 insts = mk_dict_insts uniqs theta
120 dicts = map mkInstId insts
122 mk_dict_insts us [] = []
123 mk_dict_insts us ((clas, ty) : rest)
124 = case splitUniqSupply us of { (s1, s2) ->
125 (Dict (getSUnique s1) clas (instantiateTauTy tenv ty) orig)
126 : mk_dict_insts s2 rest
130 @instTemplate@ is used if there is an instance for a method or dictionary.
133 instTemplate :: SplitUniqSupply
135 -> [(TyVarTemplate, UniType)]
137 -> (TypecheckedExpr, [Inst])
139 instTemplate uniqs orig tenv (MkInstTemplate id ty_tmpls inst_tys)
140 = (mkDictApp (mkTyApp (Var id) ty_args) ids, -- ToDo: not strictly a dict app
141 -- for Method inst_tys
144 ty_args = map (instantiateTy tenv) ty_tmpls
145 insts = mk_insts uniqs inst_tys
146 ids = map mkInstId insts
149 mk_insts us (inst_ty : rest)
150 = case splitUniqSupply us of { (s1, s2) ->
155 DictTy clas ty -> Dict uniq clas (instantiateTy tenv ty) orig
156 MethodTy id tys -> Method uniq id (map (instantiateTy tenv) tys) orig
162 %************************************************************************
164 \subsection[InstEnv-adding]{Adding new class instances}
166 %************************************************************************
168 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@ based on
169 information from a single instance declaration. It complains about
170 any overlap with an existing instance.
172 Notice that we manufacture the @DictFunId@ and @ConstMethodId@s from
173 scratch here, rather than passing them in. This means a small amount
174 of duplication (no big deal) and that we can't attach a single
175 canonical unfolding; but they don't have a slot for unfoldings
176 anyway... This could be improved. (We do, however, snaffle in the
177 pragma info from the interface...)
183 fop :: Ord b => a -> b -> b -> a
185 instance Foo Int where
186 fop x y z = if y<z then x else fop x z y
188 instance Foo a => Foo [a] where
190 fop (x:xs) y z = [fop x y z]
194 For the Int instance we add to the ??? envt
196 (ClassOpId Foo fop) |--> [Int,b] |--> InstTemplate (ConstMethodId Foo fop Int) [b] [Ord b]
199 If there are no type variables, @addClassInstance@ adds constant
200 instances for those class ops not mentioned in the class-op details
201 (possibly using the pragma info that was passed in). This MUST
202 be the same decision as that by @tcInstDecls2@ about whether to
203 generate constant methods. NB: A slightly more permissive version
204 would base the decision on the context being empty, but there is
205 slightly more admin associated and the benefits are very slight; the
206 context is seldom empty unless there are no tyvars involved.
208 Note: the way of specifying class-op instance details is INADEQUATE
209 for polymorphic class ops. That just means you can't specify clever
210 instances for them via this function.
214 :: Class -- class in question (for err msg only)
215 -> ClassInstEnv -- Incoming envt
216 -> UniType -- The instance type
217 -> Id -- Dict fun id to apply
218 -> [TyVarTemplate] -- Types to which (after instantiation) to apply the dfun
219 -> ThetaType -- Dicts to which to apply the dfun
220 -> SrcLoc -- associated SrcLoc (for err msg only)
222 ClassInstEnv -- Success
223 (Class, (UniType, SrcLoc), -- Failure: the overlapping pair
226 addClassInst clas inst_env inst_ty dfun_id inst_tyvars dfun_theta locn
227 = case (insertMEnv matchTy inst_env inst_ty dict_template) of
228 Succeeded inst_env' -> Succeeded inst_env'
229 Failed (ty', MkInstTemplate id' _ _)
230 -> Failed (clas, (inst_ty, locn), (ty', getSrcLoc id'))
232 dict_template = MkInstTemplate dfun_id
233 (map mkTyVarTemplateTy inst_tyvars)
234 (unzipWith DictTy dfun_theta)
237 ============ NOT USED =============
238 @addConstMethInst@ panics on overlap, because @addClassInst@ has already found
242 addConstMethInst :: IdInstEnv
243 -> UniType -- The instance type
244 -> Id -- The constant method
245 -> [TyVarTemplate] -- Apply method to these (as above)
248 addConstMethInst inst_env inst_ty meth_id inst_tyvars
249 = case (insertMEnv matchTys inst_env [inst_ty] template) of
250 Succeeded inst_env' -> inst_env'
251 Failed (tys', MkInstTemplate id' _ _) ->
252 pprPanic "addConstMethInst:"
253 (ppSep [ppr PprDebug meth_id,
254 ppr PprDebug inst_ty,
257 template = MkInstTemplate meth_id (map mkTyVarTemplateTy inst_tyvars) []
258 -- Constant method just needs to be applied to tyvars
259 -- (which are usually empty)
262 @mkIdInstEnv@ is useful in the simple case where we've a list of
263 @(types, id)@ pairs; the \tr{id} is the \tr{types} specialisation of
264 some other Id (in which the resulting IdInstEnv will doubtless be
265 embedded. There's no messing about with type variables or
270 mkIdInstEnv :: [([TauType],Id)] -> IdInstEnv
272 mkIdInstEnv [] = nullMEnv
273 mkIdInstEnv ((tys,id) : rest)
275 inst_env = mkIdInstEnv rest
277 case (insertMEnv matchTys inst_env tys template) of
278 Succeeded inst_env' -> inst_env'
279 Failed _ -> panic "Failed in mkIdInstEnv"
281 template = MkInstTemplate id [] []
285 %************************************************************************
287 \subsection[InstEnv-lookup]{Performing lookup}
289 %************************************************************************
292 lookupInst :: SplitUniqSupply
294 -> Maybe (TypecheckedExpr,
297 lookupInst uniqs (Dict _ clas ty orig)
298 = if isTyVarTy ty then
299 Nothing -- No instances of a class at a type variable
301 case (lookupMEnv matchTy inst_env ty) of
303 Just (_,tenv,templ) -> Just (instTemplate uniqs orig tenv templ)
308 -- During deriving and instance specialisation operations
309 -- we can't get the instances of the class from inside the
310 -- class, because the latter ain't ready yet. Instead we
311 -- find a mapping from classes to envts inside the dict origin.
312 -- (A Simon hack [WDP])
314 DerivingOrigin inst_mapper _ _ _ _ -> fst (inst_mapper clas)
316 InstanceSpecOrigin inst_mapper _ _ _ -> fst (inst_mapper clas)
318 -- Usually we just get the instances of the class from
319 -- inside the class itself.
321 other -> getClassInstEnv clas
323 lookupInst uniqs (Method _ id tys orig)
324 = if (all isTyVarTy tys) then
325 general_case -- Instance types are all type variables, so there can't be
326 -- a special instance for this method
328 else -- Get the inst env from the Id, and look up in it
329 case (lookupSpecEnv (getIdSpecialisation id) tys) of
330 Nothing -> general_case
331 Just (spec_id, types_left, num_dicts_to_toss)
332 -> Just (instMethod uniqs orig spec_id types_left)
334 general_case = Just (instMethod uniqs orig id tys)
337 Now "overloaded" literals: the plain truth is that the compiler
338 is intimately familiar w/ the types Int, Integer, Float, and Double;
339 for everything else, we actually conjure up an appropriately-applied
340 fromInteger/fromRational, as the Haskell report suggests.
343 lookupInst uniqs (LitInst u (OverloadedIntegral i from_int from_integer) ty orig)
345 case (getUniDataTyCon_maybe ty) of -- this way is *unflummoxed* by synonyms
347 | tycon == intPrimTyCon -> (intprim_lit, [])
348 | tycon == doublePrimTyCon -> (doubleprim_lit, [])
349 | tycon == intTyCon -> (int_lit, [])
350 | tycon == doubleTyCon -> (double_lit, [])
351 | tycon == floatTyCon -> (float_lit, [])
352 -- | tycon == wordTyCon -> (word_lit, [])
353 -- | tycon == addrTyCon -> (addr_lit, [])
357 if (i >= toInteger minInt && i <= toInteger maxInt) then
358 -- It's overloaded but small enough to fit into an Int
360 let u2 = getSUnique uniqs
361 method = Method u2 from_int [ty] orig
363 (App (Var (mkInstId method)) int_lit, [method])
366 -- Alas, it is overloaded and a big literal!
368 let u2 = getSUnique uniqs
369 method = Method u2 from_integer [ty] orig
371 (App (Var (mkInstId method)) (Lit (IntLit i)), [method])
374 #if __GLASGOW_HASKELL__ <= 22
375 iD = ((fromInteger i) :: Double)
377 iD = ((fromInteger i) :: Rational)
379 intprim_lit = Lit (IntPrimLit i)
380 doubleprim_lit = Lit (DoublePrimLit iD)
381 int_lit = App (Var intDataCon) intprim_lit
382 double_lit = App (Var doubleDataCon) doubleprim_lit
383 float_lit = App (Var floatDataCon) (Lit (FloatPrimLit iD))
384 -- word_lit = App (Var wordDataCon) intprim_lit
385 -- addr_lit = App (Var addrDataCon) intprim_lit
387 lookupInst uniqs (LitInst u (OverloadedFractional f from_rational) ty orig)
389 case (getUniDataTyCon_maybe ty) of -- this way is *unflummoxed* by synonyms
391 | tycon == doublePrimTyCon -> (doubleprim_lit, [])
392 | tycon == doubleTyCon -> (double_lit, [])
393 | tycon == floatTyCon -> (float_lit, [])
395 _ {-otherwise-} -> -- gotta fromRational it...
396 --pprTrace "lookupInst:fractional lit ty?:" (ppr PprDebug ty) (
398 u2 = getSUnique uniqs
399 method = Method u2 from_rational [ty] orig
401 (App (Var (mkInstId method)) (Lit (FracLit f)), [method])
405 #if __GLASGOW_HASKELL__ <= 22
406 fD = ((fromRational f) :: Double)
410 doubleprim_lit = Lit (DoublePrimLit fD)
411 double_lit = App (Var doubleDataCon) doubleprim_lit
412 float_lit = App (Var floatDataCon) (Lit (FloatPrimLit fD))
415 There is a second, simpler interface, when you want an instance
416 of a class at a given nullary type constructor. It just returns
417 the appropriate dictionary if it exists. It is used only when resolving
418 ambiguous dictionaries.
421 lookupClassInstAtSimpleType :: Class -> UniType -> Maybe Id
423 lookupClassInstAtSimpleType clas ty
424 = case (lookupMEnv matchTy (getClassInstEnv clas) ty) of
426 Just (_,_,MkInstTemplate dict [] []) -> Just dict
429 Notice in the above that the type constructors in the default list
430 should all have arity zero, so there should be no type variables
431 or thetas in the instance declaration.
433 There's yet a third interface for Insts which need no binding.
434 They are used to record constraints on type variables, notably
435 for CCall arguments and results.
438 lookupNoBindInst :: SplitUniqSupply
442 lookupNoBindInst uniqs (Dict _ clas ty orig)
443 = if isTyVarTy ty then
444 Nothing -- No instances of a class at a type variable
446 case (lookupMEnv matchTy inst_env ty) of
448 Just (_,tenv,templ) ->
449 case (instTemplate uniqs orig tenv templ) of
452 -- The idea here is that the expression built by
453 -- instTemplate isn't relevant; indeed, it might well
454 -- be a place-holder bottom value.
456 inst_env = getClassInstEnv clas
459 %************************************************************************
461 \subsection[MatchEnv]{Matching environments}
463 %************************************************************************
465 ``Matching'' environments allow you to bind a template to a value;
466 when you look up in it, you supply a value which is matched against
470 type MatchEnv key value = [(key, value)]
473 For now we just use association lists. The list is maintained sorted
474 in order of {\em decreasing specificness} of @key@, so that the first
475 match will be the most specific.
478 nullMEnv :: MatchEnv a b
481 mkMEnv :: [(key, value)] -> MatchEnv key value
485 @lookupMEnv@ looks up in a @MatchEnv@.
487 simply takes the first match, should be the most specific.
490 lookupMEnv :: (key {- template -} -> -- Matching function
491 key {- instance -} ->
493 -> MatchEnv key value -- The envt
495 -> Maybe (key, -- Template
496 match_info, -- Match info returned by matching fn
499 lookupMEnv key_match alist key
503 find ((tpl, val) : rest)
504 = case key_match tpl key of
506 Just match_info -> Just (tpl, match_info, val)
509 @insertMEnv@ extends a match environment, checking for overlaps.
512 insertMEnv :: (key {- template -} -> -- Matching function
513 key {- instance -} ->
515 -> MatchEnv key value -- Envt
516 -> key -> value -- New item
517 -> MaybeErr (MatchEnv key value) -- Success...
518 (key, value) -- Failure: Offending overlap
520 insertMEnv match_fn alist key value
523 -- insert has to put the new item in BEFORE any keys which are
524 -- LESS SPECIFIC than the new key, and AFTER any keys which are
525 -- MORE SPECIFIC The list is maintained in specific-ness order, so
526 -- we just stick it in either last, or just before the first key
527 -- of which the new key is an instance. We check for overlap at
530 insert [] = returnMaB [(key, value)]
531 insert ((t,v) : rest)
532 = case (match_fn t key) of
534 -- New key is not an instance of this existing one, so
535 -- continue down the list.
536 insert rest `thenMaB` (\ rest' ->
537 returnMaB ((t,v):rest') )
540 -- New key *is* an instance of the old one, so check the
541 -- other way round in case of identity.
543 case (match_fn key t) of
544 Just _ -> failMaB (t,v)
547 Nothing -> returnMaB ((key,value):(t,v):rest)
548 -- All ok; insert here