[project @ 1999-03-17 10:06:21 by simonpj]
[ghc-hetmet.git] / ghc / compiler / typecheck / TcUnify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
3 %
4 \section[Unify]{Unifier}
5
6 The unifier is now squarely in the typechecker monad (because of the
7 updatable substitution).
8
9 \begin{code}
10 module TcUnify ( unifyTauTy, unifyTauTyList, unifyTauTyLists, 
11                  unifyFunTy, unifyListTy, unifyTupleTy, unifyUnboxedTupleTy,
12                  unifyKind, unifyKinds, unifyTypeKind
13  ) where
14
15 #include "HsVersions.h"
16
17 -- friends: 
18 import TcMonad
19 import Type     ( Type(..), tyVarsOfType, funTyCon,
20                   mkFunTy, splitFunTy_maybe, splitTyConApp_maybe,
21                   Kind, boxedTypeKind, typeCon, anyBoxCon, anyBoxKind,
22                   splitAppTy_maybe,
23                   tidyOpenType, tidyOpenTypes, tidyTyVar
24                 )
25 import TyCon    ( TyCon, isTupleTyCon, isUnboxedTupleTyCon, 
26                   tyConArity )
27 import Name     ( hasBetterProv )
28 import Var      ( TyVar, tyVarKind, varName )
29 import VarEnv   
30 import VarSet   ( varSetElems )
31 import TcType   ( TcType, TcTauType, TcTyVar, TcKind, 
32                   newTyVarTy, newOpenTypeKind, newTyVarTy_OpenKind,
33                   tcGetTyVar, tcPutTyVar, zonkTcType, tcTypeKind
34                 )
35 -- others:
36 import BasicTypes ( Arity )
37 import TysWiredIn ( listTyCon, mkListTy, mkTupleTy, mkUnboxedTupleTy )
38 import PprType  ()              -- Instances
39 import Util
40 import Outputable
41 \end{code}
42
43
44 %************************************************************************
45 %*                                                                      *
46 \subsection{The Kind variants}
47 %*                                                                      *
48 %************************************************************************
49
50 \begin{code}
51 unifyKind :: TcKind                 -- Expected
52           -> TcKind                 -- Actual
53           -> TcM s ()
54 unifyKind k1 k2 
55   = tcAddErrCtxtM (unifyCtxt "kind" k1 k2) $
56     uTys k1 k1 k2 k2
57
58 unifyKinds :: [TcKind] -> [TcKind] -> TcM s ()
59 unifyKinds []       []       = returnTc ()
60 unifyKinds (k1:ks1) (k2:ks2) = unifyKind k1 k2  `thenTc_`
61                                unifyKinds ks1 ks2
62 unifyKinds _ _ = panic "unifyKinds: length mis-match"
63 \end{code}
64
65
66 %************************************************************************
67 %*                                                                      *
68 \subsection[Unify-exported]{Exported unification functions}
69 %*                                                                      *
70 %************************************************************************
71
72 The exported functions are all defined as versions of some
73 non-exported generic functions.
74
75 Unify two @TauType@s.  Dead straightforward.
76
77 \begin{code}
78 unifyTauTy :: TcTauType -> TcTauType -> TcM s ()
79 unifyTauTy ty1 ty2      -- ty1 expected, ty2 inferred
80   = tcAddErrCtxtM (unifyCtxt "type" ty1 ty2) $
81     uTys ty1 ty1 ty2 ty2
82 \end{code}
83
84 @unifyTauTyList@ unifies corresponding elements of two lists of
85 @TauType@s.  It uses @uTys@ to do the real work.  The lists should be
86 of equal length.  We charge down the list explicitly so that we can
87 complain if their lengths differ.
88
89 \begin{code}
90 unifyTauTyLists :: [TcTauType] -> [TcTauType] ->  TcM s ()
91 unifyTauTyLists []           []         = returnTc ()
92 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2   `thenTc_`
93                                         unifyTauTyLists tys1 tys2
94 unifyTauTyLists ty1s ty2s = panic "Unify.unifyTauTyLists: mismatched type lists!"
95 \end{code}
96
97 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
98 all together.  It is used, for example, when typechecking explicit
99 lists, when all the elts should be of the same type.
100
101 \begin{code}
102 unifyTauTyList :: [TcTauType] -> TcM s ()
103 unifyTauTyList []                = returnTc ()
104 unifyTauTyList [ty]              = returnTc ()
105 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2   `thenTc_`
106                                    unifyTauTyList tys
107 \end{code}
108
109 %************************************************************************
110 %*                                                                      *
111 \subsection[Unify-uTys]{@uTys@: getting down to business}
112 %*                                                                      *
113 %************************************************************************
114
115 @uTys@ is the heart of the unifier.  Each arg happens twice, because
116 we want to report errors in terms of synomyms if poss.  The first of
117 the pair is used in error messages only; it is always the same as the
118 second, except that if the first is a synonym then the second may be a
119 de-synonym'd version.  This way we get better error messages.
120
121 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
122
123 \begin{code}
124 uTys :: TcTauType -> TcTauType  -- Error reporting ty1 and real ty1
125      -> TcTauType -> TcTauType  -- Error reporting ty2 and real ty2
126      -> TcM s ()
127
128         -- Always expand synonyms (see notes at end)
129 uTys ps_ty1 (NoteTy _ ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
130 uTys ps_ty1 ty1 ps_ty2 (NoteTy _ ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
131
132         -- Variables; go for uVar
133 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar False tyvar1 ps_ty2 ty2
134 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar True  tyvar2 ps_ty1 ty1
135                                         -- "True" means args swapped
136
137         -- Functions; just check the two parts
138 uTys _ (FunTy fun1 arg1) _ (FunTy fun2 arg2)
139   = uTys fun1 fun1 fun2 fun2    `thenTc_`    uTys arg1 arg1 arg2 arg2
140
141         -- Type constructors must match
142 uTys ps_ty1 (TyConApp con1 tys1) ps_ty2 (TyConApp con2 tys2)
143   = checkTcM (cons_match && length tys1 == length tys2) 
144              (unifyMisMatch ps_ty1 ps_ty2)                      `thenTc_`
145     unifyTauTyLists tys1 tys2
146   where
147         -- The AnyBox wild card matches anything
148     cons_match =  con1 == con2 
149                || con1 == anyBoxCon
150                || con2 == anyBoxCon
151
152         -- Applications need a bit of care!
153         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
154         -- NB: we've already dealt with type variables and Notes,
155         -- so if one type is an App the other one jolly well better be too
156 uTys ps_ty1 (AppTy s1 t1) ps_ty2 ty2
157   = case splitAppTy_maybe ty2 of
158         Just (s2,t2) -> uTys s1 s1 s2 s2        `thenTc_`    uTys t1 t1 t2 t2
159         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
160
161         -- Now the same, but the other way round
162         -- Don't swap the types, because the error messages get worse
163 uTys ps_ty1 ty1 ps_ty2 (AppTy s2 t2)
164   = case splitAppTy_maybe ty1 of
165         Just (s1,t1) -> uTys s1 s1 s2 s2        `thenTc_`    uTys t1 t1 t2 t2
166         Nothing      -> unifyMisMatch ps_ty1 ps_ty2
167
168         -- Not expecting for-alls in unification
169         -- ... but the error message from the unifyMisMatch more informative
170         -- than a panic message!
171
172         -- Anything else fails
173 uTys ps_ty1 ty1 ps_ty2 ty2  = unifyMisMatch ps_ty1 ps_ty2
174 \end{code}
175
176 Notes on synonyms
177 ~~~~~~~~~~~~~~~~~
178 If you are tempted to make a short cut on synonyms, as in this
179 pseudocode...
180
181 \begin{verbatim}
182 uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
183   = if (con1 == con2) then
184         -- Good news!  Same synonym constructors, so we can shortcut
185         -- by unifying their arguments and ignoring their expansions.
186         unifyTauTypeLists args1 args2
187     else
188         -- Never mind.  Just expand them and try again
189         uTys ty1 ty2
190 \end{verbatim}
191
192 then THINK AGAIN.  Here is the whole story, as detected and reported
193 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
194 \begin{quotation}
195 Here's a test program that should detect the problem:
196
197 \begin{verbatim}
198         type Bogus a = Int
199         x = (1 :: Bogus Char) :: Bogus Bool
200 \end{verbatim}
201
202 The problem with [the attempted shortcut code] is that
203 \begin{verbatim}
204         con1 == con2
205 \end{verbatim}
206 is not a sufficient condition to be able to use the shortcut!
207 You also need to know that the type synonym actually USES all
208 its arguments.  For example, consider the following type synonym
209 which does not use all its arguments.
210 \begin{verbatim}
211         type Bogus a = Int
212 \end{verbatim}
213
214 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
215 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
216 would fail, even though the expanded forms (both \tr{Int}) should
217 match.
218
219 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
220 unnecessarily bind \tr{t} to \tr{Char}.
221
222 ... You could explicitly test for the problem synonyms and mark them
223 somehow as needing expansion, perhaps also issuing a warning to the
224 user.
225 \end{quotation}
226
227
228 %************************************************************************
229 %*                                                                      *
230 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
231 %*                                                                      *
232 %************************************************************************
233
234 @uVar@ is called when at least one of the types being unified is a
235 variable.  It does {\em not} assume that the variable is a fixed point
236 of the substitution; rather, notice that @uVar@ (defined below) nips
237 back into @uTys@ if it turns out that the variable is already bound.
238
239 \begin{code}
240 uVar :: Bool            -- False => tyvar is the "expected"
241                         -- True  => ty    is the "expected" thing
242      -> TcTyVar
243      -> TcTauType -> TcTauType  -- printing and real versions
244      -> TcM s ()
245
246 uVar swapped tv1 ps_ty2 ty2
247   = tcGetTyVar tv1      `thenNF_Tc` \ maybe_ty1 ->
248     case maybe_ty1 of
249         Just ty1 | swapped   -> uTys ps_ty2 ty2 ty1 ty1 -- Swap back
250                  | otherwise -> uTys ty1 ty1 ps_ty2 ty2 -- Same order
251         other       -> uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
252
253         -- Expand synonyms
254 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 (NoteTy _ ty2)
255   = uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2
256
257
258         -- The both-type-variable case
259 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 ty2@(TyVarTy tv2)
260
261         -- Same type variable => no-op
262   | tv1 == tv2
263   = returnTc ()
264
265         -- Distinct type variables
266         -- ASSERT maybe_ty1 /= Just
267   | otherwise
268   = tcGetTyVar tv2      `thenNF_Tc` \ maybe_ty2 ->
269     case maybe_ty2 of
270         Just ty2' -> uUnboundVar swapped tv1 maybe_ty1 ty2' ty2'
271
272         Nothing -> checkKinds swapped tv1 ty2                   `thenTc_`
273
274                         -- Try to update sys-y type variables in preference to sig-y ones
275                    if varName tv1 `hasBetterProv` varName tv2 then
276                         tcPutTyVar tv2 (TyVarTy tv1)                            `thenNF_Tc_`
277                         returnTc ()
278                    else
279                         tcPutTyVar tv1 ps_ty2                                   `thenNF_Tc_`
280                         returnTc ()
281
282         -- Second one isn't a type variable
283 uUnboundVar swapped tv1 maybe_ty1 ps_ty2 non_var_ty2
284   | non_var_ty2 == anyBoxKind
285         -- If the 
286   = returnTc ()
287
288   | otherwise
289   = checkKinds swapped tv1 non_var_ty2          `thenTc_`
290     occur_check non_var_ty2                     `thenTc_`
291     tcPutTyVar tv1 ps_ty2                       `thenNF_Tc_`
292     returnTc ()
293   where
294     occur_check ty = mapTc occur_check_tv (varSetElems (tyVarsOfType ty))       `thenTc_`
295                      returnTc ()
296
297     occur_check_tv tv2
298        | tv1 == tv2             -- Same tyvar; fail
299        = zonkTcType ps_ty2      `thenNF_Tc` \ zonked_ty2 ->
300          failWithTcM (unifyOccurCheck tv1 zonked_ty2)
301
302        | otherwise              -- A different tyvar
303        = tcGetTyVar tv2 `thenNF_Tc` \ maybe_ty2 ->
304          case maybe_ty2 of
305                 Just ty2' -> occur_check ty2'
306                 other     -> returnTc ()
307
308 checkKinds swapped tv1 ty2
309   = tcAddErrCtxtM (unifyKindCtxt swapped tv1 ty2)       $
310
311         -- We have to use tcTypeKind not just typeKind to get the
312         -- kind of ty2, because there might be mutable kind variables
313         -- in the way.  For example, suppose that ty2 :: (a b), and
314         -- the kind of 'a' is a kind variable 'k' that has (presumably)
315         -- been unified with 'k1 -> k2'.
316     tcTypeKind ty2              `thenNF_Tc` \ k2 ->
317
318     if swapped then
319         unifyKind k2 (tyVarKind tv1)
320     else
321         unifyKind (tyVarKind tv1) k2
322 \end{code}
323
324 %************************************************************************
325 %*                                                                      *
326 \subsection[Unify-fun]{@unifyFunTy@}
327 %*                                                                      *
328 %************************************************************************
329
330 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
331
332 \begin{code}
333 unifyFunTy :: TcType                            -- Fail if ty isn't a function type
334            -> TcM s (TcType, TcType)    -- otherwise return arg and result types
335
336 unifyFunTy ty@(TyVarTy tyvar)
337   = tcGetTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
338     case maybe_ty of
339         Just ty' -> unifyFunTy ty'
340         other       -> unify_fun_ty_help ty
341
342 unifyFunTy ty
343   = case splitFunTy_maybe ty of
344         Just arg_and_res -> returnTc arg_and_res
345         Nothing          -> unify_fun_ty_help ty
346
347 unify_fun_ty_help ty    -- Special cases failed, so revert to ordinary unification
348   = newTyVarTy_OpenKind         `thenNF_Tc` \ arg ->
349     newTyVarTy_OpenKind         `thenNF_Tc` \ res ->
350     unifyTauTy ty (mkFunTy arg res)     `thenTc_`
351     returnTc (arg,res)
352 \end{code}
353
354 \begin{code}
355 unifyListTy :: TcType              -- expected list type
356             -> TcM s TcType      -- list element type
357
358 unifyListTy ty@(TyVarTy tyvar)
359   = tcGetTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
360     case maybe_ty of
361         Just ty' -> unifyListTy ty'
362         other       -> unify_list_ty_help ty
363
364 unifyListTy ty
365   = case splitTyConApp_maybe ty of
366         Just (tycon, [arg_ty]) | tycon == listTyCon -> returnTc arg_ty
367         other                                       -> unify_list_ty_help ty
368
369 unify_list_ty_help ty   -- Revert to ordinary unification
370   = newTyVarTy boxedTypeKind            `thenNF_Tc` \ elt_ty ->
371     unifyTauTy ty (mkListTy elt_ty)     `thenTc_`
372     returnTc elt_ty
373 \end{code}
374
375 \begin{code}
376 unifyTupleTy :: Arity -> TcType -> TcM s [TcType]
377 unifyTupleTy arity ty@(TyVarTy tyvar)
378   = tcGetTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
379     case maybe_ty of
380         Just ty' -> unifyTupleTy arity ty'
381         other       -> unify_tuple_ty_help arity ty
382
383 unifyTupleTy arity ty
384   = case splitTyConApp_maybe ty of
385         Just (tycon, arg_tys) |  isTupleTyCon tycon 
386                          && tyConArity tycon == arity
387                          -> returnTc arg_tys
388         other -> unify_tuple_ty_help arity ty
389
390 unify_tuple_ty_help arity ty
391   = mapNF_Tc (\ _ -> newTyVarTy boxedTypeKind) [1..arity]       `thenNF_Tc` \ arg_tys ->
392     unifyTauTy ty (mkTupleTy arity arg_tys)                     `thenTc_`
393     returnTc arg_tys
394 \end{code}
395
396 \begin{code}
397 unifyUnboxedTupleTy :: Arity -> TcType -> TcM s [TcType]
398 unifyUnboxedTupleTy arity ty@(TyVarTy tyvar)
399   = tcGetTyVar tyvar    `thenNF_Tc` \ maybe_ty ->
400     case maybe_ty of
401         Just ty' -> unifyUnboxedTupleTy arity ty'
402         other    -> unify_unboxed_tuple_ty_help arity ty
403
404 unifyUnboxedTupleTy arity ty
405   = case splitTyConApp_maybe ty of
406         Just (tycon, arg_tys) |  isUnboxedTupleTyCon tycon 
407                          && tyConArity tycon == arity
408                          -> returnTc arg_tys
409         other -> unify_tuple_ty_help arity ty
410
411 unify_unboxed_tuple_ty_help arity ty
412   = mapNF_Tc (\ _ -> newTyVarTy_OpenKind) [1..arity]    `thenNF_Tc` \ arg_tys ->
413     unifyTauTy ty (mkUnboxedTupleTy arity arg_tys)      `thenTc_`
414     returnTc arg_tys
415 \end{code}
416
417 Make sure a kind is of the form (Type b) for some boxity b.
418
419 \begin{code}
420 unifyTypeKind  :: TcKind -> TcM s ()
421 unifyTypeKind kind@(TyVarTy kv)
422   = tcGetTyVar kv       `thenNF_Tc` \ maybe_kind ->
423     case maybe_kind of
424         Just kind' -> unifyTypeKind kind'
425         Nothing    -> unify_type_kind_help kind
426
427 unifyTypeKind kind
428   = case splitTyConApp_maybe kind of
429         Just (tycon, [_]) | tycon == typeCon -> returnTc ()
430         other                                -> unify_type_kind_help kind
431
432 unify_type_kind_help kind
433   = newOpenTypeKind     `thenNF_Tc` \ expected_kind ->
434     unifyKind expected_kind kind
435 \end{code}
436
437
438 %************************************************************************
439 %*                                                                      *
440 \subsection[Unify-context]{Errors and contexts}
441 %*                                                                      *
442 %************************************************************************
443
444 Errors
445 ~~~~~~
446
447 \begin{code}
448 unifyCtxt s ty1 ty2 tidy_env    -- ty1 expected, ty2 inferred
449   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
450     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
451     returnNF_Tc (err ty1' ty2')
452   where
453     err ty1 ty2 = (env1, 
454                    nest 4 
455                         (vcat [
456                            text "Expected" <+> text s <> colon <+> ppr tidy_ty1,
457                            text "Inferred" <+> text s <> colon <+> ppr tidy_ty2
458                         ]))
459                   where
460                     (env1, [tidy_ty1,tidy_ty2]) = tidyOpenTypes tidy_env [ty1,ty2]
461
462 unifyKindCtxt swapped tv1 ty2 tidy_env  -- not swapped => tv1 expected, ty2 inferred
463   = returnNF_Tc (env2, ptext SLIT("When matching types") <+> 
464                        sep [quotes pp_expected, ptext SLIT("and"), quotes pp_actual])
465   where
466     (pp_expected, pp_actual) | swapped   = (pp2, pp1)
467                              | otherwise = (pp1, pp2)
468     (env1, tv1') = tidyTyVar tidy_env tv1
469     (env2, ty2') = tidyOpenType  env1     ty2
470     pp1 = ppr tv1'
471     pp2 = ppr ty2'
472
473 unifyMisMatch ty1 ty2
474   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
475     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
476     let
477         (env, [tidy_ty1, tidy_ty2]) = tidyOpenTypes emptyTidyEnv [ty1',ty2']
478         msg = hang (ptext SLIT("Couldn't match"))
479                    4 (sep [quotes (ppr tidy_ty1), 
480                            ptext SLIT("against"), 
481                            quotes (ppr tidy_ty2)])
482     in
483     failWithTcM (env, msg)
484
485 unifyOccurCheck tyvar ty
486   = (env2, hang (ptext SLIT("Occurs check: cannot construct the infinite type:"))
487               4 (sep [ppr tidy_tyvar, char '=', ppr tidy_ty]))
488   where
489     (env1, tidy_tyvar) = tidyTyVar emptyTidyEnv tyvar
490     (env2, tidy_ty)    = tidyOpenType  env1     ty
491 \end{code}
492