2 % (c) The GRASP/AQUA Project, Glasgow University, 1993-1998
4 \section{Class Instance environments}
8 InstEnv, emptyInstEnv, addToInstEnv, lookupInstEnv
11 #include "HsVersions.h"
13 import Var ( TyVar, Id )
15 import VarEnv ( TyVarSubstEnv )
16 import Type ( Type, tyVarsOfTypes )
17 import Unify ( unifyTyListsX, matchTys )
23 %************************************************************************
27 %************************************************************************
30 type InstEnv = [(TyVarSet, [Type], Id)]
33 In some InstEnvs overlap is prohibited; that is, no pair of templates unify.
35 In others, overlap is permitted, but only in such a way that one can make
36 a unique choice when looking up. That is, overlap is only permitted if
37 one template matches the other, or vice versa. So this is ok:
45 If overlap is permitted, the list is kept most specific first, so that
46 the first lookup is the right choice.
49 For now we just use association lists.
51 \subsection{Avoiding a problem with overlapping}
53 Consider this little program:
56 class C a where c :: a
57 class C a => D a where d :: a
59 instance C Int where c = 17
60 instance D Int where d = 13
62 instance C a => C [a] where c = [c]
63 instance ({- C [a], -} D a) => D [a] where d = c
65 instance C [Int] where c = [37]
67 main = print (d :: [Int])
70 What do you think `main' prints (assuming we have overlapping instances, and
71 all that turned on)? Well, the instance for `D' at type `[a]' is defined to
72 be `c' at the same type, and we've got an instance of `C' at `[Int]', so the
73 answer is `[37]', right? (the generic `C [a]' instance shouldn't apply because
74 the `C [Int]' instance is more specific).
76 Ghc-4.04 gives `[37]', while ghc-4.06 gives `[17]', so 4.06 is wrong. That
77 was easy ;-) Let's just consult hugs for good measure. Wait - if I use old
78 hugs (pre-September99), I get `[17]', and stranger yet, if I use hugs98, it
79 doesn't even compile! What's going on!?
81 What hugs complains about is the `D [a]' instance decl.
84 ERROR "mj.hs" (line 10): Cannot build superclass instance
86 *** Context supplied : D a
87 *** Required superclass : C [a]
90 You might wonder what hugs is complaining about. It's saying that you need to
91 add `C [a]' to the context of the `D [a]' instance (as appears in comments).
92 But there's that `C [a]' instance decl one line above that says that I can
93 reduce the need for a `C [a]' instance to the need for a `C a' instance, and
94 in this case, I already have the necessary `C a' instance (since we have `D a'
95 explicitly in the context, and `C' is a superclass of `D').
97 Unfortunately, the above reasoning indicates a premature commitment to the
98 generic `C [a]' instance. I.e., it prematurely rules out the more specific
99 instance `C [Int]'. This is the mistake that ghc-4.06 makes. The fix is to
100 add the context that hugs suggests (uncomment the `C [a]'), effectively
101 deferring the decision about which instance to use.
103 Now, interestingly enough, 4.04 has this same bug, but it's covered up in this
104 case by a little known `optimization' that was disabled in 4.06. Ghc-4.04
105 silently inserts any missing superclass context into an instance declaration.
106 In this case, it silently inserts the `C [a]', and everything happens to work
109 (See `basicTypes/MkId:mkDictFunId' for the code in question. Search for
110 `Mark Jones', although Mark claims no credit for the `optimization' in
111 question, and would rather it stopped being called the `Mark Jones
114 So, what's the fix? I think hugs has it right. Here's why. Let's try
115 something else out with ghc-4.04. Let's add the following line:
120 Everyone raise their hand who thinks that `d :: [Int]' should give a different
121 answer from `d' :: [Int]'. Well, in ghc-4.04, it does. The `optimization'
122 only applies to instance decls, not to regular bindings, giving inconsistent
125 Old hugs had this same bug. Here's how we fixed it: like GHC, the list of
126 instances for a given class is ordered, so that more specific instances come
127 before more generic ones. For example, the instance list for C might contain:
128 ..., C Int, ..., C a, ...
129 When we go to look for a `C Int' instance we'll get that one first. But what
130 if we go looking for a `C b' (`b' is unconstrained)? We'll pass the `C Int'
131 instance, and keep going. But if `b' is unconstrained, then we don't know yet
132 if the more specific instance will eventually apply. GHC keeps going, and
133 matches on the generic `C a'. The fix is to, at each step, check to see if
134 there's a reverse match, and if so, abort the search. This prevents hugs
135 from prematurely chosing a generic instance when a more specific one exists.
140 emptyInstEnv :: InstEnv
143 isEmptyInstEnv env = null env
146 @lookupInstEnv@ looks up in a @InstEnv@, using a one-way match. Since the env is kept
147 ordered, the first match must be the only one.
148 The thing we are looking up can have an
149 arbitrary "flexi" part.
152 lookupInstEnv :: SDoc -- For error report
153 -> InstEnv -- The envt
155 -> Maybe (TyVarSubstEnv, Id)
157 lookupInstEnv doc env key
160 key_vars = tyVarsOfTypes key
162 find ((tpl_tyvars, tpl, val) : rest)
163 = case matchTys tpl_tyvars tpl key of
165 case matchTys key_vars key tpl of
167 Just (_, _) -> Nothing
168 Just (subst, leftovers) -> ASSERT( null leftovers )
172 @addToInstEnv@ extends a @InstEnv@, checking for overlaps.
174 A boolean flag controls overlap reporting.
176 True => overlap is permitted, but only if one template matches the other;
177 not if they unify but neither is
180 addToInstEnv :: Bool -- True <=> overlap permitted
182 -> [TyVar] -> [Type] -> Id -- New item
183 -> MaybeErr InstEnv -- Success...
184 ([Type], Id) -- Failure: Offending overlap
186 addToInstEnv overlap_ok env ins_tvs ins_tys value
189 ins_tv_set = mkVarSet ins_tvs
190 ins_item = (ins_tv_set, ins_tys, value)
192 insert [] = returnMaB [ins_item]
193 insert env@(cur_item@(tpl_tvs, tpl_tys, val) : rest)
196 -- (a) they are the same, or
197 -- (b) they unify, and any sort of overlap is prohibited,
198 -- (c) they unify but neither is more specific than t'other
200 || (unifiable && not overlap_ok)
201 || (unifiable && not (ins_item_more_specific || cur_item_more_specific))
202 = failMaB (tpl_tys, val)
204 -- New item is an instance of current item, so drop it here
205 | ins_item_more_specific = returnMaB (ins_item : env)
207 -- Otherwise carry on
208 | otherwise = insert rest `thenMaB` \ rest' ->
209 returnMaB (cur_item : rest')
211 unifiable = maybeToBool (unifyTyListsX (ins_tv_set `unionVarSet` tpl_tvs) tpl_tys ins_tys)
212 ins_item_more_specific = maybeToBool (matchTys tpl_tvs tpl_tys ins_tys)
213 cur_item_more_specific = maybeToBool (matchTys ins_tv_set ins_tys tpl_tys)
214 identical = ins_item_more_specific && cur_item_more_specific