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