Fixes to datacon wrappers for indexed data types
authorsimonpj@microsoft.com <unknown>
Sun, 22 Apr 2007 21:35:03 +0000 (21:35 +0000)
committersimonpj@microsoft.com <unknown>
Sun, 22 Apr 2007 21:35:03 +0000 (21:35 +0000)
nominolo@gmail.com pointed out (Trac #1204) that indexed data types
aren't quite right. I investigated and found that the wrapper
functions for indexed data types, generated in MkId, are really very
confusing.  In particular, we'd like these combinations to work
newtype + indexed data type
GADT + indexted data type
The wrapper situation gets a bit complicated!

I did a bit of refactoring, and improved matters, I think.  I am not
certain that I have gotten it right yet, but I think it's better.
I'm committing it now becuase it's been on my non-backed-up laptop for
a month and I want to get it into the repo. I don't think I've broken
anything, but I don't regard it as 'done'.

compiler/basicTypes/DataCon.lhs
compiler/basicTypes/MkId.lhs
compiler/main/PprTyThing.hs
compiler/typecheck/TcPat.lhs
compiler/typecheck/TcTyClsDecls.lhs
compiler/typecheck/TcType.lhs
compiler/types/TyCon.lhs
compiler/types/Unify.lhs

index 5211fc8..ee2c685 100644 (file)
@@ -11,9 +11,9 @@ module DataCon (
        mkDataCon,
        dataConRepType, dataConSig, dataConFullSig,
        dataConName, dataConIdentity, dataConTag, dataConTyCon, dataConUserType,
-       dataConUnivTyVars, dataConExTyVars, dataConAllTyVars, dataConResTys,
+       dataConUnivTyVars, dataConExTyVars, dataConAllTyVars, 
        dataConEqSpec, eqSpecPreds, dataConTheta, dataConStupidTheta, 
-       dataConInstArgTys, dataConOrigArgTys, 
+       dataConInstArgTys, dataConOrigArgTys, dataConOrigResTy,
        dataConInstOrigArgTys, dataConRepArgTys, 
        dataConFieldLabels, dataConFieldType,
        dataConStrictMarks, dataConExStricts,
@@ -233,7 +233,7 @@ data DataCon
        --      dcEqSpec      = [a:=:(x,y)]
        --      dcTheta       = [Ord x]
        --      dcOrigArgTys  = [a,List b]
-       --      dcTyCon       = T
+       --      dcRepTyCon       = T
 
        dcVanilla :: Bool,      -- True <=> This is a vanilla Haskell 98 data constructor
                                --          Its type is of form
@@ -288,9 +288,11 @@ data DataCon
 
        dcOrigArgTys :: [Type],         -- Original argument types
                                        -- (before unboxing and flattening of strict fields)
-
-       -- Result type of constructor is T t1..tn
-       dcTyCon  :: TyCon,              -- Result tycon, T
+       dcOrigResTy :: Type,            -- Original result type
+               -- NB: for a data instance, the original user result type may 
+               -- differ from the DataCon's representation TyCon.  Example
+               --      data instance T [a] where MkT :: a -> T [a]
+               -- The OrigResTy is T [a], but the dcRepTyCon might be :T123
 
        -- Now the strictness annotations and field labels of the constructor
        dcStrictMarks :: [StrictnessMark],
@@ -300,7 +302,7 @@ data DataCon
 
        dcFields  :: [FieldLabel],
                -- Field labels for this constructor, in the
-               -- same order as the argument types; 
+               -- same order as the dcOrigArgTys; 
                -- length = 0 (if not a record) or dataConSourceArity.
 
        -- Constructor representation
@@ -311,6 +313,9 @@ data DataCon
        dcRepStrictness :: [StrictnessMark],    -- One for each *representation* argument       
                -- See also Note [Data-con worker strictness] in MkId.lhs
 
+       -- Result type of constructor is T t1..tn
+       dcRepTyCon  :: TyCon,           -- Result tycon, T
+
        dcRepType   :: Type,    -- Type of the constructor
                                --      forall a x y. (a:=:(x,y), Ord x) => x -> y -> MkT a
                                -- (this is *not* of the constructor wrapper Id:
@@ -459,7 +464,8 @@ mkDataCon name declared_infix
                  dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, 
                  dcEqSpec = eq_spec, 
                  dcStupidTheta = stupid_theta, dcTheta = theta,
-                 dcOrigArgTys = orig_arg_tys, dcTyCon = tycon, 
+                 dcOrigArgTys = orig_arg_tys, dcOrigResTy = orig_res_ty,
+                 dcRepTyCon = tycon, 
                  dcRepArgTys = rep_arg_tys,
                  dcStrictMarks = arg_stricts, 
                  dcRepStrictness = rep_arg_stricts,
@@ -477,6 +483,22 @@ mkDataCon name declared_infix
     real_arg_tys = dict_tys                      ++ orig_arg_tys
     real_stricts = map mk_dict_strict_mark theta ++ arg_stricts
 
+       -- Example
+       --   data instance T [a] where 
+       --      TI :: forall b. b -> T [Maybe b]
+       -- The representation tycon looks like this:
+       --   data :R7T a where 
+       --      TI :: forall b c. (c :=: Maybe b) b -> :R7T c
+    orig_res_ty 
+       | Just (fam_tc, fam_tys) <- tyConFamInst_maybe tycon
+       , let fam_subst = zipTopTvSubst (tyConTyVars fam_tc) res_tys
+       = mkTyConApp fam_tc (substTys fam_subst fam_tys)
+       | otherwise
+       = mkTyConApp tycon res_tys
+       where
+         res_tys = substTyVars (mkTopTvSubst eq_spec) univ_tvs
+               -- In the example above, res_tys is a singleton, (Maybe b)
+
        -- Representation arguments and demands
        -- To do: eliminate duplication with MkId
     (rep_arg_stricts, rep_arg_tys) = computeRep real_stricts real_arg_tys
@@ -518,7 +540,7 @@ dataConTag :: DataCon -> ConTag
 dataConTag  = dcTag
 
 dataConTyCon :: DataCon -> TyCon
-dataConTyCon = dcTyCon
+dataConTyCon = dcRepTyCon
 
 dataConRepType :: DataCon -> Type
 dataConRepType = dcRepType
@@ -597,25 +619,23 @@ dataConRepStrictness :: DataCon -> [StrictnessMark]
        -- Core constructor application (Con dc args)
 dataConRepStrictness dc = dcRepStrictness dc
 
-dataConSig :: DataCon -> ([TyVar], ThetaType, [Type])
+dataConSig :: DataCon -> ([TyVar], ThetaType, [Type], Type)
 dataConSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
-                   dcTheta  = theta, dcOrigArgTys = arg_tys, dcTyCon = tycon})
-  = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys)
+                   dcTheta  = theta, dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
+  = (univ_tvs ++ ex_tvs, eqSpecPreds eq_spec ++ theta, arg_tys, res_ty)
 
 dataConFullSig :: DataCon 
