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