[project @ 1996-06-05 06:44:31 by partain]
[ghc-hetmet.git] / ghc / compiler / typecheck / Unify.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1996
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 #include "HsVersions.h"
11
12 module Unify ( unifyTauTy, unifyTauTyList, unifyTauTyLists, unifyFunTy ) where
13
14 IMP_Ubiq()
15
16 -- friends: 
17 import TcMonad  hiding ( rnMtoTcM )
18 import Type     ( GenType(..), typeKind, mkFunTy, getFunTy_maybe )
19 import TyCon    ( TyCon, mkFunTyCon )
20 import TyVar    ( GenTyVar(..), TyVar(..), tyVarKind )
21 import TcType   ( TcType(..), TcMaybe(..), TcTauType(..), TcTyVar(..),
22                   newTyVarTy, tcReadTyVar, tcWriteTyVar, zonkTcType
23                 )
24 -- others:
25 import Kind     ( Kind, hasMoreBoxityInfo, mkTypeKind )
26 import Usage    ( duffUsage )
27 import PprType  ( GenTyVar, GenType )   -- instances
28 import Pretty
29 import Unique   ( Unique )              -- instances
30 import Util
31 \end{code}
32
33
34 %************************************************************************
35 %*                                                                      *
36 \subsection[Unify-exported]{Exported unification functions}
37 %*                                                                      *
38 %************************************************************************
39
40 The exported functions are all defined as versions of some
41 non-exported generic functions.
42
43 Unify two @TauType@s.  Dead straightforward.
44
45 \begin{code}
46 unifyTauTy :: TcTauType s -> TcTauType s -> TcM s ()
47 unifyTauTy ty1 ty2 
48   = tcAddErrCtxtM (unifyCtxt ty1 ty2) $
49     uTys ty1 ty1 ty2 ty2
50 \end{code}
51
52 @unifyTauTyList@ unifies corresponding elements of two lists of
53 @TauType@s.  It uses @uTys@ to do the real work.  The lists should be
54 of equal length.  We charge down the list explicitly so that we can
55 complain if their lengths differ.
56
57 \begin{code}
58 unifyTauTyLists :: [TcTauType s] -> [TcTauType s] ->  TcM s ()
59 unifyTauTyLists []           []         = returnTc ()
60 unifyTauTyLists (ty1:tys1) (ty2:tys2) = uTys ty1 ty1 ty2 ty2   `thenTc_`
61                                         unifyTauTyLists tys1 tys2
62 unifyTauTypeLists ty1s ty2s = panic "Unify.unifyTauTypeLists: mismatched type lists!"
63 \end{code}
64
65 @unifyTauTyList@ takes a single list of @TauType@s and unifies them
66 all together.  It is used, for example, when typechecking explicit
67 lists, when all the elts should be of the same type.
68
69 \begin{code}
70 unifyTauTyList :: [TcTauType s] -> TcM s ()
71 unifyTauTyList []                = returnTc ()
72 unifyTauTyList [ty]              = returnTc ()
73 unifyTauTyList (ty1:tys@(ty2:_)) = unifyTauTy ty1 ty2   `thenTc_`
74                                    unifyTauTyList tys
75 \end{code}
76
77 %************************************************************************
78 %*                                                                      *
79 \subsection[Unify-uTys]{@uTys@: getting down to business}
80 %*                                                                      *
81 %************************************************************************
82
83 @uTys@ is the heart of the unifier.  Each arg happens twice, because
84 we want to report errors in terms of synomyms if poss.  The first of
85 the pair is used in error messages only; it is always the same as the
86 second, except that if the first is a synonym then the second may be a
87 de-synonym'd version.  This way we get better error messages.
88
89 We call the first one \tr{ps_ty1}, \tr{ps_ty2} for ``possible synomym''.
90
91 \begin{code}
92 uTys :: TcTauType s -> TcTauType s      -- Error reporting ty1 and real ty1
93      -> TcTauType s -> TcTauType s      -- Error reporting ty2 and real ty2
94      -> TcM s ()
95
96         -- Variables; go for uVar
97 uTys ps_ty1 (TyVarTy tyvar1) ps_ty2 ty2 = uVar tyvar1 ps_ty2 ty2
98 uTys ps_ty1 ty1 ps_ty2 (TyVarTy tyvar2) = uVar tyvar2 ps_ty1 ty1
99
100         -- Applications and functions; just check the two parts
101 uTys _ (FunTy fun1 arg1 _) _ (FunTy fun2 arg2 _)
102   = uTys fun1 fun1 fun2 fun2    `thenTc_`    uTys arg1 arg1 arg2 arg2
103 uTys _ (AppTy s1 t1) _ (AppTy s2 t2)
104   = uTys s1 s1 s2 s2    `thenTc_`    uTys t1 t1 t2 t2
105
106         -- Special case: converts  a -> b to (->) a b
107 uTys _ (AppTy s1 t1) _ (FunTy fun2 arg2 _)
108   = uTys s1 s1 s2 s2    `thenTc_`    uTys t1 t1 t2 t2
109   where
110     s2 = AppTy (TyConTy mkFunTyCon duffUsage) fun2
111     t2 = arg2
112
113 uTys _ (FunTy fun1 arg1 _) _ (AppTy s2 t2)
114   = uTys s1 s1 s2 s2    `thenTc_`    uTys t1 t1 t2 t2
115   where
116     s1 = AppTy (TyConTy mkFunTyCon duffUsage) fun1
117     t1 = arg1
118
119         -- Type constructors must match
120 uTys ps_ty1 (TyConTy con1 _) ps_ty2 (TyConTy con2 _)
121   = checkTc (con1 == con2) (unifyMisMatch ps_ty1 ps_ty2)
122
123         -- Always expand synonyms (see notes at end)
124 uTys ps_ty1 (SynTy con1 args1 ty1) ps_ty2 ty2 = uTys ps_ty1 ty1 ps_ty2 ty2
125 uTys ps_ty1 ty1 ps_ty2 (SynTy con2 args2 ty2) = uTys ps_ty1 ty1 ps_ty2 ty2
126
127         -- Anything else fails
128 uTys ps_ty1 ty1 ps_ty2 ty2  = failTc (unifyMisMatch ps_ty1 ps_ty2)
129 \end{code}
130
131 Notes on synonyms
132 ~~~~~~~~~~~~~~~~~
133 If you are tempted to make a short cut on synonyms, as in this
134 pseudocode...
135
136 \begin{verbatim}
137 uTys (SynTy con1 args1 ty1) (SynTy con2 args2 ty2)
138   = if (con1 == con2) then
139         -- Good news!  Same synonym constructors, so we can shortcut
140         -- by unifying their arguments and ignoring their expansions.
141         unifyTauTypeLists args1 args2
142     else
143         -- Never mind.  Just expand them and try again
144         uTys ty1 ty2
145 \end{verbatim}
146
147 then THINK AGAIN.  Here is the whole story, as detected and reported
148 by Chris Okasaki \tr{<Chris_Okasaki@loch.mess.cs.cmu.edu>}:
149 \begin{quotation}
150 Here's a test program that should detect the problem:
151
152 \begin{verbatim}
153         type Bogus a = Int
154         x = (1 :: Bogus Char) :: Bogus Bool
155 \end{verbatim}
156
157 The problem with [the attempted shortcut code] is that
158 \begin{verbatim}
159         con1 == con2
160 \end{verbatim}
161 is not a sufficient condition to be able to use the shortcut!
162 You also need to know that the type synonym actually USES all
163 its arguments.  For example, consider the following type synonym
164 which does not use all its arguments.
165 \begin{verbatim}
166         type Bogus a = Int
167 \end{verbatim}
168
169 If you ever tried unifying, say, \tr{Bogus Char} with \tr{Bogus Bool},
170 the unifier would blithely try to unify \tr{Char} with \tr{Bool} and
171 would fail, even though the expanded forms (both \tr{Int}) should
172 match.
173
174 Similarly, unifying \tr{Bogus Char} with \tr{Bogus t} would
175 unnecessarily bind \tr{t} to \tr{Char}.
176
177 ... You could explicitly test for the problem synonyms and mark them
178 somehow as needing expansion, perhaps also issuing a warning to the
179 user.
180 \end{quotation}
181
182
183 %************************************************************************
184 %*                                                                      *
185 \subsection[Unify-uVar]{@uVar@: unifying with a type variable}
186 %*                                                                      *
187 %************************************************************************
188
189 @uVar@ is called when at least one of the types being unified is a
190 variable.  It does {\em not} assume that the variable is a fixed point
191 of the substitution; rather, notice that @bindTo@ (defined below) nips
192 back into @uTys@ if it turns out that the variable is already bound.
193
194 There is a slight worry that one might try to @bindTo@ a (say) Poly
195 tyvar (as tv1) with an Open tyvar (as ty2) which is already unified to
196 an unboxed type.  In fact this can't happen, because the Open ones are
197 always the ones which are unified away.
198
199 \begin{code}
200 uVar :: TcTyVar s
201      -> TcTauType s -> TcTauType s      -- printing and real versions
202      -> TcM s ()
203
204 uVar tv1 ps_ty2 ty2
205   = tcReadTyVar tv1     `thenNF_Tc` \ maybe_ty1 ->
206     case maybe_ty1 of
207         BoundTo ty1 -> uTys ty1 ty1 ps_ty2 ty2
208         other       -> uUnboundVar tv1 maybe_ty1 ps_ty2 ty2
209
210         -- Expand synonyms
211 uUnboundVar tv1 maybe_ty1 ps_ty2 (SynTy _ _ ty2)
212   = uUnboundVar tv1 maybe_ty1 ps_ty2 ty2
213
214
215         -- The both-type-variable case
216 uUnboundVar tv1@(TyVar uniq1 kind1 name1 box1)
217             maybe_ty1
218             ps_ty2
219             ty2@(TyVarTy tv2@(TyVar uniq2 kind2 name2 box2))
220
221         -- Same type variable => no-op
222   | uniq1 == uniq2
223   = returnTc ()
224
225         -- Distinct type variables
226         -- ASSERT maybe_ty1 /= BoundTo
227   | otherwise
228   = tcReadTyVar tv2     `thenNF_Tc` \ maybe_ty2 ->
229     case (maybe_ty1, maybe_ty2) of
230         (_, BoundTo ty2') -> uUnboundVar tv1 maybe_ty1 ty2' ty2'
231
232         (UnBound, _) |  kind2 `hasMoreBoxityInfo` kind1
233                      -> tcWriteTyVar tv1 ty2            `thenNF_Tc_` returnTc ()
234         
235         (_, UnBound) |  kind1 `hasMoreBoxityInfo` kind2
236                      -> tcWriteTyVar tv2 (TyVarTy tv1)  `thenNF_Tc_` returnTc ()
237
238 -- TEMPORARY FIX
239 --      (DontBind,DontBind) 
240 --                   -> failTc (unifyDontBindErr tv1 ps_ty2)
241
242 -- TEMPORARILY allow two type-sig variables to be bound together.
243 -- See notes in tcCheckSigVars
244         (DontBind,DontBind) |  kind2 `hasMoreBoxityInfo` kind1
245                             -> tcWriteTyVar tv1 ty2             `thenNF_Tc_` returnTc ()
246         
247                             |  kind1 `hasMoreBoxityInfo` kind2
248                             -> tcWriteTyVar tv2 (TyVarTy tv1)   `thenNF_Tc_` returnTc ()
249
250         other        -> failTc (unifyKindErr tv1 ps_ty2)
251
252         -- Second one isn't a type variable
253 uUnboundVar tv1@(TyVar uniq1 kind1 name1 box1) maybe_ty1 ps_ty2 non_var_ty2
254   = case maybe_ty1 of
255         DontBind -> failTc (unifyDontBindErr tv1 ps_ty2)
256
257         UnBound  |  typeKind non_var_ty2 `hasMoreBoxityInfo` kind1
258                  -> occur_check non_var_ty2                     `thenTc_`
259                     tcWriteTyVar tv1 ps_ty2                     `thenNF_Tc_`
260                     returnTc ()
261
262         other    -> failTc (unifyKindErr tv1 ps_ty2)
263   where
264     occur_check (TyVarTy tv2@(TyVar uniq2 _ _ box2))
265        | uniq1 == uniq2         -- Same tyvar; fail
266        = failTc (unifyOccurCheck tv1 ps_ty2)
267
268        | otherwise              -- A different tyvar
269        = tcReadTyVar tv2        `thenNF_Tc` \ maybe_ty2 ->
270          case maybe_ty2 of
271                 BoundTo ty2' -> occur_check ty2'
272                 other        -> returnTc ()
273
274     occur_check (AppTy fun arg)   = occur_check fun `thenTc_` occur_check arg
275     occur_check (FunTy fun arg _) = occur_check fun `thenTc_` occur_check arg
276     occur_check (TyConTy _ _)     = returnTc ()
277     occur_check (SynTy _ _ ty2)   = occur_check ty2
278     occur_check other             = panic "Unexpected Dict or ForAll in occurCheck"
279 \end{code}
280
281 %************************************************************************
282 %*                                                                      *
283 \subsection[Unify-fun]{@unifyFunTy@}
284 %*                                                                      *
285 %************************************************************************
286
287 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
288
289 \begin{code}
290 unifyFunTy :: TcType s                          -- Fail if ty isn't a function type
291            -> TcM s (TcType s, TcType s)        -- otherwise return arg and result types
292
293 unifyFunTy ty@(TyVarTy tyvar)
294   = tcReadTyVar tyvar   `thenNF_Tc` \ maybe_ty ->
295     case maybe_ty of
296         BoundTo ty' -> unifyFunTy ty'
297
298         UnBound     -> newTyVarTy mkTypeKind                    `thenNF_Tc` \ arg ->
299                        newTyVarTy mkTypeKind                    `thenNF_Tc` \ res ->
300                        tcWriteTyVar tyvar (mkFunTy arg res)     `thenNF_Tc_`
301                        returnTc (arg,res)
302
303         DontBind    -> failTc (expectedFunErr ty)
304
305 unifyFunTy other_ty
306   = case getFunTy_maybe other_ty of
307         Just arg_and_res -> returnTc arg_and_res
308         Nothing          -> failTc (expectedFunErr other_ty)
309 \end{code}
310
311
312 %************************************************************************
313 %*                                                                      *
314 \subsection[Unify-context]{Errors and contexts}
315 %*                                                                      *
316 %************************************************************************
317
318 Errors
319 ~~~~~~
320
321 \begin{code}
322 unifyCtxt ty1 ty2
323   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
324     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
325     returnNF_Tc (err ty1' ty2')
326   where
327     err ty1' ty2' sty = ppAboves [
328                            ppCat [ppStr "When matching:", ppr sty ty1'],
329                            ppCat [ppStr "      against:", ppr sty ty2']
330                         ]
331
332 unifyMisMatch ty1 ty2 sty
333   = ppHang (ppStr "Couldn't match the type")
334          4 (ppSep [ppr sty ty1, ppStr "against", ppr sty ty2])
335
336 expectedFunErr ty sty
337   = ppHang (ppStr "Function type expected, but found the type")
338          4 (ppr sty ty)
339
340 unifyKindErr tyvar ty sty
341   = ppHang (ppStr "Compiler bug: kind mis-match between")
342          4 (ppSep [ppCat [ppr sty tyvar, ppStr "::", ppr sty (tyVarKind tyvar)],
343                    ppStr "and", 
344                    ppCat [ppr sty ty, ppStr "::", ppr sty (typeKind ty)]])
345
346 unifyDontBindErr tyvar ty sty
347   = ppHang (ppStr "Couldn't match the *signature/existential* type variable")
348          4 (ppSep [ppr sty tyvar,
349                    ppStr "with the type", 
350                    ppr sty ty])
351
352 unifyOccurCheck tyvar ty sty
353   = ppHang (ppStr "Cannot construct the infinite type (occur check)")
354          4 (ppSep [ppr sty tyvar, ppStr "=", ppr sty ty])
355 \end{code}
356