-              -> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type])
+              -> ([TyVar], [TyVar], [(TyVar,Type)], ThetaType, [Type], Type)
 dataConFullSig (MkData {dcUnivTyVars = univ_tvs, dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
-                       dcTheta  = theta, dcOrigArgTys = arg_tys, dcTyCon = tycon})
-  = (univ_tvs, ex_tvs, eq_spec, theta, arg_tys)
+                       dcTheta  = theta, dcOrigArgTys = arg_tys, dcOrigResTy = res_ty})
+  = (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, res_ty)
+
+dataConOrigResTy :: DataCon -> Type
+dataConOrigResTy dc = dcOrigResTy dc
 
 dataConStupidTheta :: DataCon -> ThetaType
 dataConStupidTheta dc = dcStupidTheta dc
 
-dataConResTys :: DataCon -> [Type]
-dataConResTys dc = [substTyVar env tv | tv <- dcUnivTyVars dc]
-  where
-    env = mkTopTvSubst (dcEqSpec dc)
-
 dataConUserType :: DataCon -> Type
 -- The user-declared type of the data constructor
 -- in the nice-to-read form 
@@ -627,15 +647,11 @@ dataConUserType :: DataCon -> Type
 dataConUserType  (MkData { dcUnivTyVars = univ_tvs, 
                           dcExTyVars = ex_tvs, dcEqSpec = eq_spec,
                           dcTheta = theta, dcOrigArgTys = arg_tys,
-                          dcTyCon = tycon })
+                          dcOrigResTy = res_ty })
   = mkForAllTys ((univ_tvs `minusList` map fst eq_spec) ++ ex_tvs) $
     mkFunTys (mkPredTys theta) $
     mkFunTys arg_tys $
-    case tyConFamInst_maybe tycon of
-      Nothing             -> mkTyConApp tycon (substTyVars subst univ_tvs)
-      Just (ftc, insttys) -> mkTyConApp ftc insttys        -- data instance
-  where
-    subst = mkTopTvSubst eq_spec
+    res_ty
 
 dataConInstArgTys :: DataCon
                  -> [Type]     -- Instantiated at these types
@@ -686,10 +702,10 @@ dataConRepArgTys dc = dcRepArgTys dc
 
 \begin{code}
 isTupleCon :: DataCon -> Bool
-isTupleCon (MkData {dcTyCon = tc}) = isTupleTyCon tc
+isTupleCon (MkData {dcRepTyCon = tc}) = isTupleTyCon tc
        
 isUnboxedTupleCon :: DataCon -> Bool
-isUnboxedTupleCon (MkData {dcTyCon = tc}) = isUnboxedTupleTyCon tc
+isUnboxedTupleCon (MkData {dcRepTyCon = tc}) = isUnboxedTupleTyCon tc
 
 isVanillaDataCon :: DataCon -> Bool
 isVanillaDataCon dc = dcVanilla dc
@@ -700,6 +716,7 @@ isVanillaDataCon dc = dcVanilla dc
 classDataCon :: Class -> DataCon
 classDataCon clas = case tyConDataCons (classTyCon clas) of
                      (dict_constr:no_more) -> ASSERT( null no_more ) dict_constr 
