2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[InstEnv]{Utilities for typechecking instance declarations}
6 The bits common to TcInstDcls and TcDeriv.
10 DFunId, ClsInstEnv, InstEnv,
12 emptyInstEnv, extendInstEnv,
13 lookupInstEnv, InstLookupResult(..),
14 classInstEnv, simpleDFunClassTyCon
17 #include "HsVersions.h"
19 import Class ( Class )
21 import VarSet ( TyVarSet, unionVarSet, mkVarSet )
22 import VarEnv ( TyVarSubstEnv )
23 import Maybes ( MaybeErr(..), returnMaB, failMaB, thenMaB, maybeToBool )
24 import Name ( getSrcLoc )
25 import Type ( Type, splitTyConApp_maybe,
26 splitSigmaTy, splitDFunTy, tyVarsOfTypes
29 import DataCon ( DataCon )
30 import TyCon ( TyCon )
32 import Unify ( matchTys, unifyTyListsX )
33 import UniqFM ( UniqFM, lookupWithDefaultUFM, addToUFM, emptyUFM )
35 import ErrUtils ( Message )
40 %************************************************************************
42 \subsection{The key types}
44 %************************************************************************
49 type InstEnv = UniqFM ClsInstEnv -- Maps Class to instances for that class
51 type ClsInstEnv = [(TyVarSet, [Type], DFunId)] -- The instances for a particular class
53 simpleDFunClassTyCon :: DFunId -> (Class, TyCon)
54 simpleDFunClassTyCon dfun
57 (_,_,clas,[ty]) = splitDFunTy (idType dfun)
58 tycon = case splitTyConApp_maybe ty of
59 Just (tycon,_) -> tycon
62 %************************************************************************
64 \subsection{Instance environments: InstEnv and ClsInstEnv}
66 %************************************************************************
68 The actual type declarations are in HscTypes.
71 emptyInstEnv :: InstEnv
72 emptyInstEnv = emptyUFM
74 classInstEnv :: InstEnv -> Class -> ClsInstEnv
75 classInstEnv env cls = lookupWithDefaultUFM env [] cls
78 A @ClsInstEnv@ lives inside a class, and identifies all the instances
79 of that class. The @Id@ inside a ClsInstEnv mapping is the dfun for
82 If class C maps to a list containing the item ([a,b], [t1,t2,t3], dfun), then
84 forall a b, C t1 t2 t3 can be constructed by dfun
86 or, to put it another way, we have
88 instance (...) => C t1 t2 t3, witnessed by dfun
90 There is an important consistency constraint in the elements of a ClsInstEnv:
92 * [a,b] must be a superset of the free vars of [t1,t2,t3]
94 * The dfun must itself be quantified over [a,b]
96 Thus, the @ClassInstEnv@ for @Eq@ might contain the following entry:
97 [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
98 The "a" in the pattern must be one of the forall'd variables in
103 Notes on overlapping instances
104 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
105 In some ClsInstEnvs, overlap is prohibited; that is, no pair of templates unify.
107 In others, overlap is permitted, but only in such a way that one can make
108 a unique choice when looking up. That is, overlap is only permitted if
109 one template matches the other, or vice versa. So this is ok:
117 If overlap is permitted, the list is kept most specific first, so that
118 the first lookup is the right choice.
121 For now we just use association lists.
123 \subsection{Avoiding a problem with overlapping}
125 Consider this little program:
128 class C a where c :: a
129 class C a => D a where d :: a
131 instance C Int where c = 17
132 instance D Int where d = 13
134 instance C a => C [a] where c = [c]
135 instance ({- C [a], -} D a) => D [a] where d = c
137 instance C [Int] where c = [37]
139 main = print (d :: [Int])
142 What do you think `main' prints (assuming we have overlapping instances, and
143 all that turned on)? Well, the instance for `D' at type `[a]' is defined to
144 be `c' at the same type, and we've got an instance of `C' at `[Int]', so the
145 answer is `[37]', right? (the generic `C [a]' instance shouldn't apply because
146 the `C [Int]' instance is more specific).
148 Ghc-4.04 gives `[37]', while ghc-4.06 gives `[17]', so 4.06 is wrong. That
149 was easy ;-) Let's just consult hugs for good measure. Wait - if I use old
150 hugs (pre-September99), I get `[17]', and stranger yet, if I use hugs98, it
151 doesn't even compile! What's going on!?
153 What hugs complains about is the `D [a]' instance decl.
156 ERROR "mj.hs" (line 10): Cannot build superclass instance
158 *** Context supplied : D a
159 *** Required superclass : C [a]
162 You might wonder what hugs is complaining about. It's saying that you
163 need to add `C [a]' to the context of the `D [a]' instance (as appears
164 in comments). But there's that `C [a]' instance decl one line above
165 that says that I can reduce the need for a `C [a]' instance to the
166 need for a `C a' instance, and in this case, I already have the
167 necessary `C a' instance (since we have `D a' explicitly in the
168 context, and `C' is a superclass of `D').
170 Unfortunately, the above reasoning indicates a premature commitment to the
171 generic `C [a]' instance. I.e., it prematurely rules out the more specific
172 instance `C [Int]'. This is the mistake that ghc-4.06 makes. The fix is to
173 add the context that hugs suggests (uncomment the `C [a]'), effectively
174 deferring the decision about which instance to use.
176 Now, interestingly enough, 4.04 has this same bug, but it's covered up
177 in this case by a little known `optimization' that was disabled in
178 4.06. Ghc-4.04 silently inserts any missing superclass context into
179 an instance declaration. In this case, it silently inserts the `C
180 [a]', and everything happens to work out.
182 (See `basicTypes/MkId:mkDictFunId' for the code in question. Search for
183 `Mark Jones', although Mark claims no credit for the `optimization' in
184 question, and would rather it stopped being called the `Mark Jones
187 So, what's the fix? I think hugs has it right. Here's why. Let's try
188 something else out with ghc-4.04. Let's add the following line:
193 Everyone raise their hand who thinks that `d :: [Int]' should give a
194 different answer from `d' :: [Int]'. Well, in ghc-4.04, it does. The
195 `optimization' only applies to instance decls, not to regular
196 bindings, giving inconsistent behavior.
198 Old hugs had this same bug. Here's how we fixed it: like GHC, the
199 list of instances for a given class is ordered, so that more specific
200 instances come before more generic ones. For example, the instance
201 list for C might contain:
202 ..., C Int, ..., C a, ...
203 When we go to look for a `C Int' instance we'll get that one first.
204 But what if we go looking for a `C b' (`b' is unconstrained)? We'll
205 pass the `C Int' instance, and keep going. But if `b' is
206 unconstrained, then we don't know yet if the more specific instance
207 will eventually apply. GHC keeps going, and matches on the generic `C
208 a'. The fix is to, at each step, check to see if there's a reverse
209 match, and if so, abort the search. This prevents hugs from
210 prematurely chosing a generic instance when a more specific one
216 @lookupInstEnv@ looks up in a @InstEnv@, using a one-way match. Since
217 the env is kept ordered, the first match must be the only one. The
218 thing we are looking up can have an arbitrary "flexi" part.
221 lookupInstEnv :: InstEnv -- The envt
222 -> Class -> [Type] -- Key
225 data InstLookupResult
226 = FoundInst -- There is a (template,substitution) pair
227 -- that makes the template match the key,
228 -- and no template is an instance of the key
231 | NoMatch Bool -- Boolean is true iff there is at least one
232 -- template that matches the key.
233 -- (but there are other template(s) that are
234 -- instances of the key, so we don't report
236 -- The NoMatch True case happens when we look up
238 -- in an InstEnv that has entries for
241 -- Then which we choose would depend on the way in which 'a'
242 -- is instantiated. So we say there is no match, but identify
243 -- it as ambiguous case in the hope of giving a better error msg.
244 -- See the notes above from Jeff Lewis
246 lookupInstEnv env key_cls key_tys
247 = find (classInstEnv env key_cls)
249 key_vars = tyVarsOfTypes key_tys
251 find [] = NoMatch False
252 find ((tpl_tyvars, tpl, val) : rest)
253 = case matchTys tpl_tyvars tpl key_tys of
255 case matchTys key_vars key_tys tpl of
257 Just (_, _) -> NoMatch (any_match rest)
258 Just (subst, leftovers) -> ASSERT( null leftovers )
261 any_match rest = or [ maybeToBool (matchTys tvs tpl key_tys)
262 | (tvs,tpl,_) <- rest
266 @addToClsInstEnv@ extends a @ClsInstEnv@, checking for overlaps.
268 A boolean flag controls overlap reporting.
270 True => overlap is permitted, but only if one template matches the other;
271 not if they unify but neither is
274 extendInstEnv :: DynFlags -> InstEnv -> [DFunId] -> (InstEnv, [Message])
275 -- Similar, but all we have is the DFuns
276 extendInstEnv dflags env infos
279 go env msgs [] = (env, msgs)
280 go env msgs (dfun:dfuns) = case addToInstEnv dflags env dfun of
281 Succeeded new_env -> go new_env msgs dfuns
282 Failed dfun' -> go env (msg:msgs) dfuns
284 msg = dupInstErr dfun dfun'
287 dupInstErr dfun1 dfun2
288 -- Overlapping/duplicate instances for given class; msg could be more glamourous
289 = hang (ptext SLIT("Duplicate or overlapping instance declarations:"))
290 2 (ppr_dfun dfun1 $$ ppr_dfun dfun2)
292 ppr_dfun dfun = ppr (getSrcLoc dfun) <> colon <+> ppr tau
294 (_,_,tau) = splitSigmaTy (idType dfun)
296 addToInstEnv :: DynFlags
298 -> MaybeErr InstEnv -- Success...
299 DFunId -- Failure: Offending overlap
301 addToInstEnv dflags inst_env dfun_id
302 = case insert_into (classInstEnv inst_env clas) of
303 Failed stuff -> Failed stuff
304 Succeeded new_env -> Succeeded (addToUFM inst_env clas new_env)
307 (ins_tvs, _, clas, ins_tys) = splitDFunTy (idType dfun_id)
309 ins_tv_set = mkVarSet ins_tvs
310 ins_item = (ins_tv_set, ins_tys, dfun_id)
312 insert_into [] = returnMaB [ins_item]
313 insert_into env@(cur_item@(tpl_tvs, tpl_tys, val) : rest)
316 -- (a) they are the same, or
317 -- (b) they unify, and any sort of overlap is prohibited,
318 -- (c) they unify but neither is more specific than t'other
320 || (unifiable && not (dopt Opt_AllowOverlappingInstances dflags))
321 || (unifiable && not (ins_item_more_specific || cur_item_more_specific))
324 -- New item is an instance of current item, so drop it here
325 | ins_item_more_specific = returnMaB (ins_item : env)
327 -- Otherwise carry on
328 | otherwise = insert_into rest `thenMaB` \ rest' ->
329 returnMaB (cur_item : rest')
331 unifiable = maybeToBool (unifyTyListsX (ins_tv_set `unionVarSet` tpl_tvs) tpl_tys ins_tys)
332 ins_item_more_specific = maybeToBool (matchTys tpl_tvs tpl_tys ins_tys)
333 cur_item_more_specific = maybeToBool (matchTys ins_tv_set ins_tys tpl_tys)
334 identical = ins_item_more_specific && cur_item_more_specific