[project @ 1996-04-05 08:26:04 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 import Ubiq
15
16 -- friends: 
17 import TcMonad
18 import Type     ( GenType(..), getTypeKind, mkFunTy, getFunTy_maybe )
19 import TyCon    ( TyCon, mkFunTyCon )
20 import TyVar    ( GenTyVar(..), TyVar(..), getTyVarKind )
21 import TcType   ( TcType(..), TcMaybe(..), TcTauType(..), TcTyVar(..),
22                   newTyVarTy, tcReadTyVar, tcWriteTyVar, zonkTcType
23                 )
24 -- others:
25 import Kind     ( Kind, isSubKindOf, 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         (DontBind,DontBind) 
233                      -> failTc (unifyDontBindErr tv1 ps_ty2)
234
235         (UnBound, _) |  kind2 `isSubKindOf` kind1
236                      -> tcWriteTyVar tv1 ty2            `thenNF_Tc_` returnTc ()
237         
238         (_, UnBound) |  kind1 `isSubKindOf` kind2
239                      -> tcWriteTyVar tv2 (TyVarTy tv1)  `thenNF_Tc_` returnTc ()
240
241         other        -> failTc (unifyKindErr tv1 ps_ty2)
242
243         -- Second one isn't a type variable
244 uUnboundVar tv1@(TyVar uniq1 kind1 name1 box1) maybe_ty1 ps_ty2 non_var_ty2
245   = case maybe_ty1 of
246         DontBind -> failTc (unifyDontBindErr tv1 ps_ty2)
247
248         UnBound  |  getTypeKind non_var_ty2 `isSubKindOf` kind1
249                  -> occur_check non_var_ty2                     `thenTc_`
250                     tcWriteTyVar tv1 ps_ty2                     `thenNF_Tc_`
251                     returnTc ()
252
253         other    -> failTc (unifyKindErr tv1 ps_ty2)
254   where
255     occur_check (TyVarTy tv2@(TyVar uniq2 _ _ box2))
256        | uniq1 == uniq2         -- Same tyvar; fail
257        = failTc (unifyOccurCheck tv1 ps_ty2)
258
259        | otherwise              -- A different tyvar
260        = tcReadTyVar tv2        `thenNF_Tc` \ maybe_ty2 ->
261          case maybe_ty2 of
262                 BoundTo ty2' -> occur_check ty2'
263                 other        -> returnTc ()
264
265     occur_check (AppTy fun arg)   = occur_check fun `thenTc_` occur_check arg
266     occur_check (FunTy fun arg _) = occur_check fun `thenTc_` occur_check arg
267     occur_check (TyConTy _ _)     = returnTc ()
268     occur_check (SynTy _ _ ty2)   = occur_check ty2
269     occur_check other             = panic "Unexpected Dict or ForAll in occurCheck"
270 \end{code}
271
272 %************************************************************************
273 %*                                                                      *
274 \subsection[Unify-fun]{@unifyFunTy@}
275 %*                                                                      *
276 %************************************************************************
277
278 @unifyFunTy@ is used to avoid the fruitless creation of type variables.
279
280 \begin{code}
281 unifyFunTy :: TcType s                          -- Fail if ty isn't a function type
282            -> TcM s (TcType s, TcType s)        -- otherwise return arg and result types
283
284 unifyFunTy ty@(TyVarTy tyvar)
285   = tcReadTyVar tyvar   `thenNF_Tc` \ maybe_ty ->
286     case maybe_ty of
287         BoundTo ty' -> unifyFunTy ty'
288
289         UnBound     -> newTyVarTy mkTypeKind                    `thenNF_Tc` \ arg ->
290                        newTyVarTy mkTypeKind                    `thenNF_Tc` \ res ->
291                        tcWriteTyVar tyvar (mkFunTy arg res)     `thenNF_Tc_`
292                        returnTc (arg,res)
293
294         DontBind    -> failTc (expectedFunErr ty)
295
296 unifyFunTy other_ty
297   = case getFunTy_maybe other_ty of
298         Just arg_and_res -> returnTc arg_and_res
299         Nothing          -> failTc (expectedFunErr other_ty)
300 \end{code}
301
302
303 %************************************************************************
304 %*                                                                      *
305 \subsection[Unify-context]{Errors and contexts}
306 %*                                                                      *
307 %************************************************************************
308
309 Errors
310 ~~~~~~
311
312 \begin{code}
313 unifyCtxt ty1 ty2
314   = zonkTcType ty1      `thenNF_Tc` \ ty1' ->
315     zonkTcType ty2      `thenNF_Tc` \ ty2' ->
316     returnNF_Tc (err ty1' ty2')
317   where
318     err ty1' ty2' sty = ppAboves [
319                            ppCat [ppStr "When matching:", ppr sty ty1'],
320                            ppCat [ppStr "      against:", ppr sty ty2']
321                         ]
322
323 unifyMisMatch ty1 ty2 sty
324   = ppHang (ppStr "Couldn't match the type")
325          4 (ppSep [ppr sty ty1, ppStr "against", ppr sty ty2])
326
327 expectedFunErr ty sty
328   = ppHang (ppStr "Function type expected, but found the type")
329          4 (ppr sty ty)
330
331 unifyKindErr tyvar ty sty
332   = ppHang (ppStr "Compiler bug: kind mis-match between")
333          4 (ppSep [ppr sty tyvar, ppLparen, ppr sty (getTyVarKind tyvar), ppRparen,
334                    ppStr "and", 
335                    ppr sty ty, ppLparen, ppr sty (getTypeKind ty), ppRparen])
336
337 unifyDontBindErr tyvar ty sty
338   = ppHang (ppStr "Couldn't match the *signature/existential* type variable")
339          4 (ppSep [ppr sty tyvar,
340                    ppStr "with the type", 
341                    ppr sty ty])
342
343 unifyOccurCheck tyvar ty sty
344   = ppHang (ppStr "Cannot construct the infinite type (occur check)")
345          4 (ppSep [ppr sty tyvar, ppStr "=", ppr sty ty])
346 \end{code}
347