+                     [] -> panic "classDataCon"
 \end{code}
 
 %************************************************************************
index 67cf5e4..6f664da 100644 (file)
@@ -44,7 +44,6 @@ import TysWiredIn
 import PrelRules
 import Type
 import TcGadt
-import HsBinds
 import Coercion
 import TcType
 import CoreUtils
@@ -162,8 +161,8 @@ Notice that
   Making an explicit case expression allows the simplifier to eliminate
   it in the (common) case where the constructor arg is already evaluated.
 
-[Wrappers for data instance tycons]
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Note [Wrappers for data instance tycons]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 In the case of data instances, the wrapper also applies the coercion turning
 the representation type into the family instance type to cast the result of
 the wrapper.  For example, consider the declarations
@@ -171,27 +170,45 @@ the wrapper.  For example, consider the declarations
   data family Map k :: * -> *
   data instance Map (a, b) v = MapPair (Map a (Pair b v))
 
-The tycon to which the datacon MapPair belongs gets a unique internal name of
-the form :R123Map, and we call it the representation tycon.  In contrast, Map
-is the family tycon (accessible via tyConFamInst_maybe).  The wrapper and work
-of MapPair get the types
+The tycon to which the datacon MapPair belongs gets a unique internal
+name of the form :R123Map, and we call it the representation tycon.
+In contrast, Map is the family tycon (accessible via
+tyConFamInst_maybe). A coercion allows you to move between
+representation and family type.  It is accessible from :R123Map via
+tyConFamilyCoercion_maybe and has kind
+
+  Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
+
+The wrapper and worker of MapPair get the types
 
   $WMapPair :: forall a b v. Map a (Map a b v) -> Map (a, b) v
+  $WMapPair a b v = $wMapPair a b v `cast` sym (Co123Map a b v)
+
   $wMapPair :: forall a b v. Map a (Map a b v) -> :R123Map a b v
 
-which implies that the wrapper code will have to apply the coercion moving
-between representation and family type.  It is accessible via
-tyConFamilyCoercion_maybe and has kind
+This coercion is conditionally applied by wrapFamInstBody.
 
-  Co123Map a b v :: {Map (a, b) v :=: :R123Map a b v}
+It's a bit more complicated if the data instance is a GADT as well!
 
-This coercion is conditionally applied by wrapFamInstBody.
+   data instance T [a] where
+       T1 :: forall b. b -> T [Maybe b]
+Hence
+   Co7T a :: T [a] ~ :R7T a
+
+Now we want
+
+  $WT1 :: forall b. b -> T [Maybe b]
+  $WT1 a b v = $wT1 b (Maybe b) (Maybe b) 
+                       `cast` sym (Co7T (Maybe b))
+
+  $wT1 :: forall b c. (b ~ Maybe c) => b -> :R7T c
 
 \begin{code}
 mkDataConIds :: Name -> Name -> DataCon -> DataConIds
 mkDataConIds wrap_name wkr_name data_con
-  | isNewTyCon tycon
-  = DCIds Nothing nt_work_id                 -- Newtype, only has a worker
+  | isNewTyCon tycon                   -- Newtype, only has a worker
+  , not (isFamInstTyCon tycon)         -- unless it's a family instancex
+  = DCIds Nothing nt_work_id                 
 
   | any isMarkedStrict all_strict_marks             -- Algebraic, needs wrapper
     || not (null eq_spec)                   -- NB: LoadIface.ifaceDeclSubBndrs
@@ -202,34 +219,18 @@ mkDataConIds wrap_name wkr_name data_con
   = DCIds Nothing wrk_id
   where
     (univ_tvs, ex_tvs, eq_spec, 
-     theta, orig_arg_tys)          = dataConFullSig data_con
-    tycon                          = dataConTyCon data_con
+     theta, orig_arg_tys, res_ty) = dataConFullSig data_con
+    res_ty_args                          = tyConAppArgs res_ty
+    tycon                         = dataConTyCon data_con
 
        ----------- Wrapper --------------
        -- We used to include the stupid theta in the wrapper's args
        -- but now we don't.  Instead the type checker just injects these
        -- extra constraints where necessary.
     wrap_tvs = (univ_tvs `minusList` map fst eq_spec) ++ ex_tvs
-    subst         = mkTopTvSubst eq_spec
-    famSubst      = ASSERT( length (tyConTyVars tycon  ) ==  
-                            length (mkTyVarTys univ_tvs)   )
-                    zipTopTvSubst (tyConTyVars tycon) (mkTyVarTys univ_tvs)
-                    -- substitution mapping the type constructor's type
-                    -- arguments to the universals of the data constructor
-                    -- (crucial when type checking interfaces)
-    dict_tys       = mkPredTys theta
-    result_ty_args = substTyVars subst univ_tvs
-    result_ty      = case tyConFamInst_maybe tycon of
-                        -- ordinary constructor
-                      Nothing            -> mkTyConApp tycon result_ty_args
-                        -- family instance constructor
-                      Just (familyTyCon, 
-                            instTys)     -> 
-                        mkTyConApp familyTyCon ( substTys subst 
-                                               . substTys famSubst 
-                                               $ instTys)
-    wrap_ty        = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
-                    mkFunTys orig_arg_tys $ result_ty
+    dict_tys = mkPredTys theta
+    wrap_ty  = mkForAllTys wrap_tvs $ mkFunTys dict_tys $
+              mkFunTys orig_arg_tys $ res_ty
        -- NB: watch out here if you allow user-written equality 
        --     constraints in data constructor signatures
 
