[project @ 2004-12-20 17:16:24 by simonpj]
[ghc-hetmet.git] / ghc / compiler / types / Unify.lhs
1 \begin{code}
2 module Unify ( 
3         -- Matching and unification
4         matchTys, matchTyX, tcMatchPreds, MatchEnv(..), 
5
6         unifyTys, unifyTysX,
7
8         tcRefineTys, tcMatchTys, 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 matchTys :: 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 matchTys 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 matchTyX :: MatchEnv 
91          -> TvSubstEnv          -- Substitution to extend
92          -> Type                -- Template
93          -> Type                -- Target
94          -> Maybe TvSubstEnv
95
96 matchTyX 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 ost 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                 | otherwise
121                 -> Just (extendVarEnv subst tv1 ty2)
122
123         Just ty1' | tcEqTypeX (nukeRnEnvL rn_env) ty1' ty2
124                 -- ty1 has no locally-bound variables, hence nukeRnEnvL
125                 -- Note tcEqType...we are doing source-type matching here
126                   -> Just subst
127
128         other -> Nothing
129
130    | otherwise  -- tv1 is not a template tyvar
131    = case ty2 of
132         TyVarTy tv2 | tv1' == rnOccR rn_env tv2 -> Just subst
133         other                                   -> Nothing
134   where
135     rn_env = me_env menv
136     tv1' = rnOccL rn_env tv1
137
138 match menv subst (ForAllTy tv1 ty1) (ForAllTy tv2 ty2) 
139   = match menv' subst ty1 ty2
140   where         -- Use the magic of rnBndr2 to go under the binders
141     menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
142
143 match menv subst (PredTy p1) (PredTy p2) 
144   = match_pred menv subst p1 p2
145 match menv subst (TyConApp tc1 tys1) (TyConApp tc2 tys2) 
146   | tc1 == tc2 = match_tys menv subst tys1 tys2
147 match menv subst (FunTy ty1a ty1b) (FunTy ty2a ty2b) 
148   = do { subst' <- match menv subst ty1a ty2a
149        ; match menv subst' ty1b ty2b }
150 match menv subst (AppTy ty1a ty1b) ty2
151   | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
152   = do { subst' <- match menv subst ty1a ty2a
153        ; match menv subst' ty1b ty2b }
154
155 match menv subst ty1 ty2
156   = Nothing
157
158 --------------
159 match_tys menv subst tys1 tys2 = match_list (match menv) subst tys1 tys2
160
161 --------------
162 match_list :: (TvSubstEnv -> a -> a -> Maybe TvSubstEnv)
163            -> TvSubstEnv -> [a] -> [a] -> Maybe TvSubstEnv
164 match_list fn subst []         []         = Just subst
165 match_list fn subst (ty1:tys1) (ty2:tys2) = do  { subst' <- fn subst ty1 ty2
166                                                 ; match_list fn subst' tys1 tys2 }
167 match_list fn subst tys1       tys2       = Nothing     
168
169 --------------
170 match_pred menv subst (ClassP c1 tys1) (ClassP c2 tys2)
171   | c1 == c2 = match_tys menv subst tys1 tys2
172 match_pred menv subst (IParam n1 t1) (IParam n2 t2)
173   | n1 == n2 = match menv subst t1 t2
174 match_pred menv subst p1 p2 = Nothing
175 \end{code}
176
177
178 %************************************************************************
179 %*                                                                      *
180                 The workhorse
181 %*                                                                      *
182 %************************************************************************
183
184 \begin{code}
185 tcRefineTys, tcMatchTys 
186         :: [TyVar]                      -- Try to unify these
187         -> TvSubstEnv                   -- Not idempotent
188         -> [Type] -> [Type]
189         -> MaybeErr Message TvSubstEnv  -- Not idempotent
190 -- This one is used by the type checker.  Neither the input nor result
191 -- substitition is idempotent
192 tcRefineTys ex_tvs subst tys1 tys2
193   = initUM (tryToBind (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
194
195 tcMatchTys ex_tvs subst tys1 tys2
196   = initUM (bindOnly (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
197
198 ----------------------------
199 coreRefineTys :: [TyVar]        -- Try to unify these
200               -> TvSubst        -- A full-blown apply-once substitition
201               -> Type           -- A fixed point of the incoming substitution
202               -> Type
203               -> Maybe TvSubstEnv       -- In-scope set is unaffected
204 -- Used by Core Lint and the simplifier.  Takes a full apply-once substitution.
205 -- The incoming substitution's in-scope set should mention all the variables free 
206 -- in the incoming types
207 coreRefineTys ex_tvs subst@(TvSubst in_scope orig_env) ty1 ty2
208   = maybeErrToMaybe $ initUM (tryToBind (mkVarSet ex_tvs)) $
209     do  {       -- Apply the input substitution; nothing int ty2
210           let ty1' = substTy subst ty1  
211                 -- Run the unifier, starting with an empty env
212         ; extra_env <- unify emptyTvSubstEnv ty1' ty2
213
214                 -- Find the fixed point of the resulting non-idempotent
215                 -- substitution, and apply it to the 
216         ; let extra_subst     = TvSubst in_scope extra_env_fixpt
217               extra_env_fixpt = mapVarEnv (substTy extra_subst) extra_env
218               orig_env'       = mapVarEnv (substTy extra_subst) orig_env
219         ; return (orig_env' `plusVarEnv` extra_env_fixpt) }
220     
221
222 ----------------------------
223 unifyTys :: TyVarSet -> [Type] -> [Type] -> Maybe TvSubstEnv
224 unifyTys bind_these tys1 tys2
225   = maybeErrToMaybe $ initUM (bindOnly bind_these) $
226     unify_tys emptyTvSubstEnv tys1 tys2
227
228 unifyTysX :: TyVarSet -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
229 unifyTysX bind_these subst tys1 tys2
230   = maybeErrToMaybe $ initUM (bindOnly bind_these) $
231     unify_tys subst tys1 tys2
232
233 ----------------------------
234 tryToBind, bindOnly :: TyVarSet -> TyVar -> BindFlag
235 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
236                     | otherwise              = AvoidMe
237
238 bindOnly tv_set tv | tv `elemVarSet` tv_set = BindMe
239                    | otherwise              = DontBindMe
240
241 emptyTvSubstEnv :: TvSubstEnv
242 emptyTvSubstEnv = emptyVarEnv
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 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
262                         unify_ subst ty1 ty2
263
264 -- in unify_, any NewTcApps/Preds should be taken at face value
265 unify_ subst (TyVarTy tv1) ty2  = uVar False subst tv1 ty2
266 unify_ subst ty1 (TyVarTy tv2)  = uVar True  subst tv2 ty1
267
268 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
269
270 unify_ subst t1@(TyConApp tyc1 tys1) t2@(TyConApp tyc2 tys2) 
271   | tyc1 == tyc2 = unify_tys subst tys1 tys2
272
273 unify_ subst (FunTy ty1a ty1b) (FunTy ty2a ty2b) 
274   = do { subst' <- unify subst ty1a ty2a
275        ; unify subst' ty1b ty2b }
276
277         -- Applications need a bit of care!
278         -- They can match FunTy and TyConApp, so use splitAppTy_maybe
279         -- NB: we've already dealt with type variables and Notes,
280         -- so if one type is an App the other one jolly well better be too
281 unify_ subst (AppTy ty1a ty1b) ty2
282   | Just (ty2a, ty2b) <- repSplitAppTy_maybe ty2
283   = do  { subst' <- unify subst ty1a ty2a
284         ; unify subst' ty1b ty2b }
285
286 unify_ subst ty1 (AppTy ty2a ty2b)
287   | Just (ty1a, ty1b) <- repSplitAppTy_maybe ty1
288   = do  { subst' <- unify subst ty1a ty2a
289         ; unify subst' ty1b ty2b }
290
291 unify_ subst ty1 ty2 = failWith (misMatch ty1 ty2)
292
293 ------------------------------
294 unify_pred subst (ClassP c1 tys1) (ClassP c2 tys2)
295   | c1 == c2 = unify_tys subst tys1 tys2
296 unify_pred subst (IParam n1 t1) (IParam n2 t2)
297   | n1 == n2 = unify subst t1 t2
298 unify_pred subst p1 p2 = failWith (misMatch (PredTy p1) (PredTy p2))
299  
300 ------------------------------
301 unify_tys = unifyList unify
302
303 unifyList :: Outputable a 
304           => (TvSubstEnv -> a -> a -> UM TvSubstEnv)
305           -> TvSubstEnv -> [a] -> [a] -> UM TvSubstEnv
306 unifyList unifier subst orig_xs orig_ys
307   = go subst orig_xs orig_ys
308   where
309     go subst []     []     = return subst
310     go subst (x:xs) (y:ys) = do { subst' <- unifier subst x y
311                                 ; go subst' xs ys }
312     go subst _      _      = failWith (lengthMisMatch orig_xs orig_ys)
313
314 ------------------------------
315 uVar :: Bool            -- Swapped
316      -> TvSubstEnv      -- An existing substitution to extend
317      -> TyVar           -- Type variable to be unified
318      -> Type            -- with this type
319      -> UM TvSubstEnv
320
321 uVar swap subst tv1 ty
322  = -- check to see whether tv1 is refined
323    case (lookupVarEnv subst tv1) of
324      -- yes, call back into unify'
325      Just ty' | swap      -> unify subst ty ty' 
326               | otherwise -> unify subst ty' ty
327      -- No, continue
328      Nothing          -> uUnrefined subst tv1 ty
329
330
331 uUnrefined :: TvSubstEnv          -- An existing substitution to extend
332            -> TyVar               -- Type variable to be unified
333            -> Type                -- with this type
334            -> UM TvSubstEnv
335
336 -- We know that tv1 isn't refined
337 uUnrefined subst tv1 ty2@(TyVarTy tv2)
338   | tv1 == tv2    -- Same, do nothing
339   = return subst
340
341     -- Check to see whether tv2 is refined
342   | Just ty' <- lookupVarEnv subst tv2
343   = uUnrefined subst tv1 ty'
344
345   -- So both are unrefined; next, see if the kinds force the direction
346   | k1 == k2    -- Can update either; so check the bind-flags
347   = do  { b1 <- tvBindFlag tv1
348         ; b2 <- tvBindFlag tv2
349         ; case (b1,b2) of
350             (DontBindMe, DontBindMe) -> failWith (misMatch ty1 ty2)
351             (DontBindMe, _)          -> bindTv subst tv2 ty1
352             (BindMe, _)              -> bindTv subst tv1 ty2
353             (AvoidMe, BindMe)        -> bindTv subst tv2 ty1
354             (AvoidMe, _)             -> bindTv subst tv1 ty2
355         }
356
357   | k1 `isSubKind` k2   -- Must update tv2
358   = do  { b2 <- tvBindFlag tv2
359         ; case b2 of
360             DontBindMe -> failWith (misMatch ty1 ty2)
361             other      -> bindTv subst tv2 ty1
362         }
363
364   | k2 `isSubKind` k1   -- Must update tv1
365   = do  { b1 <- tvBindFlag tv1
366         ; case b1 of
367             DontBindMe -> failWith (misMatch ty1 ty2)
368             other      -> bindTv subst tv1 ty2
369         }
370
371   | otherwise = failWith (kindMisMatch tv1 ty2)
372   where
373     ty1 = TyVarTy tv1
374     k1 = tyVarKind tv1
375     k2 = tyVarKind tv2
376
377 uUnrefined subst tv1 ty2        -- ty2 is not a type variable
378         -- Do occurs check...
379   | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2)
380   = failWith (occursCheck tv1 ty2)
381         -- And a kind check...
382   | k2 `isSubKind` k1
383   = do  { b1 <- tvBindFlag tv1
384         ; case b1 of            -- And  check that tv1 is bindable
385             DontBindMe -> failWith (misMatch ty1 ty2)
386             other      -> bindTv subst tv1 ty2
387         }
388   | otherwise
389   = pprTrace "kind" (ppr tv1 <+> ppr k1 $$ ppr ty2 <+> ppr k2) $
390     failWith (kindMisMatch tv1 ty2)
391   where
392     ty1 = TyVarTy tv1
393     k1 = tyVarKind tv1
394     k2 = typeKind ty2
395
396 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
397 -- Apply the non-idempotent substitution to a set of type variables,
398 -- remembering that the substitution isn't necessarily idempotent
399 substTvSet subst tvs
400   = foldVarSet (unionVarSet . get) emptyVarSet tvs
401   where
402     get tv = case lookupVarEnv subst tv of
403                 Nothing -> unitVarSet tv
404                 Just ty -> substTvSet subst (tyVarsOfType ty)
405
406 bindTv subst tv ty = return (extendVarEnv subst tv ty)
407 \end{code}
408
409 %************************************************************************
410 %*                                                                      *
411                 Unification monad
412 %*                                                                      *
413 %************************************************************************
414
415 \begin{code}
416 data BindFlag = BindMe | AvoidMe | DontBindMe
417
418 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
419                          -> MaybeErr Message a }
420
421 instance Monad UM where
422   return a = UM (\tvs -> Succeeded a)
423   fail s   = UM (\tvs -> Failed (text s))
424   m >>= k  = UM (\tvs -> case unUM m tvs of
425                            Failed err -> Failed err
426                            Succeeded v  -> unUM (k v) tvs)
427
428 initUM :: (TyVar -> BindFlag) -> UM a -> MaybeErr Message a
429 initUM badtvs um = unUM um badtvs
430
431 tvBindFlag :: TyVar -> UM BindFlag
432 tvBindFlag tv = UM (\tv_fn -> Succeeded (tv_fn tv))
433
434 failWith :: Message -> UM a
435 failWith msg = UM (\tv_fn -> Failed msg)
436
437 maybeErrToMaybe :: MaybeErr fail succ -> Maybe succ
438 maybeErrToMaybe (Succeeded a) = Just a
439 maybeErrToMaybe (Failed m)    = Nothing
440
441 ------------------------------
442 repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
443 -- Like Type.splitAppTy_maybe, but any coreView stuff is already done
444 repSplitAppTy_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
445 repSplitAppTy_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
446 repSplitAppTy_maybe (TyConApp tc tys) = case snocView tys of
447                                                 Just (tys', ty') -> Just (TyConApp tc tys', ty')
448                                                 Nothing          -> Nothing
449 repSplitAppTy_maybe other = Nothing
450 \end{code}
451
452
453 %************************************************************************
454 %*                                                                      *
455                 Error reporting
456         We go to a lot more trouble to tidy the types
457         in TcUnify.  Maybe we'll end up having to do that
458         here too, but I'll leave it for now.
459 %*                                                                      *
460 %************************************************************************
461
462 \begin{code}
463 misMatch t1 t2
464   = ptext SLIT("Can't match types") <+> quotes (ppr t1) <+> 
465     ptext SLIT("and") <+> quotes (ppr t2)
466
467 lengthMisMatch tys1 tys2
468   = sep [ptext SLIT("Can't match unequal length lists"), 
469          nest 2 (ppr tys1), nest 2 (ppr tys2) ]
470
471 kindMisMatch tv1 t2
472   = vcat [ptext SLIT("Can't match kinds") <+> quotes (ppr (tyVarKind tv1)) <+> 
473             ptext SLIT("and") <+> quotes (ppr (typeKind t2)),
474           ptext SLIT("when matching") <+> quotes (ppr tv1) <+> 
475                 ptext SLIT("with") <+> quotes (ppr t2)]
476
477 occursCheck tv ty
478   = hang (ptext SLIT("Can't construct the infinite type"))
479        2 (ppr tv <+> equals <+> ppr ty)
480 \end{code}