remove empty dir
[ghc-hetmet.git] / ghc / compiler / types / Unify.lhs
index 0143235..f60c7be 100644 (file)
@@ -1,11 +1,13 @@
 \begin{code}
 module Unify ( 
        -- Matching and unification
-       matchTys, matchTyX, tcMatchPreds, MatchEnv(..), 
+       tcMatchTys, tcMatchTyX, ruleMatchTyX, tcMatchPreds, MatchEnv(..), 
 
-       unifyTys, unifyTysX,
+       tcUnifyTys, 
 
-       tcRefineTys, tcMatchTys, coreRefineTys,
+       gadtRefineTys, BindFlag(..),
+
+       coreRefineTys, TypeRefinement,
 
        -- Re-export
        MaybeErr(..)
@@ -17,9 +19,11 @@ import Var           ( Var, TyVar, tyVarKind )
 import VarEnv
 import VarSet
 import Kind            ( isSubKind )
-import Type            ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta, 
-                         TvSubstEnv, TvSubst(..), substTy, tcEqTypeX )
+import Type            ( typeKind, tyVarsOfType, tyVarsOfTypes, tyVarsOfTheta, mkTyVarTys,
+                         TvSubstEnv, emptyTvSubstEnv, TvSubst(..), substTy, tcEqTypeX,
+                         mkOpenTvSubst, tcView )
 import TypeRep          ( Type(..), PredType(..), funTyCon )
+import DataCon                 ( DataCon, dataConInstResTy )
 import Util            ( snocView )
 import ErrUtils                ( Message )
 import Outputable
@@ -62,21 +66,35 @@ data MatchEnv
        , me_env   :: RnEnv2    -- Renaming envt for nested foralls
        }                       --   In-scope set includes template tyvars
 
-matchTys :: TyVarSet           -- Template tyvars
+tcMatchTys :: TyVarSet         -- Template tyvars
         -> [Type]              -- Template
         -> [Type]              -- Target
-        -> Maybe TvSubstEnv    -- One-shot; in principle the template
+        -> Maybe TvSubst       -- One-shot; in principle the template
                                -- variables could be free in the target
 
-matchTys tmpls tys1 tys2
-  = match_tys (ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope_tyvars})
-             emptyTvSubstEnv 
-             tys1 tys2
+tcMatchTys tmpls tys1 tys2
+  = case match_tys menv emptyTvSubstEnv tys1 tys2 of
+       Just subst_env -> Just (TvSubst in_scope subst_env)
+       Nothing        -> Nothing
   where
-    in_scope_tyvars = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
+    menv     = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
+    in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfTypes tys2)
        -- We're assuming that all the interesting 
        -- tyvars in tys1 are in tmpls
 
+-- This is similar, but extends a substitution
+tcMatchTyX :: TyVarSet                 -- Template tyvars
+          -> TvSubst           -- Substitution to extend
+          -> Type              -- Template
+          -> Type              -- Target
+          -> Maybe TvSubst
+tcMatchTyX tmpls (TvSubst in_scope subst_env) ty1 ty2
+  = case match menv subst_env ty1 ty2 of
+       Just subst_env -> Just (TvSubst in_scope subst_env)
+       Nothing        -> Nothing
+  where
+    menv = ME {me_tmpls = tmpls, me_env = mkRnEnv2 in_scope}
+
 tcMatchPreds
        :: [TyVar]                      -- Bind these
        -> [PredType] -> [PredType]
@@ -87,19 +105,20 @@ tcMatchPreds tmpls ps1 ps2
     menv = ME { me_tmpls = mkVarSet tmpls, me_env = mkRnEnv2 in_scope_tyvars }
     in_scope_tyvars = mkInScopeSet (tyVarsOfTheta ps1 `unionVarSet` tyVarsOfTheta ps2)
 
-matchTyX :: MatchEnv 
+-- This one is called from the expression matcher, which already has a MatchEnv in hand
+ruleMatchTyX :: MatchEnv 
         -> TvSubstEnv          -- Substitution to extend
         -> Type                -- Template
         -> Type                -- Target
         -> Maybe TvSubstEnv
 