@@ -283,7 +284,7 @@ mkDataConIds wrap_name wkr_name data_con
                   -- e.g.      newtype Eq a => T a = MkT (...)
                   mkCompulsoryUnfolding $ 
                   mkLams wrap_tvs $ Lam id_arg1 $ 
-                  wrapNewTypeBody tycon result_ty_args
+                  wrapNewTypeBody tycon res_ty_args
                        (Var id_arg1)
 
     id_arg1 = mkTemplateLocal 1 (head orig_arg_tys)
@@ -318,10 +319,10 @@ mkDataConIds wrap_name wkr_name data_con
                    (zip (dict_args ++ id_args) all_strict_marks)
                    i3 []
 
-    con_app _ rep_ids = wrapFamInstBody tycon result_ty_args $
-                         Var wrk_id `mkTyApps`  result_ty_args
-                                    `mkVarApps` ex_tvs
-                                    `mkTyApps`  map snd eq_spec
+    con_app _ rep_ids = wrapFamInstBody tycon res_ty_args $
+                         Var wrk_id `mkTyApps`  res_ty_args
+                                    `mkVarApps` ex_tvs                 
+                                    `mkTyApps`  map snd eq_spec        -- Equality evidence 
                                     `mkVarApps` reverse rep_ids
 
     (dict_args,i2) = mkLocals 1  dict_tys
@@ -340,7 +341,7 @@ mkDataConIds wrap_name wkr_name data_con
                MarkedStrict 
                   | isUnLiftedType (idType arg) -> body i (arg:rep_args)
                   | otherwise ->
-                       Case (Var arg) arg result_ty [(DEFAULT,[], body i (arg:rep_args))]
+                       Case (Var arg) arg res_ty [(DEFAULT,[], body i (arg:rep_args))]
 
                MarkedUnboxed
                   -> unboxProduct i (Var arg) (idType arg) the_body 
@@ -361,18 +362,6 @@ mAX_CPR_SIZE = 10
 mkLocals i tys = (zipWith mkTemplateLocal [i..i+n-1] tys, i+n)
               where
                 n = length tys
-
--- If the type constructor is a representation type of a data instance, wrap
--- the expression into a cast adjusting the expression type, which is an
--- instance of the representation type, to the corresponding instance of the
--- family instance type.
---
-wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
-wrapFamInstBody tycon args result_expr
-  | Just co_con <- tyConFamilyCoercion_maybe tycon
-  = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) result_expr
-  | otherwise
-  = result_expr
 \end{code}
 
 
@@ -453,23 +442,41 @@ Note the forall'd tyvars of the selector are just the free tyvars
 of the result type; there may be other tyvars in the constructor's
 type (e.g. 'b' in T2).
 
-\begin{code}
+Note [Selector running example]
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+It's OK to combine GADTs and type families.  Here's a running example:
+
+       data instance T [a] where 
+         T1 { fld :: b } :: T [Maybe b]
+
+The representation type looks like this
+       data :R7T a where
+         T1 { fld :: b } :: :R7T (Maybe b)
 
--- Steps for handling "naughty" vs "non-naughty" selectors:
---  1. Determine naughtiness by comparing field type vs result type
---  2. Install naughty ones with selector_ty of type _|_ and fill in mzero for info
---  3. If it's not naughty, do the normal plan.
+and there's coercion from the family type to the representation type
+       :CoR7T a :: T [a] ~ :R7T a
 
+The selector we want for fld looks like this:
+
+       fld :: forall b. T [Maybe b] -> b
+       fld = /\b. \(d::T [Maybe b]).
+             case d `cast` :CoR7T (Maybe b) of 
+               T1 (x::b) -> x
+
+The scrutinee of the case has type :R7T (Maybe b), which can be
+gotten by appying the eq_spec to the univ_tvs of the data con.
+
+\begin{code}
 mkRecordSelId :: TyCon -> FieldLabel -> Id
 mkRecordSelId tycon field_label
        -- Assumes that all fields with the same field label have the same type
   | is_naughty = naughty_id
   | otherwise  = sel_id
   where
-    is_naughty = not (tyVarsOfType field_ty `subVarSet` res_tv_set)
+    is_naughty = not (tyVarsOfType field_ty `subVarSet` data_tv_set)
     sel_id_details = RecordSelId tycon field_label is_naughty
 
-    -- Escapist case here for naughty construcotrs
+    -- Escapist case here for naughty constructors
     -- We give it no IdInfo, and a type of forall a.a (never looked at)
     naughty_id = mkGlobalId sel_id_details field_label forall_a_a noCafIdInfo
     forall_a_a = mkForAllTy alphaTyVar (mkTyVarTy alphaTyVar)
