[project @ 2004-12-30 22:14:59 by simonpj]
[ghc-hetmet.git] / ghc / compiler / types / Unify.lhs
1 \begin{code}
2 module Unify ( 
3         -- Matching and unification
4         tcMatchTys, tcMatchTyX, tcMatchPreds, MatchEnv(..), 
5
6         tcUnifyTys, tcUnifyTysX,
7
8         gadtRefineTys, gadtMatchTys, coreRefineTys,
9
10         -- Re-export
11         MaybeErr(..)
12    ) where
13
14 #include "HsVersions.h"
15
16 import Var              ( Var, TyVar, tyVarKind )
17 import VarEnv
18 import VarSet
19 import Kind             ( isSubKind )
20 import Type             ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta, 
21                           TvSubstEnv, TvSubst(..), substTy, tcEqTypeX )
22 import TypeRep          ( Type(..), PredType(..), funTyCon )
23 import Util             ( snocView )
24 import ErrUtils         ( Message )
25 import Outputable
26 import Maybes
27 \end{code}
28
29
30 %************************************************************************
31 %*                                                                      *
32                 Matching
33 %*                                                                      *
34 %************************************************************************
35
36
37 Matching is much tricker than you might think.
38
39 1. The substitution we generate binds the *template type variables*
40    which are given to us explicitly.
41
42 2. We want to match in the presence of foralls; 
43         e.g     (forall a. t1) ~ (forall b. t2)
44
45    That is what the RnEnv2 is for; it does the alpha-renaming
46    that makes it as if a and b were the same variable.
47    Initialising the RnEnv2, so that it can generate a fresh
48    binder when necessary, entails knowing the free variables of
49    both types.
50
51 3. We must be careful not to bind a template type variable to a
52    locally bound variable.  E.g.
53         (forall a. x) ~ (forall b. b)
54    where x is the template type variable.  Then we do not want to
55    bind x to a/b!  This is a kind of occurs check.
56    The necessary locals accumulate in the RnEnv2.
57
58
59 \begin{code}
60 data MatchEnv
61   = ME  { me_tmpls :: VarSet    -- Template tyvars
62         , me_env   :: RnEnv2    -- Renaming envt for nested foralls
63         }                       --   In-scope set includes template tyvars
64
65 tcMatchTys :: TyVarSet          -- Template tyvars
66          -> [Type]              -- Template
67          -> [Type]              -- Target
68          -> Maybe TvSubstEnv    -- One-shot; in principle the template
69                                 -- variables could be free in the target
70
71 tcMatchTys tmpls tys1 tys2
72   = match_tys (ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope_tyvars})
73               emptyTvSubstEnv 
74               tys1 tys2
75   where
76     in_scope_tyvars = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
77         -- We're assuming that all the interesting 
78         -- tyvars in tys1 are in tmpls
79
80 tcMatchPreds
81         :: [TyVar]                      -- Bind these
82         -> [PredType] -> [PredType]
83         -> Maybe TvSubstEnv
84 tcMatchPreds tmpls ps1 ps2
85   = match_list (match_pred menv) emptyTvSubstEnv ps1 ps2
86   where
87     menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
88     in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
89
90 tcMatchTyX :: MatchEnv 
91          -> TvSubstEnv          -- Substitution to extend
92          -> Type                -- Template
93          -> Type                -- Target
94          -> Maybe TvSubstEnv
95
96 tcMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2        -- Rename for export
97 \end{code}
98
99 Now the internals of matching
100
101 \begin{code}
102 match :: MatchEnv       -- For the most part this is pushed downwards
103       -> TvSubstEnv     -- Substitution so far:
104                         --   Domain is subset of template tyvars
105                         --   Free vars of range is subset of 
106                         --      in-scope set of the RnEnv2
107       -> Type -> Type   -- Template and target respectively
108       -> Maybe TvSubstEnv
109 -- This matcher works on source types; that is, 
110 -- it respects NewTypes and PredType
111
112 match menv subst (NoteTy _ ty1) ty2 = match menv subst ty1 ty2
113 match menv subst ty1 (NoteTy _ ty2) = match menv subst ty1 ty2
114
115 match menv subst (TyVarTy tv1) ty2
116   | tv1 `elemVarSet` me_tmpls menv
117   = case lookupVarEnv subst tv1' of
118         Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
119                 -> Nothing      -- Occurs check
120                 | not (typeKind ty2 `isSubKind` tyVarKind tv1)
121                 -> Nothing      -- Kind mis-match
122                 | otherwise
123                 -> Just (extendVarEnv subst tv1 ty2)
124
125         Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
126                 -- ty1 has no locally-bound variables, hence nukeRnEnvL
127                 -- Note tcEqType...we are doing source-type matching here
128                   -> Just subst
129
130         other -> Nothing
131
132    | otherwise  -- tv1 is not a template tyvar
133    = case ty2 of
134         TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
135         other                                   -> Nothing
136   where
137     rn_env = me_env menv
138     tv1' = rnOccL rn_env tv1
139
140 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2) 
141   = match menv' subst ty1 ty2
142   where         -- Use the magic of rnBndr2 to go under the binders
143     menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
144
145 match menv subst (PredTy p1) (PredTy p2) 
146   = match_pred menv subst p1 p2
147 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
148   | tc1 == tc2 = match_tys menv subst tys1 tys2
149 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b) 
150   = do { subst' <- match menv subst ty1a ty2a
151        ; match menv subst' ty1b ty2b }
152 match menv subst (AppTy ty1a ty1b) ty2
153   | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
154   = do { subst' <- match menv subst ty1a ty2a
155        ; match menv subst' ty1b ty2b }
156
157 match menv subst ty1 ty2
158   = Nothing
159
160 --------------
161 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
162
163 --------------
164 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
165            -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
166 match_list fn subst []         []         = Just subst
167 match_list fn subst (ty1:tys1) (ty2:tys2) = do  { subst' <- fn subst ty1 ty2
168                                                 ; match_list fn subst' tys1 tys2 }
169 match_list fn subst tys1       tys2       = Nothing     
170
171 --------------
172 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
173   | c1 == c2 = match_tys menv subst tys1 tys2
174 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
175   | n1 == n2 = match menv subst t1 t2
176 match_pred menv subst p1 p2 = Nothing
177 \end{code}
178
179
180 %************************************************************************
181 %*                                                                      *
182                 The workhorse
183 %*                                                                      *
184 %************************************************************************
185
186 \begin{code}
187 gadtRefineTys, gadtMatchTys 
188         :: [TyVar]                      -- Try to unify these
189         -> TvSubstEnv                   -- Not idempotent
190         -> [Type] -> [Type]
191         -> MaybeErr Message TvSubstEnv  -- Not idempotent
192 -- This one is used by the type checker.  Neither the input nor result
193 -- substitition is idempotent
194 gadtRefineTys ex_tvs subst tys1 tys2
195   = initUM (tryToBind (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
196
197 gadtMatchTys ex_tvs subst tys1 tys2
198   = initUM (bindOnly (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
199
200 ----------------------------
201 coreRefineTys :: InScopeSet     -- Superset of free vars of either type
202               -> [TyVar]        -- Try to unify these
203               -> Type           -- Both types should be a fixed point 
204               -> Type           --   of the incoming substitution
205               -> Maybe TvSubstEnv       -- In-scope set is unaffected
206 -- Used by Core Lint and the simplifier.  Takes a full apply-once substitution.
207 -- The incoming substitution's in-scope set should mention all the variables free 
208 -- in the incoming types
209 coreRefineTys in_scope ex_tvs ty1 ty2
210   = maybeErrToMaybe $ initUM (tryToBind (mkVarSet ex_tvs)) $
211     do  {       -- Run the unifier, starting with an empty env
212         ; subst_env <- unify emptyTvSubstEnv ty1 ty2
213
214         -- Find the fixed point of the resulting non-idempotent substitution
215         ; let subst           = TvSubst in_scope subst_env_fixpt
216               subst_env_fixpt = mapVarEnv (substTy subst) subst_env
217         ; return subst_env_fixpt }
218
219 ----------------------------
220 tcUnifyTys :: TyVarSet -> [Type] -> [Type] -> Maybe TvSubstEnv
221 tcUnifyTys bind_these tys1 tys2
222   = maybeErrToMaybe $ initUM (bindOnly bind_these) $
223     unify_tys emptyTvSubstEnv tys1 tys2
224
225 tcUnifyTysX :: TyVarSet -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
226 tcUnifyTysX bind_these subst tys1 tys2
227   = maybeErrToMaybe $ initUM (bindOnly bind_these) $
228     unify_tys subst tys1 tys2
229
230 ----------------------------
231 tryToBind, bindOnly :: TyVarSet -> TyVar -> BindFlag
232 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
233                     | otherwise              = AvoidMe
234
235 bindOnly tv_set tv | tv `elemVarSet` tv_set = BindMe
236                    | otherwise              = DontBindMe
237
238 emptyTvSubstEnv :: TvSubstEnv
239 emptyTvSubstEnv = emptyVarEnv
240 \end{code}
241
242
243 %************************************************************************
244 %*                                                                      *
245                 The workhorse
246 %*                                                                      *
247 %************************************************************************
248
249 \begin{code}
250 unify :: TvSubstEnv             -- An existing substitution to extend
251       -> Type -> Type           -- Types to be unified
252       -> UM TvSubstEnv          -- Just the extended substitution, 
253                                 -- Nothing if unification failed
254 -- We do not require the incoming substitution to be idempotent,
255 -- nor guarantee that the outgoing one is.  That's fixed up by
256 -- the wrappers.
257
258 -- Respects newtypes, PredTypes
259
260 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
261                       unify_ subst ty1 ty2
262
263 -- in unify_, any NewTcApps/Preds should be taken at face value
264 unify_ subst (TyVarTy tv1) ty2  = uVar False subst tv1 ty2
265 unify_ subst ty1 (TyVarTy tv2)  = uVar True  subst tv2 ty1
266
267 unify_ subst (NoteTy _ ty1) ty2  = unify subst ty1 ty2
268 unify_ subst ty1 (NoteTy _ ty2)  = unify subst ty1 ty2
269
270 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
271
272 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2) 
273   | tyc1 == tyc2 = unify_tys subst tys1 tys2
274
275 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b) 
276   = do { subst' <- unify subst ty1a ty2a
277        ; unify subst' ty1b ty2b }
278
279         -- Applications need a bit of care!
280         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
281         -- NB: we've already dealt with type variables and Notes,
282         -- so if one type is an App the other one jolly well better be too
283 unify_ subst (AppTy ty1a ty1b) ty2
284   | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
285   = do  { subst' <- unify subst ty1a ty2a
286         ; unify subst' ty1b ty2b }
287
288 unify_ subst ty1 (AppTy ty2a ty2b)
289   | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
290   = do  { subst' <- unify subst ty1a ty2a
291         ; unify subst' ty1b ty2b }
292
293 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
294
295 ------------------------------
296 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
297   | c1 == c2 = unify_tys subst tys1 tys2
298 unify_pred subst (IParam n1 t1) (IParam n2 t2)
299   | n1 == n2 = unify subst t1 t2
300 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
301  
302 ------------------------------
303 unify_tys = unifyList unify
304
305 unifyList :: Outputable a 
306           => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
307           -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
308 unifyList unifier subst orig_xs orig_ys
309   = go subst orig_xs orig_ys
310   where
311     go subst []     []     = return subst
312     go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
313                                 ; go subst' xs ys }
314     go subst _      _      = failWith (lengthMisMatch orig_xs orig_ys)
315
316 ------------------------------
317 uVar :: Bool            -- Swapped
318      -> TvSubstEnv      -- An existing substitution to extend
319      -> TyVar           -- Type variable to be unified
320      -> Type            -- with this type
321      -> UM TvSubstEnv
322
323 uVar swap subst tv1 ty
324  = -- check to see whether tv1 is refined
325    case (lookupVarEnv subst tv1) of
326      -- yes, call back into unify'
327      Just ty' | swap      -> unify subst ty ty' 
328               | otherwise -> unify subst ty' ty
329      -- No, continue
330      Nothing          -> uUnrefined subst tv1 ty
331
332
333 uUnrefined :: TvSubstEnv          -- An existing substitution to extend
334            -> TyVar               -- Type variable to be unified
335            -> Type                -- with this type
336            -> UM TvSubstEnv
337
338 -- We know that tv1 isn't refined
339 uUnrefined subst tv1 ty2@(TyVarTy tv2)
340   | tv1 == tv2    -- Same, do nothing
341   = return subst
342
343     -- Check to see whether tv2 is refined
344   | Just ty' <- lookupVarEnv subst tv2
345   = uUnrefined subst tv1 ty'
346
347   -- So both are unrefined; next, see if the kinds force the direction
348   | k1 == k2    -- Can update either; so check the bind-flags
349   = do  { b1 <- tvBindFlag tv1
350         ; b2 <- tvBindFlag tv2
351         ; case (b1,b2) of
352             (DontBindMe, DontBindMe) -> failWith (misMatch ty1 ty2)
353             (DontBindMe, _)          -> bindTv subst tv2 ty1
354             (BindMe, _)              -> bindTv subst tv1 ty2
355             (AvoidMe, BindMe)        -> bindTv subst tv2 ty1
356             (AvoidMe, _)             -> bindTv subst tv1 ty2
357         }
358
359   | k1 `isSubKind` k2   -- Must update tv2
360   = do  { b2 <- tvBindFlag tv2
361         ; case b2 of
362             DontBindMe -> failWith (misMatch ty1 ty2)
363             other      -> bindTv subst tv2 ty1
364         }
365
366   | k2 `isSubKind` k1   -- Must update tv1
367   = do  { b1 <- tvBindFlag tv1
368         ; case b1 of
369             DontBindMe -> failWith (misMatch ty1 ty2)
370             other      -> bindTv subst tv1 ty2
371         }
372
373   | otherwise = failWith (kindMisMatch tv1 ty2)
374   where
375     ty1 = TyVarTy tv1
376     k1 = tyVarKind tv1
377     k2 = tyVarKind tv2
378
379 uUnrefined subst tv1 ty2        -- ty2 is not a type variable
380         -- Do occurs check...
381   | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2)
382   = failWith (occursCheck tv1 ty2)
383         -- And a kind check...
384   | k2 `isSubKind` k1
385   = do  { b1 <- tvBindFlag tv1
386         ; case b1 of            -- And  check that tv1 is bindable
387             DontBindMe -> failWith (misMatch ty1 ty2)
388             other      -> bindTv subst tv1 ty2
389         }
390   | otherwise
391   = pprTrace "kind" (ppr tv1 <+> ppr k1 $$ ppr ty2 <+> ppr k2) $
392     failWith (kindMisMatch tv1 ty2)
393   where
394     ty1 = TyVarTy tv1
395     k1 = tyVarKind tv1
396     k2 = typeKind ty2
397
398 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
399 -- Apply the non-idempotent substitution to a set of type variables,
400 -- remembering that the substitution isn't necessarily idempotent
401 substTvSet subst tvs
402   = foldVarSet (unionVarSet . get) emptyVarSet tvs
403   where
404     get tv = case lookupVarEnv subst tv of
405                 Nothing -> unitVarSet tv
406                 Just ty -> substTvSet subst (tyVarsOfType ty)
407
408 bindTv subst tv ty = return (extendVarEnv subst tv ty)
409 \end{code}
410
411 %************************************************************************
412 %*                                                                      *
413                 Unification monad
414 %*                                                                      *
415 %************************************************************************
416
417 \begin{code}
418 data BindFlag = BindMe | AvoidMe | DontBindMe
419
420 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
421                          -> MaybeErr Message a }
422
423 instance Monad UM where
424   return a = UM (\tvs -> Succeeded a)
425   fail s   = UM (\tvs -> Failed (text s))
426   m >>= k  = UM (\tvs -> case unUM m tvs of
427                            Failed err -> Failed err
428                            Succeeded v  -> unUM (k v) tvs)
429
430 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
431 initUM badtvs um = unUM um badtvs
432
433 tvBindFlag :: TyVar -> UM BindFlag
434 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
435
436 failWith :: Message -> UM a
437 failWith msg = UM (\tv_fn -> Failed msg)
438
439 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
440 maybeErrToMaybe (Succeeded a) = Just a
441 maybeErrToMaybe (Failed m)    = Nothing
442
443 ------------------------------
444 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
445 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
446 repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
447 repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
448 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
449                                                 Just (tys', ty') -> Just (TyConApp tc tys', ty')
450                                                 Nothing          -> Nothing
451 repSplitAppTy_maybe other = Nothing
452 \end{code}
453
454
455 %************************************************************************
456 %*                                                                      *
457                 Error reporting
458         We go to a lot more trouble to tidy the types
459         in TcUnify.  Maybe we'll end up having to do that
460         here too, but I'll leave it for now.
461 %*                                                                      *
462 %************************************************************************
463
464 \begin{code}
465 misMatch t1 t2
466   = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+> 
467     ptext SLIT("and") <+> quotes (ppr t2)
468
469 lengthMisMatch tys1 tys2
470   = sep [ptext SLIT("Can't match unequal length lists"), 
471          nest 2 (ppr tys1), nest 2 (ppr tys2) ]
472
473 kindMisMatch tv1 t2
474   = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+> 
475             ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
476           ptext SLIT("when matching") <+> quotes (ppr tv1) <+> 
477                 ptext SLIT("with") <+> quotes (ppr t2)]
478
479 occursCheck tv ty
480   = hang (ptext SLIT("Can't construct the infinite type"))
481        2 (ppr tv <+> equals <+> ppr ty)
482 \end{code}