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