@@ -481,10 +488,9 @@ mkRecordSelId tycon field_label
     has_field con     = field_label `elem` dataConFieldLabels con
 
     con1       = head data_cons_w_field
-    res_tys    = dataConResTys con1
-    res_tv_set = tyVarsOfTypes res_tys
-    res_tvs    = varSetElems res_tv_set
-    data_ty    = mkTyConApp tycon res_tys
+    (univ_tvs, _, eq_spec, _, _, data_ty) = dataConFullSig con1
+    data_tv_set        = tyVarsOfType data_ty
+    data_tvs   = varSetElems data_tv_set
     field_ty   = dataConFieldType con1 field_label
     
        -- *Very* tiresomely, the selectors are (unnecessarily!) overloaded over
@@ -499,10 +505,9 @@ mkRecordSelId tycon field_label
     n_stupid_dicts  = length stupid_dict_tys
 
     (field_tyvars,pre_field_theta,field_tau) = tcSplitSigmaTy field_ty
-  
-    field_theta  = filter (not . isEqPred) pre_field_theta
-    field_dict_tys                      = mkPredTys field_theta
-    n_field_dict_tys                    = length field_dict_tys
+    field_theta       = filter (not . isEqPred) pre_field_theta
+    field_dict_tys    = mkPredTys field_theta
+    n_field_dict_tys  = length field_dict_tys
        -- If the field has a universally quantified type we have to 
        -- be a bit careful.  Suppose we have
        --      data R = R { op :: forall a. Foo a => a -> a }
@@ -519,7 +524,7 @@ mkRecordSelId tycon field_label
        --      op (R op) = op
 
     selector_ty :: Type
-    selector_ty  = mkForAllTys res_tvs $ mkForAllTys field_tyvars $
+    selector_ty  = mkForAllTys data_tvs $ mkForAllTys field_tyvars $
                   mkFunTys stupid_dict_tys  $  mkFunTys field_dict_tys $
                   mkFunTy data_ty field_tau
       
@@ -546,7 +551,8 @@ mkRecordSelId tycon field_label
     field_dict_ids   = mkTemplateLocalsNum field_dict_base field_dict_tys
     dict_id_base     = field_dict_base + n_field_dict_tys
     data_id         = mkTemplateLocal dict_id_base data_ty
-    arg_base        = dict_id_base + 1
+    scrut_id        = mkTemplateLocal (dict_id_base+1) scrut_ty
+    arg_base        = dict_id_base + 2
 
     the_alts :: [CoreAlt]
     the_alts   = map mk_alt data_cons_w_field  -- Already sorted by data-con
@@ -559,14 +565,19 @@ mkRecordSelId tycon field_label
     caf_info    | no_default = NoCafRefs
                | otherwise  = MayHaveCafRefs
 
-    sel_rhs = mkLams res_tvs $ mkLams field_tyvars $ 
+    sel_rhs = mkLams data_tvs $ mkLams field_tyvars $ 
              mkLams stupid_dict_ids $ mkLams field_dict_ids $
-             Lam data_id     $ mk_result sel_body
+             Lam data_id $ mk_result sel_body
+
+    scrut_ty_args = substTyVars (mkTopTvSubst eq_spec) univ_tvs
+    scrut_ty     = mkTyConApp tycon scrut_ty_args
+    scrut = unwrapFamInstScrut tycon scrut_ty_args (Var data_id)
+       -- First coerce from the type family to the representation type
 
        -- NB: A newtype always has a vanilla DataCon; no existentials etc
-       --     res_tys will simply be the dataConUnivTyVars
-    sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon res_tys (Var data_id)
-            | otherwise        = Case (Var data_id) data_id field_ty (default_alt ++ the_alts)
+       --     data_tys will simply be the dataConUnivTyVars
+    sel_body | isNewTyCon tycon = unwrapNewTypeBody tycon scrut_ty_args scrut
+            | otherwise        = Case scrut scrut_id field_ty (default_alt ++ the_alts)
 
     mk_result poly_result = mkVarApps (mkVarApps poly_result field_tyvars) field_dict_ids
        -- We pull the field lambdas to the top, so we need to 
@@ -577,12 +588,12 @@ mkRecordSelId tycon field_label
        --      foo = /\a. \t:T. case t of { MkT f -> f a }
 
     mk_alt data_con 
-      =   ASSERT2( res_ty `tcEqType` field_ty, ppr data_con $$ ppr res_ty $$ ppr field_ty )
+      =   ASSERT2( data_ty `tcEqType` field_ty, ppr data_con $$ ppr data_ty $$ ppr field_ty )
          mkReboxingAlt rebox_uniqs data_con (ex_tvs ++ co_tvs ++ arg_vs) rhs
       where
            -- get pattern binders with types appropriately instantiated
        arg_uniqs = map mkBuiltinUnique [arg_base..]
