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