2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 \section[TcInstUtil]{Utilities for typechecking instance declarations}
6 The bits common to TcInstDcls and TcDeriv.
10 InstInfo(..), pprInstInfo,
11 instInfoClass, simpleInstInfoTy, simpleInstInfoTyCon,
13 -- Instance environment
14 InstEnv, emptyInstEnv, buildInstanceEnv,
15 lookupInstEnv, InstLookupResult(..),
16 classInstEnv, classDataCon
19 #include "HsVersions.h"
21 import RnHsSyn ( RenamedMonoBinds, RenamedSig )
22 import HsTypes ( toHsType )
24 import CmdLineOpts ( opt_AllowOverlappingInstances )
26 --import TcEnv ( InstEnv, emptyInstEnv, addToInstEnv )
27 import Bag ( bagToList, Bag )
28 import Class ( Class )
29 import Var ( TyVar, Id, idName )
30 import Maybes ( MaybeErr(..) )
31 import Name ( getSrcLoc, nameModule, isLocallyDefined, toRdrName )
32 import SrcLoc ( SrcLoc )
33 import Type ( Type, ThetaType, splitTyConApp_maybe, mkSigmaTy, mkDictTy )
34 import PprType ( pprConstraint )
35 import Class ( classTyCon )
36 import DataCon ( DataCon )
37 import TyCon ( TyCon, tyConDataCons )
43 %************************************************************************
45 \subsection{The InstInfo type}
47 %************************************************************************
49 The InstInfo type summarises the information in an instance declaration
51 instance c => k (t tvs) where b
57 [TyVar] -- Type variables, tvs
58 [Type] -- The types at which the class is being instantiated
59 ThetaType -- inst_decl_theta: the original context, c, from the
60 -- instance declaration. It constrains (some of)
63 RenamedMonoBinds -- Bindings, b
64 SrcLoc -- Source location assoc'd with this instance's defn
65 [RenamedSig] -- User pragmas recorded for generating specialised instances
67 pprInstInfo (InstInfo clas tvs tys inst_decl_theta _ mbinds _ _)
68 = vcat [ptext SLIT("InstInfo:") <+> ppr (mkSigmaTy tvs inst_decl_theta (mkDictTy clas tys)),
71 instInfoClass :: InstInfo -> Class
72 instInfoClass (InstInfo clas _ _ _ _ _ _ _) = clas
74 simpleInstInfoTy :: InstInfo -> Type
75 simpleInstInfoTy (InstInfo _ _ [ty] _ _ _ _ _) = ty
77 simpleInstInfoTyCon :: InstInfo -> TyCon
78 -- Gets the type constructor for a simple instance declaration,
79 -- i.e. one of the form instance (...) => C (T a b c) where ...
80 simpleInstInfoTyCon inst
81 = case splitTyConApp_maybe (simpleInstInfoTy inst) of
82 Just (tycon, _) -> tycon
86 A tiny function which doesn't belong anywhere else.
87 It makes a nasty mutual-recursion knot if you put it in Class.
90 classDataCon :: Class -> DataCon
91 classDataCon clas = case tyConDataCons (classTyCon clas) of
92 (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr
95 %************************************************************************
97 \subsection{Converting instance info into suitable InstEnvs}
99 %************************************************************************
102 buildInstanceEnv :: Bag InstInfo -> NF_TcM InstEnv
104 buildInstanceEnv info = --pprTrace "BuildInstanceEnv" (ppr info)
105 foldrNF_Tc addClassInstance emptyInstEnv (bagToList info)
108 @addClassInstance@ adds the appropriate stuff to the @ClassInstEnv@
109 based on information from a single instance declaration. It complains
110 about any overlap with an existing instance.
119 (InstInfo clas inst_tyvars inst_tys _
122 = -- Add the instance to the class's instance environment
123 case addToInstEnv opt_AllowOverlappingInstances
124 inst_env clas inst_tyvars inst_tys dfun_id of
125 Failed (tys', dfun_id') -> addErrTc (dupInstErr clas (inst_tys, dfun_id)
130 Succeeded inst_env' -> returnNF_Tc inst_env'
134 dupInstErr clas info1@(tys1, dfun1) info2@(tys2, dfun2)
135 -- Overlapping/duplicate instances for given class; msg could be more glamourous
136 = hang (ptext SLIT("Duplicate or overlapping instance declarations"))
137 4 (sep [ptext SLIT("for") <+> quotes (pprConstraint clas tys1),
138 nest 4 (sep [ppr_loc dfun1, ptext SLIT("and") <+> ppr_loc dfun2])])
141 | isLocallyDefined dfun = ptext SLIT("defined at") <+> ppr (getSrcLoc dfun)
142 | otherwise = ptext SLIT("imported from module") <+> quotes (ppr (nameModule (idName dfun)))
146 %************************************************************************
148 \subsection{Instance environments: InstEnv and ClsInstEnv}
150 %************************************************************************
152 The actual type declarations are in HscTypes.
155 emptyInstEnv :: InstEnv
156 emptyInstEnv = emptyUFM
158 classInstEnv :: InstEnv -> Class -> ClsInstEnv
159 classInstEnv env cls = lookupWithDefaultUFM env [] cls
162 A @ClsInstEnv@ lives inside a class, and identifies all the instances
163 of that class. The @Id@ inside a ClsInstEnv mapping is the dfun for
166 If class C maps to a list containing the item ([a,b], [t1,t2,t3], dfun), then
168 forall a b, C t1 t2 t3 can be constructed by dfun
170 or, to put it another way, we have
172 instance (...) => C t1 t2 t3, witnessed by dfun
174 There is an important consistency constraint in the elements of a ClsInstEnv:
176 * [a,b] must be a superset of the free vars of [t1,t2,t3]
178 * The dfun must itself be quantified over [a,b]
180 Thus, the @ClassInstEnv@ for @Eq@ might contain the following entry:
181 [a] ===> dfun_Eq_List :: forall a. Eq a => Eq [a]
182 The "a" in the pattern must be one of the forall'd variables in
187 Notes on overlapping instances
188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189 In some ClsInstEnvs, overlap is prohibited; that is, no pair of templates unify.
191 In others, overlap is permitted, but only in such a way that one can make
192 a unique choice when looking up. That is, overlap is only permitted if
193 one template matches the other, or vice versa. So this is ok:
201 If overlap is permitted, the list is kept most specific first, so that
202 the first lookup is the right choice.
205 For now we just use association lists.
207 \subsection{Avoiding a problem with overlapping}
209 Consider this little program:
212 class C a where c :: a
213 class C a => D a where d :: a
215 instance C Int where c = 17
216 instance D Int where d = 13
218 instance C a => C [a] where c = [c]
219 instance ({- C [a], -} D a) => D [a] where d = c
221 instance C [Int] where c = [37]
223 main = print (d :: [Int])
226 What do you think `main' prints (assuming we have overlapping instances, and
227 all that turned on)? Well, the instance for `D' at type `[a]' is defined to
228 be `c' at the same type, and we've got an instance of `C' at `[Int]', so the
229 answer is `[37]', right? (the generic `C [a]' instance shouldn't apply because
230 the `C [Int]' instance is more specific).
232 Ghc-4.04 gives `[37]', while ghc-4.06 gives `[17]', so 4.06 is wrong. That
233 was easy ;-) Let's just consult hugs for good measure. Wait - if I use old
234 hugs (pre-September99), I get `[17]', and stranger yet, if I use hugs98, it
235 doesn't even compile! What's going on!?
237 What hugs complains about is the `D [a]' instance decl.
240 ERROR "mj.hs" (line 10): Cannot build superclass instance
242 *** Context supplied : D a
243 *** Required superclass : C [a]
246 You might wonder what hugs is complaining about. It's saying that you
247 need to add `C [a]' to the context of the `D [a]' instance (as appears
248 in comments). But there's that `C [a]' instance decl one line above
249 that says that I can reduce the need for a `C [a]' instance to the
250 need for a `C a' instance, and in this case, I already have the
251 necessary `C a' instance (since we have `D a' explicitly in the
252 context, and `C' is a superclass of `D').
254 Unfortunately, the above reasoning indicates a premature commitment to the
255 generic `C [a]' instance. I.e., it prematurely rules out the more specific
256 instance `C [Int]'. This is the mistake that ghc-4.06 makes. The fix is to
257 add the context that hugs suggests (uncomment the `C [a]'), effectively
258 deferring the decision about which instance to use.
260 Now, interestingly enough, 4.04 has this same bug, but it's covered up
261 in this case by a little known `optimization' that was disabled in
262 4.06. Ghc-4.04 silently inserts any missing superclass context into
263 an instance declaration. In this case, it silently inserts the `C
264 [a]', and everything happens to work out.
266 (See `basicTypes/MkId:mkDictFunId' for the code in question. Search for
267 `Mark Jones', although Mark claims no credit for the `optimization' in
268 question, and would rather it stopped being called the `Mark Jones
271 So, what's the fix? I think hugs has it right. Here's why. Let's try
272 something else out with ghc-4.04. Let's add the following line:
277 Everyone raise their hand who thinks that `d :: [Int]' should give a
278 different answer from `d' :: [Int]'. Well, in ghc-4.04, it does. The
279 `optimization' only applies to instance decls, not to regular
280 bindings, giving inconsistent behavior.
282 Old hugs had this same bug. Here's how we fixed it: like GHC, the
283 list of instances for a given class is ordered, so that more specific
284 instances come before more generic ones. For example, the instance
285 list for C might contain:
286 ..., C Int, ..., C a, ...
287 When we go to look for a `C Int' instance we'll get that one first.
288 But what if we go looking for a `C b' (`b' is unconstrained)? We'll
289 pass the `C Int' instance, and keep going. But if `b' is
290 unconstrained, then we don't know yet if the more specific instance
291 will eventually apply. GHC keeps going, and matches on the generic `C
292 a'. The fix is to, at each step, check to see if there's a reverse
293 match, and if so, abort the search. This prevents hugs from
294 prematurely chosing a generic instance when a more specific one
300 @lookupInstEnv@ looks up in a @InstEnv@, using a one-way match. Since
301 the env is kept ordered, the first match must be the only one. The
302 thing we are looking up can have an arbitrary "flexi" part.
305 lookupInstEnv :: InstEnv -- The envt
306 -> Class -> [Type] -- Key
309 data InstLookupResult
310 = FoundInst -- There is a (template,substitution) pair
311 -- that makes the template match the key,
312 -- and no template is an instance of the key
315 | NoMatch Bool -- Boolean is true iff there is at least one
316 -- template that matches the key.
317 -- (but there are other template(s) that are
318 -- instances of the key, so we don't report
320 -- The NoMatch True case happens when we look up
322 -- in an InstEnv that has entries for
325 -- Then which we choose would depend on the way in which 'a'
326 -- is instantiated. So we say there is no match, but identify
327 -- it as ambiguous case in the hope of giving a better error msg.
328 -- See the notes above from Jeff Lewis
330 lookupInstEnv env key_cls key_tys
331 = find (classInstEnv env key_cls)
333 key_vars = tyVarsOfTypes key_tys
335 find [] = NoMatch False
336 find ((tpl_tyvars, tpl, val) : rest)
337 = case matchTys tpl_tyvars tpl key_tys of
339 case matchTys key_vars key_tys tpl of
341 Just (_, _) -> NoMatch (any_match rest)
342 Just (subst, leftovers) -> ASSERT( null leftovers )
345 any_match rest = or [ maybeToBool (matchTys tvs tpl key_tys)
346 | (tvs,tpl,_) <- rest
350 @addToClsInstEnv@ extends a @ClsInstEnv@, checking for overlaps.
352 A boolean flag controls overlap reporting.
354 True => overlap is permitted, but only if one template matches the other;
355 not if they unify but neither is
358 addToInstEnv :: Bool -- True <=> overlap permitted
360 -> Class -> [TyVar] -> [Type] -> Id -- New item
361 -> MaybeErr InstEnv -- Success...
362 ([Type], Id) -- Failure: Offending overlap
364 addToInstEnv overlap_ok inst_env clas ins_tvs ins_tys value
365 = case insert_into (classInstEnv inst_env clas) of
366 Failed stuff -> Failed stuff
367 Succeeded new_env -> Succeeded (addToUFM inst_env clas new_env)
370 ins_tv_set = mkVarSet ins_tvs
371 ins_item = (ins_tv_set, ins_tys, value)
373 insert_into [] = returnMaB [ins_item]
374 insert_into env@(cur_item@(tpl_tvs, tpl_tys, val) : rest)
377 -- (a) they are the same, or
378 -- (b) they unify, and any sort of overlap is prohibited,
379 -- (c) they unify but neither is more specific than t'other
381 || (unifiable && not overlap_ok)
382 || (unifiable && not (ins_item_more_specific || cur_item_more_specific))
383 = failMaB (tpl_tys, val)
385 -- New item is an instance of current item, so drop it here
386 | ins_item_more_specific = returnMaB (ins_item : env)
388 -- Otherwise carry on
389 | otherwise = insert_into rest `thenMaB` \ rest' ->
390 returnMaB (cur_item : rest')
392 unifiable = maybeToBool (unifyTyListsX (ins_tv_set `unionVarSet` tpl_tvs) tpl_tys ins_tys)
393 ins_item_more_specific = maybeToBool (matchTys tpl_tvs tpl_tys ins_tys)
394 cur_item_more_specific = maybeToBool (matchTys ins_tv_set ins_tys tpl_tys)
395 identical = ins_item_more_specific && cur_item_more_specific