[project @ 2000-10-13 14:14:31 by sewardj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcInstUtil.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[TcInstUtil]{Utilities for typechecking instance declarations}
5
6 The bits common to TcInstDcls and TcDeriv.
7
8 \begin{code}
9 module TcInstUtil (
10         InstInfo(..), pprInstInfo,
11         instInfoClass, simpleInstInfoTy, simpleInstInfoTyCon, 
12
13         -- Instance environment
14         InstEnv, emptyInstEnv, buildInstanceEnv,
15         lookupInstEnv, InstLookupResult(..),
16         classInstEnv, classDataCon
17     ) where
18
19 #include "HsVersions.h"
20
21 import RnHsSyn          ( RenamedMonoBinds, RenamedSig )
22 import HsTypes          ( toHsType )
23
24 import CmdLineOpts      ( opt_AllowOverlappingInstances )
25 import TcMonad
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 )
38 import Outputable
39 \end{code}
40
41
42
43 %************************************************************************
44 %*                                                                      *
45 \subsection{The InstInfo type}
46 %*                                                                      *
47 %************************************************************************
48
49 The InstInfo type summarises the information in an instance declaration
50
51     instance c => k (t tvs) where b
52
53 \begin{code}
54 data InstInfo
55   = InstInfo
56       Class             -- Class, k
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)
61                         --   the TyVars above
62       Id                -- The dfun id
63       RenamedMonoBinds  -- Bindings, b
64       SrcLoc            -- Source location assoc'd with this instance's defn
65       [RenamedSig]      -- User pragmas recorded for generating specialised instances
66
67 pprInstInfo (InstInfo clas tvs tys inst_decl_theta _ mbinds _ _)
68  = vcat [ptext SLIT("InstInfo:") <+> ppr (mkSigmaTy tvs inst_decl_theta (mkDictTy clas tys)),
69          nest 4 (ppr mbinds)]
70
71 instInfoClass :: InstInfo -> Class
72 instInfoClass (InstInfo clas _ _ _ _ _ _ _) = clas
73
74 simpleInstInfoTy :: InstInfo -> Type
75 simpleInstInfoTy (InstInfo _ _ [ty] _ _ _ _ _) = ty
76
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
83 \end{code}
84
85
86 A tiny function which doesn't belong anywhere else.
87 It makes a nasty mutual-recursion knot if you put it in Class.
88
89 \begin{code}
90 classDataCon :: Class -> DataCon
91 classDataCon clas = case tyConDataCons (classTyCon clas) of
92                       (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr 
93 \end{code}                    
94
95 %************************************************************************
96 %*                                                                      *
97 \subsection{Converting instance info into suitable InstEnvs}
98 %*                                                                      *
99 %************************************************************************
100
101 \begin{code}
102 buildInstanceEnv :: Bag InstInfo -> NF_TcM InstEnv
103
104 buildInstanceEnv info = --pprTrace "BuildInstanceEnv" (ppr info)
105                         foldrNF_Tc addClassInstance emptyInstEnv (bagToList info)
106 \end{code}
107
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.
111
112 \begin{code}
113 addClassInstance
114     :: InstInfo
115     -> InstEnv
116     -> NF_TcM InstEnv
117
118 addClassInstance 
119     (InstInfo clas inst_tyvars inst_tys _
120               dfun_id _ src_loc _)
121     inst_env
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) 
126                                                                 (tys',     dfun_id'))
127                                                 `thenNF_Tc_`
128                                      returnNF_Tc inst_env
129
130         Succeeded inst_env' -> returnNF_Tc inst_env'
131 \end{code}
132
133 \begin{code}
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])])
139   where
140     ppr_loc dfun
141         | isLocallyDefined dfun = ptext SLIT("defined at")           <+> ppr (getSrcLoc dfun)
142         | otherwise             = ptext SLIT("imported from module") <+> quotes (ppr (nameModule (idName dfun)))
143 \end{code}
144
145
146 %************************************************************************
147 %*                                                                      *
148 \subsection{Instance environments: InstEnv and ClsInstEnv}
149 %*                                                                      *
150 %************************************************************************
151
152 The actual type declarations are in HscTypes.
153
154 \begin{code}
155 emptyInstEnv :: InstEnv
156 emptyInstEnv = emptyUFM
157
158 classInstEnv :: InstEnv -> Class -> ClsInstEnv
159 classInstEnv env cls = lookupWithDefaultUFM env [] cls
160 \end{code}
161
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
164 that instance.  
165
166 If class C maps to a list containing the item ([a,b], [t1,t2,t3], dfun), then
167
168         forall a b, C t1 t2 t3  can be constructed by dfun
169
170 or, to put it another way, we have
171
172         instance (...) => C t1 t2 t3,  witnessed by dfun
173
174 There is an important consistency constraint in the elements of a ClsInstEnv:
175
176   * [a,b] must be a superset of the free vars of [t1,t2,t3]
177
178   * The dfun must itself be quantified over [a,b]
179
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
183 the dfun type.
184
185
186
187 Notes on overlapping instances
188 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
189 In some ClsInstEnvs, overlap is prohibited; that is, no pair of templates unify.
190
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:
194
195   [a]  [Int]
196
197 but this is not
198
199   (Int,a)  (b,Int)
200
201 If overlap is permitted, the list is kept most specific first, so that
202 the first lookup is the right choice.
203
204
205 For now we just use association lists.
206
207 \subsection{Avoiding a problem with overlapping}
208
209 Consider this little program:
210
211 \begin{pseudocode}
212      class C a        where c :: a
213      class C a => D a where d :: a
214
215      instance C Int where c = 17
216      instance D Int where d = 13
217
218      instance C a => C [a] where c = [c]
219      instance ({- C [a], -} D a) => D [a] where d = c
220
221      instance C [Int] where c = [37]
222
223      main = print (d :: [Int])
224 \end{pseudocode}
225
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).
231
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!?
236
237 What hugs complains about is the `D [a]' instance decl.
238
239 \begin{pseudocode}
240      ERROR "mj.hs" (line 10): Cannot build superclass instance
241      *** Instance            : D [a]
242      *** Context supplied    : D a
243      *** Required superclass : C [a]
244 \end{pseudocode}
245
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').
253
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.
259
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.
265
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
269 optimization' ;-)
270
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:
273
274     d' :: D a => [a]
275     d' = c
276
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.
281
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
295 exists.
296
297 --Jeff
298
299
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.
303
304 \begin{code}
305 lookupInstEnv :: InstEnv                        -- The envt
306               -> Class -> [Type]        -- Key
307               -> InstLookupResult
308
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
313         TyVarSubstEnv Id
314
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 
319                         --  FoundInst)
320         -- The NoMatch True case happens when we look up
321         --      Foo [a]
322         -- in an InstEnv that has entries for
323         --      Foo [Int]
324         --      Foo [b]
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
329
330 lookupInstEnv env key_cls key_tys
331   = find (classInstEnv env key_cls)
332   where
333     key_vars = tyVarsOfTypes key_tys
334
335     find [] = NoMatch False
336     find ((tpl_tyvars, tpl, val) : rest)
337       = case matchTys tpl_tyvars tpl key_tys of
338           Nothing                 ->
339             case matchTys key_vars key_tys tpl of
340               Nothing             -> find rest
341               Just (_, _)         -> NoMatch (any_match rest)
342           Just (subst, leftovers) -> ASSERT( null leftovers )
343                                      FoundInst subst val
344
345     any_match rest = or [ maybeToBool (matchTys tvs tpl key_tys)
346                         | (tvs,tpl,_) <- rest
347                         ]
348 \end{code}
349
350 @addToClsInstEnv@ extends a @ClsInstEnv@, checking for overlaps.
351
352 A boolean flag controls overlap reporting.
353
354 True => overlap is permitted, but only if one template matches the other;
355         not if they unify but neither is 
356
357 \begin{code}
358 addToInstEnv :: Bool                                    -- True <=> overlap permitted
359              -> InstEnv                                 -- Envt
360              -> Class -> [TyVar] -> [Type] -> Id        -- New item
361              -> MaybeErr InstEnv                        -- Success...
362                          ([Type], Id)                   -- Failure: Offending overlap
363
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)
368         
369   where
370     ins_tv_set = mkVarSet ins_tvs
371     ins_item = (ins_tv_set, ins_tys, value)
372
373     insert_into [] = returnMaB [ins_item]
374     insert_into env@(cur_item@(tpl_tvs, tpl_tys, val) : rest)
375
376         -- FAIL if:
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
380       |  identical 
381       || (unifiable && not overlap_ok)
382       || (unifiable && not (ins_item_more_specific || cur_item_more_specific))
383       =  failMaB (tpl_tys, val)
384
385         -- New item is an instance of current item, so drop it here
386       | ins_item_more_specific  = returnMaB (ins_item : env)
387
388         -- Otherwise carry on
389       | otherwise  = insert_into rest     `thenMaB` \ rest' ->
390                      returnMaB (cur_item : rest')
391       where
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
396 \end{code}
397
398