Re-work the newtype-deriving support
[ghc-hetmet.git] / compiler / types / Coercion.lhs
1
2  Module for type coercions, as in System FC.
3
4 Coercions are represented as types, and their kinds tell what types the 
5 coercion works on. 
6
7 The coercion kind constructor is a special TyCon that must always be saturated
8
9   typeKind (symCoercion type) :: TyConApp CoercionTyCon{...} [type, type]
10
11 \begin{code}
12 module Coercion (
13         Coercion,
14  
15         mkCoKind, mkReflCoKind, splitCoercionKind_maybe, splitCoercionKind,
16         coercionKind, coercionKinds, coercionKindPredTy,
17
18         -- Equality predicates
19         isEqPred, mkEqPred, getEqPredTys, isEqPredTy,  
20
21         -- Coercion transformations
22         mkSymCoercion, mkTransCoercion,
23         mkLeftCoercion, mkRightCoercion, mkInstCoercion, mkAppCoercion,
24         mkForAllCoercion, mkFunCoercion, mkInstsCoercion, mkUnsafeCoercion,
25         mkNewTypeCoercion, mkDataInstCoercion, mkAppsCoercion,
26
27         splitNewTypeRepCo_maybe, decomposeCo,
28
29         unsafeCoercionTyCon, symCoercionTyCon,
30         transCoercionTyCon, leftCoercionTyCon, 
31         rightCoercionTyCon, instCoercionTyCon -- needed by TysWiredIn
32        ) where 
33
34 #include "HsVersions.h"
35
36 import TypeRep
37 import Type       ( Type, Kind, PredType, substTyWith, mkAppTy, mkForAllTy,
38                     mkFunTy, splitAppTy_maybe, splitForAllTy_maybe, coreView,
39                     kindView, mkTyConApp, isCoercionKind, isEqPred, mkAppTys,
40                     coreEqType, splitAppTys, isTyVarTy, splitTyConApp_maybe
41                   )
42 import TyCon      ( TyCon, tyConArity, mkCoercionTyCon, isClosedNewTyCon,
43                     newTyConRhs, newTyConCo_maybe, 
44                     isCoercionTyCon, isCoercionTyCon_maybe )
45 import Var        ( Var, TyVar, isTyVar, tyVarKind )
46 import Name       ( BuiltInSyntax(..), Name, mkWiredInName, tcName )
47 import OccName    ( mkOccNameFS )
48 import PrelNames  ( symCoercionTyConKey, 
49                     transCoercionTyConKey, leftCoercionTyConKey,
50                     rightCoercionTyConKey, instCoercionTyConKey, 
51                     unsafeCoercionTyConKey, gHC_PRIM
52                   )
53 import Util       ( lengthIs, snocView )
54 import Unique     ( hasKey )
55 import BasicTypes ( Arity )
56 import Outputable
57
58
59
60 ------------------------------
61 decomposeCo :: Arity -> Coercion -> [Coercion]
62 -- (decomposeCo 3 c) = [right (left (left c)), right (left c), right c]
63 -- So this breaks a coercion with kind T A B C :=: T D E F into
64 -- a list of coercions of kinds A :=: D, B :=: E and E :=: F
65 decomposeCo n co
66   = go n co []
67   where
68     go 0 co cos = cos
69     go n co cos = go (n-1) (mkLeftCoercion co)
70                            (mkRightCoercion co : cos)
71
72 ------------------------------
73
74 -------------------------------------------------------
75 -- and some coercion kind stuff
76
77 isEqPredTy (PredTy pred) = isEqPred pred
78 isEqPredTy other         = False
79
80 mkEqPred :: (Type, Type) -> PredType
81 mkEqPred (ty1, ty2) = EqPred ty1 ty2
82
83 getEqPredTys :: PredType -> (Type,Type)
84 getEqPredTys (EqPred ty1 ty2) = (ty1, ty2)
85 getEqPredTys other            = pprPanic "getEqPredTys" (ppr other)
86
87 mkCoKind :: Type -> Type -> CoercionKind
88 mkCoKind ty1 ty2 = PredTy (EqPred ty1 ty2)
89
90 mkReflCoKind :: Type -> CoercionKind
91 mkReflCoKind ty = mkCoKind ty ty
92
93 splitCoercionKind :: CoercionKind -> (Type, Type)
94 splitCoercionKind co | Just co' <- kindView co = splitCoercionKind co'
95 splitCoercionKind (PredTy (EqPred ty1 ty2))    = (ty1, ty2)
96
97 splitCoercionKind_maybe :: Kind -> Maybe (Type, Type)
98 splitCoercionKind_maybe co | Just co' <- kindView co = splitCoercionKind_maybe co'
99 splitCoercionKind_maybe (PredTy (EqPred ty1 ty2)) = Just (ty1, ty2)
100 splitCoercionKind_maybe other = Nothing
101
102 isCoVar :: Var -> Bool
103 isCoVar tv = isTyVar tv && isCoercionKind (tyVarKind tv)
104
105 type Coercion     = Type
106 type CoercionKind = Kind        -- A CoercionKind is always of form (ty1 :=: ty2)
107
108 coercionKind :: Coercion -> (Type, Type)
109 --      c :: (t1 :=: t2)
110 -- Then (coercionKind c) = (t1,t2)
111 coercionKind (TyVarTy a) | isCoVar a = splitCoercionKind (tyVarKind a)
112                          | otherwise = let t = (TyVarTy a) in (t, t)
113 coercionKind (AppTy ty1 ty2) 
114   = let (t1, t2) = coercionKind ty1
115         (s1, s2) = coercionKind ty2 in
116     (mkAppTy t1 s1, mkAppTy t2 s2)
117 coercionKind (TyConApp tc args)
118   | Just (ar, rule) <- isCoercionTyCon_maybe tc 
119     -- CoercionTyCons carry their kinding rule, so we use it here
120   = if length args >= ar 
121     then splitCoercionKind (rule args)
122     else pprPanic ("arity/arguments mismatch in coercionKind:") 
123              (ppr ar $$ ppr tc <+> ppr args)
124   | otherwise
125   = let (lArgs, rArgs) = coercionKinds args in
126     (TyConApp tc lArgs, TyConApp tc rArgs)
127 coercionKind (FunTy ty1 ty2) 
128   = let (t1, t2) = coercionKind ty1
129         (s1, s2) = coercionKind ty2 in
130     (mkFunTy t1 s1, mkFunTy t2 s2)
131 coercionKind (ForAllTy tv ty) 
132   = let (ty1, ty2) = coercionKind ty in
133     (ForAllTy tv ty1, ForAllTy tv ty2)
134 coercionKind (NoteTy _ ty) = coercionKind ty
135 coercionKind (PredTy (EqPred c1 c2)) 
136   = let k1 = coercionKindPredTy c1
137         k2 = coercionKindPredTy c2 in
138     (k1,k2)
139 coercionKind (PredTy (ClassP cl args)) 
140   = let (lArgs, rArgs) = coercionKinds args in
141     (PredTy (ClassP cl lArgs), PredTy (ClassP cl rArgs))
142 coercionKind (PredTy (IParam name ty))
143   = let (ty1, ty2) = coercionKind ty in
144     (PredTy (IParam name ty1), PredTy (IParam name ty2))
145
146 coercionKindPredTy :: Coercion -> CoercionKind
147 coercionKindPredTy c = let (t1, t2) = coercionKind c in mkCoKind t1 t2
148
149 coercionKinds :: [Coercion] -> ([Type], [Type])
150 coercionKinds tys = unzip $ map coercionKind tys
151
152 -------------------------------------
153 -- Coercion kind and type mk's
154 -- (make saturated TyConApp CoercionTyCon{...} args)
155
156 mkCoercion coCon args = ASSERT( tyConArity coCon == length args ) 
157                         TyConApp coCon args
158
159 mkAppCoercion, mkFunCoercion, mkTransCoercion, mkInstCoercion :: Coercion -> Coercion -> Coercion
160 mkSymCoercion, mkLeftCoercion, mkRightCoercion :: Coercion -> Coercion
161
162 mkAppCoercion    co1 co2 = mkAppTy co1 co2
163 mkAppsCoercion   co1 tys = foldl mkAppTy co1 tys
164 -- note that a TyVar should be used here, not a CoVar (nor a TcTyVar)
165 mkForAllCoercion tv  co  = ASSERT ( isTyVar tv ) mkForAllTy tv co
166 mkFunCoercion    co1 co2 = mkFunTy co1 co2
167
168
169 -- This smart constructor creates a sym'ed version its argument,
170 -- but tries to push the sym's down to the leaves.  If we come to
171 -- sym tv or sym tycon then we can drop the sym because tv and tycon
172 -- are reflexive coercions
173 mkSymCoercion co      
174   | Just co2 <- splitSymCoercion_maybe co = co2
175      -- sym (sym co) --> co
176   | Just (co1, arg_tys) <- splitTyConApp_maybe co
177   , not (isCoercionTyCon co1) = mkTyConApp co1 (map mkSymCoercion arg_tys)
178      -- we can drop the sym for a TyCon 
179      -- sym (ty [t1, ..., tn]) --> ty [sym t1, ..., sym tn] 
180   | (co1, arg_tys) <- splitAppTys co
181   , isTyVarTy co1 = mkAppTys (maybe_drop co1) (map mkSymCoercion arg_tys)
182      -- sym (tv [t1, ..., tn]) --> tv [sym t1, ..., sym tn]
183      --   if tv type variable
184      -- sym (cv [t1, ..., tn]) --> (sym cv) [sym t1, ..., sym tn]
185      --   if cv is a coercion variable
186      -- fall through if head is a CoercionTyCon
187   | Just (co1, co2) <- splitTransCoercion_maybe co
188      -- sym (co1 `trans` co2) --> (sym co2) `trans (sym co2)
189   = mkTransCoercion (mkSymCoercion co2) (mkSymCoercion co1)
190   | Just (co, ty) <- splitInstCoercion_maybe co
191      -- sym (co @ ty) --> (sym co) @ ty
192   = mkInstCoercion (mkSymCoercion co) ty
193   | Just co <- splitLeftCoercion_maybe co
194      -- sym (left co) --> left (sym co)
195   = mkLeftCoercion (mkSymCoercion co)
196   | Just co <- splitRightCoercion_maybe co
197      -- sym (right co) --> right (sym co)
198   = mkRightCoercion (mkSymCoercion co)
199   where
200     maybe_drop (TyVarTy tv) 
201         | isCoVar tv = mkCoercion symCoercionTyCon [TyVarTy tv]
202         | otherwise  = TyVarTy tv
203     maybe_drop other = other
204 mkSymCoercion (ForAllTy tv ty) = ForAllTy tv (mkSymCoercion ty)
205 -- for atomic types and constructors, we can just ignore sym since these
206 -- are reflexive coercions
207 mkSymCoercion (TyVarTy tv) 
208   | isCoVar tv = mkCoercion symCoercionTyCon [TyVarTy tv]
209   | otherwise  = TyVarTy tv
210 mkSymCoercion co = mkCoercion symCoercionTyCon [co] 
211
212 -- Smart constructors for left and right
213 mkLeftCoercion co 
214   | Just (co', _) <- splitAppCoercion_maybe co = co'
215   | otherwise                            = mkCoercion leftCoercionTyCon [co]
216
217 mkRightCoercion  co      
218   | Just (co1, co2) <- splitAppCoercion_maybe co = co2
219   | otherwise = mkCoercion rightCoercionTyCon [co]
220
221 mkTransCoercion co1 co2 = mkCoercion transCoercionTyCon [co1, co2]
222
223 mkInstCoercion  co ty = mkCoercion instCoercionTyCon  [co, ty]
224
225 mkInstsCoercion co tys = foldl mkInstCoercion co tys
226
227 splitSymCoercion_maybe :: Coercion -> Maybe Coercion
228 splitSymCoercion_maybe (TyConApp tc [co]) = 
229   if tc `hasKey` symCoercionTyConKey
230   then Just co
231   else Nothing
232 splitSymCoercion_maybe co = Nothing
233
234 splitAppCoercion_maybe :: Coercion -> Maybe (Coercion, Coercion)
235 -- Splits a coercion application, being careful *not* to split (left c), etc
236 -- which are really sytactic constructs, not applications
237 splitAppCoercion_maybe co  | Just co' <- coreView co = splitAppCoercion_maybe co'
238 splitAppCoercion_maybe (FunTy ty1 ty2)   = Just (TyConApp funTyCon [ty1], ty2)
239 splitAppCoercion_maybe (AppTy ty1 ty2)   = Just (ty1, ty2)
240 splitAppCoercion_maybe (TyConApp tc tys) 
241    | not (isCoercionTyCon tc)
242    = case snocView tys of
243        Just (tys', ty') -> Just (TyConApp tc tys', ty')
244        Nothing          -> Nothing
245 splitAppCoercion_maybe co = Nothing
246
247 splitTransCoercion_maybe :: Coercion -> Maybe (Coercion, Coercion)
248 splitTransCoercion_maybe (TyConApp tc [ty1, ty2]) 
249  = if tc `hasKey` transCoercionTyConKey then
250        Just (ty1, ty2)
251    else
252        Nothing
253 splitTransCoercion_maybe other = Nothing
254
255 splitInstCoercion_maybe :: Coercion -> Maybe (Coercion, Type)
256 splitInstCoercion_maybe (TyConApp tc [ty1, ty2])
257  = if tc `hasKey` instCoercionTyConKey then
258        Just (ty1, ty2)
259     else
260        Nothing
261 splitInstCoercion_maybe other = Nothing
262
263 splitLeftCoercion_maybe :: Coercion -> Maybe Coercion
264 splitLeftCoercion_maybe (TyConApp tc [co])
265  = if tc `hasKey` leftCoercionTyConKey then
266        Just co
267    else
268        Nothing
269 splitLeftCoercion_maybe other = Nothing
270
271 splitRightCoercion_maybe :: Coercion -> Maybe Coercion
272 splitRightCoercion_maybe (TyConApp tc [co])
273  = if tc `hasKey` rightCoercionTyConKey then
274        Just co
275    else
276        Nothing
277 splitRightCoercion_maybe other = Nothing
278
279 -- Unsafe coercion is not safe, it is used when we know we are dealing with
280 -- bottom, which is one case in which it is safe.  It is also used to 
281 -- implement the unsafeCoerce# primitive.
282 mkUnsafeCoercion :: Type -> Type -> Coercion
283 mkUnsafeCoercion ty1 ty2 
284   = mkCoercion unsafeCoercionTyCon [ty1, ty2]
285
286
287 -- See note [Newtype coercions] in TyCon
288 mkNewTypeCoercion :: Name -> TyCon -> ([TyVar], Type) -> TyCon
289 mkNewTypeCoercion name tycon (tvs, rhs_ty)
290   = mkCoercionTyCon name co_con_arity (mkKindingFun rule)
291   where
292     co_con_arity = length tvs
293
294     rule args = (TyConApp tycon tys, substTyWith tvs tys rhs_ty, rest)
295         where
296           tys  = take co_con_arity args
297           rest = drop co_con_arity args
298
299 -- Coercion identifying a data/newtype representation type and its family
300 -- instance.  It has the form `Co tvs :: F ts :=: R tvs', where `Co' is the
301 -- coercion tycon built here, `F' the family tycon and `R' the (derived)
302 -- representation tycon.
303 --
304 mkDataInstCoercion :: Name      -- unique name for the coercion tycon
305                    -> [TyVar]   -- type parameters of the coercion (`tvs')
306                    -> TyCon     -- family tycon (`F')
307                    -> [Type]    -- type instance (`ts')
308                    -> TyCon     -- representation tycon (`R')
309                    -> TyCon     -- => coercion tycon (`Co')
310 mkDataInstCoercion name tvs family instTys rep_tycon
311   = mkCoercionTyCon name coArity (mkKindingFun rule)
312   where
313     coArity = length tvs
314
315     rule args = (substTyWith tvs tys $               -- with sigma = [tys/tvs],
316                    TyConApp family instTys,          --       sigma (F ts)
317                  TyConApp rep_tycon tys,             --   :=: R tys
318                  rest)                               -- surplus arguments
319       where
320         tys  = take coArity args
321         rest = drop coArity args
322
323 --------------------------------------
324 -- Coercion Type Constructors...
325
326 -- Example.  The coercion ((sym c) (sym d) (sym e))
327 -- will be represented by (TyConApp sym [c, sym d, sym e])
328 -- If sym c :: p1=q1
329 --    sym d :: p2=q2
330 --    sym e :: p3=q3
331 -- then ((sym c) (sym d) (sym e)) :: (p1 p2 p3)=(q1 q2 q3)
332 --
333 -- (mkKindingFun f) is given the args [c, sym d, sym e]
334 mkKindingFun :: ([Type] -> (Type, Type, [Type]))
335              -> [Type] -> Kind
336 mkKindingFun f args = 
337   let (ty1, ty2, rest) = f args in 
338   let (argtys1, argtys2) = unzip (map coercionKind rest) in
339   mkCoKind (mkAppTys ty1 argtys1) (mkAppTys ty2 argtys2)
340         
341
342 symCoercionTyCon, transCoercionTyCon, leftCoercionTyCon, rightCoercionTyCon, instCoercionTyCon :: TyCon
343 -- Each coercion TyCon is built with the special CoercionTyCon record and
344 -- carries its own kinding rule.  Such CoercionTyCons must be fully applied
345 -- by any TyConApp in which they are applied, however they may also be over
346 -- applied (see example above) and the kinding function must deal with this.
347 symCoercionTyCon = 
348   mkCoercionTyCon symCoercionTyConName 1 (mkKindingFun flipCoercionKindOf)
349   where
350     flipCoercionKindOf (co:rest) = (ty2, ty1, rest)
351         where
352           (ty1, ty2) = coercionKind co
353
354 transCoercionTyCon = 
355   mkCoercionTyCon transCoercionTyConName 2 (mkKindingFun composeCoercionKindsOf)
356   where
357     composeCoercionKindsOf (co1:co2:rest) = 
358         WARN( not (r1 `coreEqType` a2), text "Strange! Type mismatch in trans coercion, probably a bug")
359         (a1, r2, rest)
360       where
361         (a1, r1) = coercionKind co1
362         (a2, r2) = coercionKind co2 
363
364 leftCoercionTyCon =
365   mkCoercionTyCon leftCoercionTyConName 1 (mkKindingFun leftProjectCoercionKindOf)
366   where
367     leftProjectCoercionKindOf (co:rest) = (ty1, ty2, rest)
368       where
369         (ty1,ty2) = fst (splitCoercionKindOf co)
370
371 rightCoercionTyCon =
372   mkCoercionTyCon rightCoercionTyConName 1 (mkKindingFun rightProjectCoercionKindOf)
373   where
374     rightProjectCoercionKindOf (co:rest) = (ty1, ty2, rest)
375       where
376         (ty1,ty2) = snd (splitCoercionKindOf co)
377
378 splitCoercionKindOf :: Type -> ((Type,Type), (Type,Type))
379 -- Helper for left and right.  Finds coercion kind of its input and
380 -- returns the left and right projections of the coercion...
381 --
382 -- if c :: t1 s1 :=: t2 s2 then splitCoercionKindOf c = ((t1, t2), (s1, s2))
383 splitCoercionKindOf co
384   | Just (ty1, ty2) <- splitCoercionKind_maybe (coercionKindPredTy co)
385   , Just (ty_fun1, ty_arg1) <- splitAppTy_maybe ty1
386   , Just (ty_fun2, ty_arg2) <- splitAppTy_maybe ty2
387   = ((ty_fun1, ty_fun2),(ty_arg1, ty_arg2))
388
389 instCoercionTyCon 
390   =  mkCoercionTyCon instCoercionTyConName 2 (mkKindingFun instCoercionKind)
391   where
392     instantiateCo t s =
393       let Just (tv, ty) = splitForAllTy_maybe t in
394       substTyWith [tv] [s] ty
395
396     instCoercionKind (co1:ty:rest) = (instantiateCo t1 ty, instantiateCo t2 ty, rest)
397       where (t1, t2) = coercionKind co1
398
399 unsafeCoercionTyCon 
400   = mkCoercionTyCon unsafeCoercionTyConName 2 (mkKindingFun unsafeCoercionKind)
401   where
402    unsafeCoercionKind (ty1:ty2:rest) = (ty1,ty2,rest) 
403         
404 --------------------------------------
405 -- ...and their names
406
407 mkCoConName occ key coCon = mkWiredInName gHC_PRIM (mkOccNameFS tcName occ)
408                             key Nothing (ATyCon coCon) BuiltInSyntax
409
410 transCoercionTyConName = mkCoConName FSLIT("trans") transCoercionTyConKey transCoercionTyCon
411 symCoercionTyConName   = mkCoConName FSLIT("sym") symCoercionTyConKey symCoercionTyCon
412 leftCoercionTyConName  = mkCoConName FSLIT("left") leftCoercionTyConKey leftCoercionTyCon
413 rightCoercionTyConName = mkCoConName FSLIT("right") rightCoercionTyConKey rightCoercionTyCon
414 instCoercionTyConName  = mkCoConName FSLIT("inst") instCoercionTyConKey instCoercionTyCon
415 unsafeCoercionTyConName = mkCoConName FSLIT("CoUnsafe") unsafeCoercionTyConKey unsafeCoercionTyCon
416
417
418
419 -- this is here to avoid module loops
420 splitNewTypeRepCo_maybe :: Type -> Maybe (Type, Coercion)  
421 -- Sometimes we want to look through a newtype and get its associated coercion
422 -- It only strips *one layer* off, so the caller will usually call itself recursively
423 -- Only applied to types of kind *, hence the newtype is always saturated
424 splitNewTypeRepCo_maybe ty 
425   | Just ty' <- coreView ty = splitNewTypeRepCo_maybe ty'
426 splitNewTypeRepCo_maybe (TyConApp tc tys)
427   | isClosedNewTyCon tc 
428   = ASSERT( tys `lengthIs` tyConArity tc )      -- splitNewTypeRepCo_maybe only be applied 
429                                                 --      to *types* (of kind *)
430         case newTyConRhs tc of
431           (tvs, rep_ty) -> 
432               ASSERT( length tvs == length tys )
433               Just (substTyWith tvs tys rep_ty, mkTyConApp co_con tys)
434   where
435     co_con = maybe (pprPanic "splitNewTypeRepCo_maybe" (ppr tc)) id (newTyConCo_maybe tc)
436 splitNewTypeRepCo_maybe other = Nothing
437 \end{code}