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