-matchTyX menv subst ty1 ty2 = match menv subst ty1 ty2 -- Rename for export
+ruleMatchTyX menv subst ty1 ty2 = match menv subst ty1 ty2     -- Rename for export
 \end{code}
 
 Now the internals of matching
 
 \begin{code}
-match :: MatchEnv      -- For the ost part this is pushed downwards
+match :: MatchEnv      -- For the most part this is pushed downwards
       -> TvSubstEnv    -- Substitution so far:
                        --   Domain is subset of template tyvars
                        --   Free vars of range is subset of 
@@ -109,14 +128,16 @@ match :: MatchEnv -- For the ost part this is pushed downwards
 -- This matcher works on source types; that is, 
 -- it respects NewTypes and PredType
 
-match menv subst (NoteTy _ ty1) ty2 = match menv subst ty1 ty2
-match menv subst ty1 (NoteTy _ ty2) = match menv subst ty1 ty2
+match menv subst ty1 ty2 | Just ty1' <- tcView ty1 = match menv subst ty1' ty2
+match menv subst ty1 ty2 | Just ty2' <- tcView ty2 = match menv subst ty1 ty2'
 
 match menv subst (TyVarTy tv1) ty2
   | tv1 `elemVarSet` me_tmpls menv
   = case lookupVarEnv subst tv1' of
        Nothing | any (inRnEnvR rn_env) (varSetElems (tyVarsOfType ty2))
                -> Nothing      -- Occurs check
+               | not (typeKind ty2 `isSubKind` tyVarKind tv1)
+               -> Nothing      -- Kind mis-match
                | otherwise
                -> Just (extendVarEnv subst tv1 ty2)
 
@@ -177,69 +198,87 @@ match_pred menv subst p1 p2 = Nothing
 
 %************************************************************************
 %*                                                                     *
-               The workhorse
+               Unification
 %*                                                                     *
 %************************************************************************
 
 \begin{code}
