[project @ 2005-03-01 05:49:43 by simonpj]
[ghc-hetmet.git] / ghc / compiler / deSugar / MatchCon.lhs
index e828999..3787265 100644 (file)
@@ -1,4 +1,4 @@
-%
+
 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
 %
 \section[MatchCon]{Pattern-matching constructors}
@@ -10,16 +10,20 @@ module MatchCon ( matchConFamily ) where
 
 import {-# SOURCE #-} Match    ( match )
 
-import HsSyn           ( OutPat(..) )
-
+import HsSyn           ( Pat(..), HsConDetails(..), isEmptyLHsBinds )
+import DsBinds         ( dsHsNestedBinds )
+import DataCon         ( isVanillaDataCon, dataConTyVars, dataConOrigArgTys )
+import TcType          ( tcTyConAppArgs )
+import Type            ( substTys, zipTopTvSubst, mkTyVarTys )
+import CoreSyn
 import DsMonad
 import DsUtils
 
 import Id              ( Id )
-import CoreSyn
-import Type            ( mkTyVarTys )
-import Unique          ( Uniquable(..), Unique )
-import UniqFM          -- Until equivClassesUniq moves to Util
+import Type             ( Type )
+import ListSetOps      ( equivClassesByUniq )
+import SrcLoc          ( unLoc, Located(..) )
+import Unique          ( Uniquable(..) )
 import Outputable
 \end{code}
 
@@ -75,71 +79,84 @@ have-we-used-all-the-constructors? question; the local function
 @match_cons_used@ does all the real work.
 \begin{code}
 matchConFamily :: [Id]
+               -> Type
               -> [EquationInfo]
               -> DsM MatchResult
-
-matchConFamily (var:vars) eqns_info
+matchConFamily (var:vars) ty eqns_info
   = let
        -- Sort into equivalence classes by the unique on the constructor
        -- All the EqnInfos should start with a ConPat
        eqn_groups = equivClassesByUniq get_uniq eqns_info
-       get_uniq (EqnInfo _ _ (ConPat data_con _ _ _ _ : _) _) = getUnique data_con
+       get_uniq (EqnInfo { eqn_pats = ConPatOut (L _ data_con) _ _ _ _ _ : _}) = getUnique data_con
     in
        -- Now make a case alternative out of each group
-    mapDs (match_con vars) eqn_groups  `thenDs` \ alts ->
-
-    returnDs (mkCoAlgCaseMatchResult var alts)
+    mappM (match_con vars ty) eqn_groups       `thenDs` \ alts ->
+    returnDs (mkCoAlgCaseMatchResult var ty alts)
 \end{code}
 
 And here is the local function that does all the work.  It is
 more-or-less the @matchCon@/@matchClause@ functions on page~94 in
-Wadler's chapter in SLPJ.
+Wadler's chapter in SLPJ.  The function @shift_con_pats@ does what the
+list comprehension in @matchClause@ (SLPJ, p.~94) does, except things
+are trickier in real life.  Works for @ConPats@, and we want it to
+fail catastrophically for anything else (which a list comprehension
+wouldn't).  Cf.~@shift_lit_pats@ in @MatchLits@.
 
 \begin{code}
-match_con vars all_eqns@(EqnInfo n ctx (ConPat data_con _ ex_tvs ex_dicts arg_pats : pats1) match_result1 : other_eqns)
-  = -- Make new vars for the con arguments; avoid new locals where possible
-    mapDs selectMatchVar arg_pats                         `thenDs` \ arg_vars ->
-
-    -- Now do the business to make the alt for _this_ ConPat ...
-    match (ex_dicts ++ arg_vars ++ vars)
-         (map shift_con_pat all_eqns)  `thenDs` \ match_result ->
-
-       -- Substitute over the result
-    let
-       match_result' | null ex_tvs = match_result
-                     | otherwise   = adjustMatchResult subst_it match_result
-    in 
-    returnDs (data_con, ex_tvs ++ ex_dicts ++ arg_vars, match_result')
-  where
-    shift_con_pat :: EquationInfo -> EquationInfo
-    shift_con_pat (EqnInfo n ctx (ConPat _ _ ex_tvs' ex_dicts' arg_pats: pats) match_result)
-      = EqnInfo n ctx (new_pats  ++ pats) match_result
-      where
-       new_pats  = map VarPat ex_dicts' ++ arg_pats 
-
-       -- We 'substitute' by going: (/\ tvs' -> e) tvs
-    subst_it e = foldr subst_one e other_eqns
-    subst_one (EqnInfo _ _ (ConPat _ _ ex_tvs' _ _ : _) _) e = mkTyApps (mkLams ex_tvs' e) ex_tys
-    ex_tys = mkTyVarTys ex_tvs
-
-
--- Belongs in Util.lhs
-equivClassesByUniq :: (a -> Unique) -> [a] -> [[a]]
-       -- NB: it's *very* important that if we have the input list [a,b,c],
-       -- where a,b,c all have the same unique, then we get back the list
-       --      [a,b,c]
-       -- not
-       --      [c,b,a]
-       -- Hence the use of foldr, plus the reversed-args tack_on below
-equivClassesByUniq get_uniq xs
-  = eltsUFM (foldr add emptyUFM xs)
+match_con vars ty eqns
+  = do { -- Make new vars for the con arguments; avoid new locals where possible
+         arg_vars <- selectMatchVars (map unLoc arg_pats1) arg_tys
+       ; eqns' <- mapM shift eqns 
+       ; match_result <- match (arg_vars ++ vars) ty eqns'
+       ; return (con, tvs1 ++ dicts1 ++ arg_vars, match_result) }
   where
-    add a ufm = addToUFM_C tack_on ufm (get_uniq a) [a]
-    tack_on old new = new++old
+    ConPatOut (L _ con) tvs1 dicts1 _ (PrefixCon arg_pats1) pat_ty = firstPat (head eqns)
+
+    shift eqn@(EqnInfo { eqn_wrap = wrap, 
+                        eqn_pats = ConPatOut _ tvs ds bind (PrefixCon arg_pats) _ : pats })
+       = do { prs <- dsHsNestedBinds bind
+            ; return (eqn { eqn_wrap = wrap . wrapBinds (tvs `zip` tvs1) 
+                                            . wrapBinds (ds  `zip` dicts1)
+                                            . mkDsLet (Rec prs),
+                            eqn_pats = map unLoc arg_pats ++ pats }) }
+
+       -- Get the arg types, which we use to type the new vars
+       -- to match on, from the "outside"; the types of pats1 may 
+       -- be more refined, and hence won't do
+    arg_tys = substTys (zipTopTvSubst (dataConTyVars con) inst_tys)
+                      (dataConOrigArgTys con)
+    inst_tys | isVanillaDataCon con = tcTyConAppArgs pat_ty    -- Newtypes opaque!
+            | otherwise            = mkTyVarTys tvs1
 \end{code}
 
-Note on @shift_con_pats@ just above: does what the list comprehension in
-@matchClause@ (SLPJ, p.~94) does, except things are trickier in real
-life.  Works for @ConPats@, and we want it to fail catastrophically
-for anything else (which a list comprehension wouldn't).
-Cf.~@shift_lit_pats@ in @MatchLits@.
+Note [Existentials in shift_con_pat]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Consider
+       data T = forall a. Ord a => T a (a->Int)
+
+       f (T x f) True  = ...expr1...
+       f (T y g) False = ...expr2..
+
+When we put in the tyvars etc we get
+
+       f (T a (d::Ord a) (x::a) (f::a->Int)) True =  ...expr1...
+       f (T b (e::Ord b) (y::a) (g::a->Int)) True =  ...expr2...
+
+After desugaring etc we'll get a single case:
+
+       f = \t::T b::Bool -> 
+           case t of
+              T a (d::Ord a) (x::a) (f::a->Int)) ->
+           case b of
+               True  -> ...expr1...
+               False -> ...expr2...
+
+*** We have to substitute [a/b, d/e] in expr2! **
+Hence
+               False -> ....((/\b\(e:Ord b).expr2) a d)....
+
+Originally I tried to use 
+       (\b -> let e = d in expr2) a 
+to do this substitution.  While this is "correct" in a way, it fails
+Lint, because e::Ord b but d::Ord a.  
+