-        (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con res_tys
+        (ex_tvs, co_tvs, arg_vs) = dataConOrigInstPat arg_uniqs data_con scrut_ty_args
 
        rebox_base  = arg_base + length ex_tvs + length co_tvs + length arg_vs
        rebox_uniqs = map mkBuiltinUnique [rebox_base..]
@@ -599,9 +610,9 @@ mkRecordSelId tycon field_label
                -- and apply to (Maybe b'), to get (Maybe b)
         Succeeded refinement = gadtRefine emptyRefinement ex_tvs co_tvs
        the_arg_id_ty = idType the_arg_id
-        (rhs, res_ty) = case refineType refinement the_arg_id_ty of
-                         Just (co, res_ty) -> (Cast (Var the_arg_id) co, res_ty)
-                         Nothing           -> (Var the_arg_id, the_arg_id_ty)
+        (rhs, data_ty) = case refineType refinement the_arg_id_ty of
+                         Just (co, data_ty) -> (Cast (Var the_arg_id) co, data_ty)
+                         Nothing            -> (Var the_arg_id, the_arg_id_ty)
 
        field_vs    = filter (not . isPredTy . idType) arg_vs 
        the_arg_id  = assoc "mkRecordSelId:mk_alt" (field_lbls `zip` field_vs) field_label
@@ -806,7 +817,16 @@ mkDictSelId name clas
     rhs_body | isNewTyCon tycon = unwrapNewTypeBody tycon (map mkTyVarTy tyvars) (Var dict_id)
             | otherwise        = Case (Var dict_id) dict_id (idType the_arg_id)
                                       [(DataAlt data_con, arg_ids, Var the_arg_id)]
+\end{code}
+
 
+%************************************************************************
+%*                                                                     *
+       Wrapping and unwrapping newtypes and type families
+%*                                                                     *
+%************************************************************************
+
+\begin{code}
 wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
 -- The wrapper for the data constructor for a newtype looks like this:
 --     newtype T a = MkT (a,Int)
@@ -818,14 +838,14 @@ wrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
 -- body of the wrapper, namely
 --     e `cast` (CoT [a])
 --
--- If a coercion constructor is prodivided in the newtype, then we use
+-- If a coercion constructor is provided in the newtype, then we use
 -- it, otherwise the wrap/unwrap are both no-ops 
 --
--- If the we are dealing with a newtype instance, we have a second coercion
+-- If the we are dealing with a newtype *instance*, we have a second coercion
 -- identifying the family instance with the constructor of the newtype
 -- instance.  This coercion is applied in any case (ie, composed with the
 -- coercion constructor of the newtype or applied by itself).
---
+
 wrapNewTypeBody tycon args result_expr
   = wrapFamInstBody tycon args inner
   where
@@ -839,7 +859,7 @@ wrapNewTypeBody tycon args result_expr
 -- be done via a CoPat by the type checker.  We have to do it this way as
 -- computing the right type arguments for the coercion requires more than just
 -- a spliting operation (cf, TcPat.tcConPat).
---
+
 unwrapNewTypeBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
 unwrapNewTypeBody tycon args result_expr
   | Just co_con <- newTyConCo_maybe tycon
@@ -847,7 +867,24 @@ unwrapNewTypeBody tycon args result_expr
   | otherwise
   = result_expr
 
+-- If the type constructor is a representation type of a data instance, wrap
+-- the expression into a cast adjusting the expression type, which is an
+-- instance of the representation type, to the corresponding instance of the
+-- family instance type.
+-- See Note [Wrappers for data instance tycons]
+wrapFamInstBody :: TyCon -> [Type] -> CoreExpr -> CoreExpr
+wrapFamInstBody tycon args body
+  | Just co_con <- tyConFamilyCoercion_maybe tycon
+  = mkCoerce (mkSymCoercion (mkTyConApp co_con args)) body
+  | otherwise
+  = body
 
+unwrapFamInstScrut :: TyCon -> [Type] -> CoreExpr -> CoreExpr
+unwrapFamInstScrut tycon args scrut
+  | Just co_con <- tyConFamilyCoercion_maybe tycon
+  = mkCoerce (mkTyConApp co_con args) scrut
+  | otherwise
+  = scrut
 \end{code}
 
 
index 51144ec..025004f 100644 (file)
@@ -18,8 +18,9 @@ module PprTyThing (
 
 import qualified GHC
 
-import GHC ( TyThing(..), SrcLoc )
-import DataCon ( dataConResTys )
+import TyCon   ( tyConFamInst_maybe )
+import Type    ( pprTypeApp )
+import GHC     ( TyThing(..), SrcLoc )
 import Outputable
 
 -- -----------------------------------------------------------------------------
@@ -66,8 +67,11 @@ pprTyThingHdr exts (ADataCon dataCon) = pprDataConSig exts dataCon
 pprTyThingHdr exts (ATyCon tyCon)     = pprTyConHdr   exts tyCon
 pprTyThingHdr exts (AClass cls)       = pprClassHdr   exts cls
         
-pprTyConHdr exts tyCon =
-  addFamily (ptext keyword) <+> ppr_bndr tyCon <+> hsep (map ppr vars)
+pprTyConHdr exts tyCon
+  | Just (fam_tc, tys) <- tyConFamInst_maybe tyCon
+  = ptext keyword <+> ptext SLIT("instance") <+> pprTypeApp (ppr_bndr tyCon) tys
+  | otherwise
+  = ptext keyword <+> opt_family <+> ppr_bndr tyCon <+> hsep (map ppr vars)
   where
     vars | GHC.isPrimTyCon tyCon || 
           GHC.isFunTyCon tyCon = take (GHC.tyConArity tyCon) GHC.alphaTyVars
@@ -77,9 +81,9 @@ pprTyConHdr exts tyCon =
             | GHC.isNewTyCon tyCon = SLIT("newtype")
             | otherwise            = SLIT("data")
 
-    addFamily keytext 
-      | GHC.isOpenTyCon tyCon = keytext <> ptext SLIT(" family")
-      | otherwise             = keytext
+    opt_family
+      | GHC.isOpenTyCon tyCon = ptext SLIT("family")
+      | otherwise             = empty
 
 pprDataConSig exts dataCon =
   ppr_bndr dataCon <+> dcolon <+> pprType exts (GHC.dataConType dataCon)
@@ -143,10 +147,9 @@ pprDataConDecl exts gadt_style show_label dataCon
   | otherwise      = ppr_bndr dataCon <+> dcolon <+> 
                        sep [ ppr_tvs, GHC.pprThetaArrow theta, pp_tau ]
   where
-    (tyvars, theta, argTypes) = GHC.dataConSig dataCon
+    (tyvars, theta, argTypes, res_ty) = GHC.dataConSig dataCon
     tyCon = GHC.dataConTyCon dataCon
     labels = GHC.dataConFieldLabels dataCon
-    res_tys = dataConResTys dataCon
     qualVars = filter (flip notElem (GHC.tyConTyVars tyCon)) tyvars
     stricts = GHC.dataConStrictMarks dataCon
     tys_w_strs = zip stricts argTypes
@@ -157,8 +160,7 @@ pprDataConDecl exts gadt_style show_label dataCon
                                hsep (map ppr qualVars) <> dot
 
        -- printing out the dataCon as a type signature, in GADT style
-    pp_tau = foldr add pp_res_ty tys_w_strs
-    pp_res_ty = GHC.pprTypeApp (ppr_bndr tyCon) res_tys
+    pp_tau = foldr add (ppr res_ty) tys_w_strs
     add (str,ty) pp_ty = pprBangTy str ty <+> arrow <+> pp_ty
 
     pprParendBangTy (strict,ty)
index ca3433c..14c12a5 100644 (file)
@@ -546,7 +546,7 @@ tcConPat :: PatState -> SrcSpan -> DataCon -> TyCon
         -> HsConDetails Name (LPat Name) -> (PatState -> TcM a)
         -> TcM (Pat TcId, [TcTyVar], a)
 tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
-  = do { let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig data_con
+  = do { let (univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _) = dataConFullSig data_con
              skol_info = PatSkol data_con
              origin    = SigOrigin skol_info
 
@@ -583,8 +583,8 @@ tcConPat pstate con_span data_con tycon pat_ty arg_pats thing_inside
             ex_tvs' ++ inner_tvs, res)
        }
   where
-    -- Split against the family tycon if the pattern constructor belongs to a
-    -- representation tycon.
+    -- Split against the family tycon if the pattern constructor 
+    -- belongs to a representation tycon.
     --
     boxySplitTyConAppWithFamily tycon pat_ty =
       traceTc traceMsg >>
index 4313ad9..a1ca8ca 100644 (file)
@@ -960,23 +960,23 @@ checkValidTyCon tc
                -- NB: this check assumes that all the constructors of a given
                -- data type use the same type variables
         where
-        tvs1 = mkVarSet (dataConAllTyVars con1)
-        res1 = dataConResTys con1
+       (tvs1, _, _, res1) = dataConSig con1
+        ts1 = mkVarSet tvs1
         fty1 = dataConFieldType con1 label
 
         checkOne (_, con2)    -- Do it bothways to ensure they are structurally identical
-           = do { checkFieldCompat label con1 con2 tvs1 res1 res2 fty1 fty2
-                ; checkFieldCompat label con2 con1 tvs2 res2 res1 fty2 fty1 }
+           = do { checkFieldCompat label con1 con2 ts1 res1 res2 fty1 fty2
+                ; checkFieldCompat label con2 con1 ts2 res2 res1 fty2 fty1 }
            where        
-                tvs2 = mkVarSet (dataConAllTyVars con2)
-               res2 = dataConResTys con2 
+               (tvs2, _, _, res2) = dataConSig con2
+               ts2 = mkVarSet tvs2
                 fty2 = dataConFieldType con2 label
 
 checkFieldCompat fld con1 con2 tvs1 res1 res2 fty1 fty2
   = do { checkTc (isJust mb_subst1) (resultTypeMisMatch fld con1 con2)
        ; checkTc (isJust mb_subst2) (fieldTypeMisMatch fld con1 con2) }
   where
-    mb_subst1 = tcMatchTys tvs1 res1 res2
+    mb_subst1 = tcMatchTy tvs1 res1 res2
     mb_subst2 = tcMatchTyX tvs1 (expectJust "checkFieldCompat" mb_subst1) fty1 fty2
 
 -------------------------------
@@ -1003,7 +1003,7 @@ checkNewDataCon con
                -- No existentials
     }
   where
-    (univ_tvs, ex_tvs, eq_spec, theta, arg_tys) = dataConFullSig con
+    (_univ_tvs, ex_tvs, eq_spec, theta, arg_tys, _res_ty) = dataConFullSig con
 
 -------------------------------
 checkValidClass :: Class -> TcM ()
index bfff2c8..728f58b 100644 (file)
@@ -890,11 +890,11 @@ dataConsStupidTheta (con1:cons)
   = nubBy tcEqPred all_preds
   where
     all_preds    = dataConStupidTheta con1 ++ other_stupids
-    res_tys1     = dataConResTys con1
-    tvs1         = tyVarsOfTypes res_tys1
+    res_ty1       = dataConOrigResTy con1
     other_stupids = [ substPred subst pred
                    | con <- cons
-                   , let Just subst = tcMatchTys tvs1 res_tys1 (dataConResTys con)
+                   , let (tvs, _, _, res_ty) = dataConSig con
+                         Just subst = tcMatchTy (mkVarSet tvs) res_ty res_ty1
                    , pred <- dataConStupidTheta con ]
 dataConsStupidTheta [] = panic "dataConsStupidTheta"
 \end{code}
index 8b2b24c..dfbf02c 100644 (file)
@@ -203,10 +203,11 @@ data AlgTyConRhs
   | OpenTyCon {
 
       otArgPoss   :: Maybe [Int],  
-       -- for associated families: for each tyvar in the AT decl, gives the
-       -- position of that tyvar in the class argument list (starting from 0).
-       -- NB: Length is less than tyConArity iff higher kind signature.
-       -- NB: Just _ <=> associated (not toplevel) family
+       -- Nothing <=> top-level indexed type family
+       -- Just ns <=> associated (not toplevel) family
+       --   In the latter case, for each tyvar in the AT decl, 'ns' gives the
+       --   position of that tyvar in the class argument list (starting from 0).
+       --   NB: Length is less than tyConArity iff higher kind signature.
        
       otIsNewtype :: Bool           
         -- is a newtype (rather than data type)?
@@ -274,15 +275,16 @@ data AlgTyConParent
 
   | FamilyTyCon                -- Type constructors representing an instance of a type
        TyCon           --   The type family
-       [Type]          --   Instance types
+       [Type]          --   Instance types; free variables are the tyConTyVars
+                       --      of this TyCon
        TyCon           --   A CoercionTyCon identifying the representation 
                        --     type with the type instance family.  
                        --      c.f. Note [Newtype coercions]
        -- E.g.  data intance T [a] = ...
        -- gives a representation tycon:
-       --      data T77 a = ...
-       --      axiom co a :: T [a] ~ T77 a
-       -- with T77's algTcParent = FamilyTyCon T [a] co
+       --      data :R7T a = ...
+       --      axiom co a :: T [a] ~ :R7T a
+       -- with :R7T's algTcParent = FamilyTyCon T [a] co
 
 data SynTyConRhs
   = OpenSynTyCon Kind          -- Type family: *result* kind given
index 34993ad..f99c56c 100644 (file)
@@ -7,7 +7,8 @@ module Unify (
        -- Matching of types: 
        --      the "tc" prefix indicates that matching always
        --      respects newtypes (rather than looking through them)
-       tcMatchTys, tcMatchTyX, ruleMatchTyX, tcMatchPreds, MatchEnv(..)
+       tcMatchTy, tcMatchTys, tcMatchTyX, 
+       ruleMatchTyX, tcMatchPreds, MatchEnv(..)
    ) where
 
 #include "HsVersions.h"
@@ -57,10 +58,26 @@ data MatchEnv
        , me_env   :: RnEnv2    -- Renaming envt for nested foralls
        }                       --   In-scope set includes template tyvars
 
+tcMatchTy :: TyVarSet          -- Template tyvars
+         -> Type               -- Template
+         -> Type               -- Target
+         -> Maybe TvSubst      -- One-shot; in principle the template
+                               -- variables could be free in the target
+
+tcMatchTy tmpls ty1 ty2
+  = case match menv emptyTvSubstEnv 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 }
+    in_scope = mkInScopeSet (tmpls `unionVarSet` tyVarsOfType ty2)
+       -- We're assuming that all the interesting 
+       -- tyvars in tys1 are in tmpls
+
 tcMatchTys :: TyVarSet         -- Template tyvars
-        -> [Type]              -- Template
-        -> [Type]              -- Target
-        -> Maybe TvSubst       -- One-shot; in principle the template
+          -> [Type]            -- Template
+          -> [Type]            -- Target
+          -> Maybe TvSubst     -- One-shot; in principle the template
                                -- variables could be free in the target
 
 tcMatchTys tmpls tys1 tys2