-tcRefineTys, tcMatchTys 
-       :: [TyVar]                      -- Try to unify these
-       -> TvSubstEnv                   -- Not idempotent
-       -> [Type] -> [Type]
-       -> MaybeErr Message TvSubstEnv  -- Not idempotent
--- This one is used by the type checker.  Neither the input nor result
--- substitition is idempotent
-tcRefineTys ex_tvs subst tys1 tys2
-  = initUM (tryToBind (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
-
-tcMatchTys ex_tvs subst tys1 tys2
-  = initUM (bindOnly (mkVarSet ex_tvs)) (unify_tys subst tys1 tys2)
-
-----------------------------
-coreRefineTys :: [TyVar]       -- Try to unify these
-             -> TvSubst        -- A full-blown apply-once substitition
-             -> Type           -- A fixed point of the incoming substitution
-             -> Type
-             -> Maybe TvSubstEnv       -- In-scope set is unaffected
--- Used by Core Lint and the simplifier.  Takes a full apply-once substitution.
--- The incoming substitution's in-scope set should mention all the variables free 
--- in the incoming types
-coreRefineTys ex_tvs subst@(TvSubst in_scope orig_env) ty1 ty2
-  = maybeErrToMaybe $ initUM (tryToBind (mkVarSet ex_tvs)) $
-    do {       -- Apply the input substitution; nothing int ty2
-         let ty1' = substTy subst ty1  
-               -- Run the unifier, starting with an empty env
-       ; extra_env <- unify emptyTvSubstEnv ty1' ty2
-
-               -- Find the fixed point of the resulting non-idempotent
-               -- substitution, and apply it to the 
-       ; let extra_subst     = TvSubst in_scope extra_env_fixpt
-             extra_env_fixpt = mapVarEnv (substTy extra_subst) extra_env
-             orig_env'       = mapVarEnv (substTy extra_subst) orig_env
-       ; return (orig_env' `plusVarEnv` extra_env_fixpt) }
-    
+tcUnifyTys :: (TyVar -> BindFlag)
+          -> [Type] -> [Type]
+          -> Maybe TvSubst     -- A regular one-shot substitution
+-- The two types may have common type variables, and indeed do so in the
+-- second call to tcUnifyTys in FunDeps.checkClsFD
+tcUnifyTys bind_fn tys1 tys2
+  = maybeErrToMaybe $ initUM bind_fn $
+    do { subst_env <- unify_tys emptyTvSubstEnv tys1 tys2
+
+       -- Find the fixed point of the resulting non-idempotent substitution
+       ; let in_scope        = mkInScopeSet (tvs1 `unionVarSet` tvs2)
+             subst           = TvSubst in_scope subst_env_fixpt
+             subst_env_fixpt = mapVarEnv (substTy subst) subst_env
+       ; return subst }
+  where
+    tvs1 = tyVarsOfTypes tys1
+    tvs2 = tyVarsOfTypes tys2
 
 ----------------------------
-unifyTys :: TyVarSet -> [Type] -> [Type] -> Maybe TvSubstEnv
-unifyTys bind_these tys1 tys2
-  = maybeErrToMaybe $ initUM (bindOnly bind_these) $
-    unify_tys emptyTvSubstEnv tys1 tys2
-
-unifyTysX :: TyVarSet -> TvSubstEnv -> [Type] -> [Type] -> Maybe TvSubstEnv
-unifyTysX bind_these subst tys1 tys2
-  = maybeErrToMaybe $ initUM (bindOnly bind_these) $
-    unify_tys subst tys1 tys2
+coreRefineTys :: DataCon -> [TyVar]    -- Case pattern (con tv1 .. tvn ...)
+             -> Type                   -- Type of scrutinee
+             -> Maybe TypeRefinement
+
+type TypeRefinement = (TvSubstEnv, Bool)
+       -- The Bool is True iff all the bindings in the 
+       -- env are for the pattern type variables
+       -- In this case, there is no type refinement 
+       -- for already-in-scope type variables
+
+-- Used by Core Lint and the simplifier.
+coreRefineTys con tvs scrut_ty
+  = maybeErrToMaybe $ initUM (tryToBind tv_set) $
+    do {       -- Run the unifier, starting with an empty env
+       ; subst_env <- unify emptyTvSubstEnv pat_res_ty scrut_ty
+
+       -- Find the fixed point of the resulting non-idempotent substitution
+       ; let subst           = mkOpenTvSubst subst_env_fixpt
+             subst_env_fixpt = mapVarEnv (substTy subst) subst_env
+               
+       ; return (subst_env_fixpt, all_bound_here subst_env) }
+  where
+    pat_res_ty = dataConInstResTy con (mkTyVarTys tvs)
+
+       -- 'tvs' are the tyvars bound by the pattern
+    tv_set            = mkVarSet tvs
+    all_bound_here env = all bound_here (varEnvKeys env)
+    bound_here uniq    = elemVarSetByKey uniq tv_set
+
+-- This version is used by the type checker
+gadtRefineTys :: TvSubst 
+             -> DataCon -> [TyVar]
+             -> [Type] -> [Type]       
+             -> MaybeErr Message (TvSubst, Bool)
+-- The bool is True <=> the only *new* bindings are for pat_tvs
+
+gadtRefineTys (TvSubst in_scope env1) con pat_tvs pat_tys ctxt_tys
+  = initUM (tryToBind tv_set) $
+    do {       -- Run the unifier, starting with an empty env
+       ; env2 <- unify_tys env1 pat_tys ctxt_tys
+
+       -- Find the fixed point of the resulting non-idempotent substitution
+       ; let subst2          = TvSubst in_scope subst_env_fixpt
+             subst_env_fixpt = mapVarEnv (substTy subst2) env2
+               
+       ; return (subst2, all_bound_here env2) }
+  where
+       -- 'tvs' are the tyvars bound by the pattern
+    tv_set            = mkVarSet pat_tvs
+    all_bound_here env = all bound_here (varEnvKeys env)
+    bound_here uniq    = elemVarEnvByKey uniq env1 || elemVarSetByKey uniq tv_set
+       -- The bool is True <=> the only *new* bindings are for pat_tvs
 
 ----------------------------
-tryToBind, bindOnly :: TyVarSet -> TyVar -> BindFlag
+tryToBind :: TyVarSet -> TyVar -> BindFlag
 tryToBind tv_set tv | tv `elemVarSet` tv_set = BindMe
                    | otherwise              = AvoidMe
-
-bindOnly tv_set tv | tv `elemVarSet` tv_set = BindMe
-                  | otherwise              = DontBindMe
-
-emptyTvSubstEnv :: TvSubstEnv
-emptyTvSubstEnv = emptyVarEnv
 \end{code}
 
 
@@ -258,15 +297,17 @@ unify :: TvSubstEnv               -- An existing substitution to extend
 -- nor guarantee that the outgoing one is.  That's fixed up by
 -- the wrappers.
 
+-- Respects newtypes, PredTypes
+
 unify subst ty1 ty2 = -- pprTrace "unify" (ppr subst <+> pprParendType ty1 <+> pprParendType ty2) $
-                       unify_ subst ty1 ty2
+                     unify_ subst ty1 ty2
 
 -- in unify_, any NewTcApps/Preds should be taken at face value
 unify_ subst (TyVarTy tv1) ty2  = uVar False subst tv1 ty2
 unify_ subst ty1 (TyVarTy tv2)  = uVar True  subst tv2 ty1
 
-unify_ subst (NoteTy _ ty1) ty2  = unify subst ty1 ty2
-unify_ subst ty1 (NoteTy _ ty2)  = unify subst ty1 ty2
+unify_ subst ty1 ty2 | Just ty1' <- tcView ty1 = unify subst ty1' ty2
+unify_ subst ty1 ty2 | Just ty2' <- tcView ty2 = unify subst ty1 ty2'
 
 unify_ subst (PredTy p1) (PredTy p2) = unify_pred subst p1 p2
 
@@ -322,79 +363,77 @@ uVar :: Bool            -- Swapped
      -> UM TvSubstEnv
 
 uVar swap subst tv1 ty
- = -- check to see whether tv1 is refined
+ = -- Check to see whether tv1 is refined by the substitution
    case (lookupVarEnv subst tv1) of
-     -- yes, call back into unify'
+     -- Yes, call back into unify'
      Just ty' | swap      -> unify subst ty ty' 
               | otherwise -> unify subst ty' ty
      -- No, continue
-     Nothing          -> uUnrefined subst tv1 ty
+     Nothing          -> uUnrefined subst tv1 ty ty
 
 
 uUnrefined :: TvSubstEnv          -- An existing substitution to extend
            -> TyVar               -- Type variable to be unified
            -> Type                -- with this type
+           -> Type                -- (de-noted version)
            -> UM TvSubstEnv
 
 -- We know that tv1 isn't refined
-uUnrefined subst tv1 ty2@(TyVarTy tv2)
-  | tv1 == tv2    -- Same, do nothing
+
+uUnrefined subst tv1 ty2 ty2'
+  | Just ty2'' <- tcView ty2'
+  = uUnrefined subst tv1 ty2 ty2''     -- Unwrap synonyms
+               -- This is essential, in case we have
+               --      type Foo a = a
+               -- and then unify a :=: Foo a
+
+uUnrefined subst tv1 ty2 (TyVarTy tv2)
+  | tv1 == tv2         -- Same type variable
   = return subst
 
     -- Check to see whether tv2 is refined
   | Just ty' <- lookupVarEnv subst tv2
-  = uUnrefined subst tv1 ty'
+  = uUnrefined subst tv1 ty' ty'
 
   -- So both are unrefined; next, see if the kinds force the direction
   | k1 == k2   -- Can update either; so check the bind-flags
   = do { b1 <- tvBindFlag tv1
        ; b2 <- tvBindFlag tv2
        ; case (b1,b2) of
-           (DontBindMe, DontBindMe) -> failWith (misMatch ty1 ty2)
-           (DontBindMe, _)          -> bindTv subst tv2 ty1
-           (BindMe, _)              -> bindTv subst tv1 ty2
-           (AvoidMe, BindMe)        -> bindTv subst tv2 ty1
-           (AvoidMe, _)             -> bindTv subst tv1 ty2
-       }
+           (BindMe, _)          -> bind tv1 ty2
 
-  | k1 `isSubKind` k2  -- Must update tv2
-  = do { b2 <- tvBindFlag tv2
-       ; case b2 of
-           DontBindMe -> failWith (misMatch ty1 ty2)
-           other      -> bindTv subst tv2 ty1
-       }
+           (AvoidMe, BindMe)    -> bind tv2 ty1
+           (AvoidMe, _)         -> bind tv1 ty2
 
-  | k2 `isSubKind` k1  -- Must update tv1
-  = do { b1 <- tvBindFlag tv1
-       ; case b1 of
-           DontBindMe -> failWith (misMatch ty1 ty2)
-           other      -> bindTv subst tv1 ty2
+           (WildCard, WildCard) -> return subst
+           (WildCard, Skolem)   -> return subst
+           (WildCard, _)        -> bind tv2 ty1
+
+           (Skolem, WildCard)   -> return subst
+           (Skolem, Skolem)     -> failWith (misMatch ty1 ty2)
+           (Skolem, _)          -> bind tv2 ty1
        }
 
+  | k1 `isSubKind` k2 = bindTv subst tv2 ty1   -- Must update tv2
+  | k2 `isSubKind` k1 = bindTv subst tv1 ty2   -- Must update tv1
+
   | otherwise = failWith (kindMisMatch tv1 ty2)
   where
     ty1 = TyVarTy tv1
     k1 = tyVarKind tv1
     k2 = tyVarKind tv2
+    bind tv ty = return (extendVarEnv subst tv ty)
 
-uUnrefined subst tv1 ty2       -- ty2 is not a type variable
-       -- Do occurs check...
-  | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2)
-  = failWith (occursCheck tv1 ty2)
-       -- And a kind check...
-  | k2 `isSubKind` k1
-  = do { b1 <- tvBindFlag tv1
-       ; case b1 of            -- And  check that tv1 is bindable
-           DontBindMe -> failWith (misMatch ty1 ty2)
-           other      -> bindTv subst tv1 ty2
-       }
+uUnrefined subst tv1 ty2 ty2'  -- ty2 is not a type variable
+  | tv1 `elemVarSet` substTvSet subst (tyVarsOfType ty2')
+  = failWith (occursCheck tv1 ty2)     -- Occurs check
+  | not (k2 `isSubKind` k1)
+  = failWith (kindMisMatch tv1 ty2)    -- Kind check
   | otherwise
-  = pprTrace "kind" (ppr tv1 <+> ppr k1 $$ ppr ty2 <+> ppr k2) $
-    failWith (kindMisMatch tv1 ty2)
+  = bindTv subst tv1 ty2               -- Bind tyvar to the synonym if poss
   where
-    ty1 = TyVarTy tv1
     k1 = tyVarKind tv1
-    k2 = typeKind ty2
+    k2 = typeKind ty2'
 
 substTvSet :: TvSubstEnv -> TyVarSet -> TyVarSet
 -- Apply the non-idempotent substitution to a set of type variables,
@@ -406,7 +445,13 @@ substTvSet subst tvs
                Nothing -> unitVarSet tv
                Just ty -> substTvSet subst (tyVarsOfType ty)
 
-bindTv subst tv ty = return (extendVarEnv subst tv ty)
+bindTv subst tv ty     -- ty is not a type variable
+  = do { b <- tvBindFlag tv
+       ; case b of
+           Skolem   -> failWith (misMatch (TyVarTy tv) ty)
+           WildCard -> return subst
+           other    -> return (extendVarEnv subst tv ty)
+       }
 \end{code}
 
 %************************************************************************
@@ -416,7 +461,15 @@ bindTv subst tv ty = return (extendVarEnv subst tv ty)
 %************************************************************************
 
 \begin{code}
-data BindFlag = BindMe | AvoidMe | DontBindMe
+data BindFlag 
+  = BindMe     -- A regular type variable
+  | AvoidMe    -- Like BindMe but, given the choice, avoid binding it
+
+  | Skolem     -- This type variable is a skolem constant
+               -- Don't bind it; it only matches itself
+
+  | WildCard   -- This type variable matches anything,
+               -- and does not affect the substitution
 
 newtype UM a = UM { unUM :: (TyVar -> BindFlag)
                         -> MaybeErr Message a }