2 % (c) The University of Glasgow 2011
7 module Generics ( canDoGenerics,
8 mkBindsRep0, tc_mkRep0TyCon, mkBindsMetaD,
9 MetaTyCons(..), metaTyCons2TyCons
19 import Name hiding (varName)
20 import Module (moduleName, moduleNameString)
25 -- For generation of representation types
26 import TcEnv (tcLookupTyCon)
27 import TcRnMonad (TcM, newUnique)
35 #include "HsVersions.h"
38 %************************************************************************
40 \subsection{Generating representation types}
42 %************************************************************************
45 canDoGenerics :: ThetaType -> [DataCon] -> Bool
46 -- Called on source-code data types, to see if we should generate
47 -- generic functions for them. (This info is recorded in the interface file for
48 -- imported data types.)
50 canDoGenerics stupid_theta data_cs
51 = not (any bad_con data_cs) -- See comment below
53 -- && not (null data_cs) -- No values of the type
54 -- JPM: we now support empty datatypes
56 && null stupid_theta -- We do not support datatypes with context (for now)
58 bad_con dc = any bad_arg_type (dataConOrigArgTys dc) || not (isVanillaDataCon dc)
59 -- If any of the constructor has an unboxed type as argument,
60 -- then we can't build the embedding-projection pair, because
61 -- it relies on instantiating *polymorphic* sum and product types
62 -- at the argument types of the constructors
64 -- Nor can we do the job if it's an existential data constructor,
66 -- Nor if the args are polymorphic types (I don't think)
67 bad_arg_type ty = isUnLiftedType ty || not (isTauTy ty)
68 -- JPM: TODO: I'm not sure I know what isTauTy checks for, so I'm leaving it
69 -- like this for now...
72 %************************************************************************
74 \subsection{Generating the RHS of a generic default method}
76 %************************************************************************
79 type US = Int -- Local unique supply, just a plain Int
80 type Alt = (LPat RdrName, LHsExpr RdrName)
82 -- Bindings for the Representable0 instance
83 mkBindsRep0 :: TyCon -> LHsBinds RdrName
85 unitBag (L loc (mkFunBind (L loc from0_RDR) from0_matches))
87 unitBag (L loc (mkFunBind (L loc to0_RDR) to0_matches))
89 from0_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- from0_alts]
90 to0_matches = [mkSimpleHsAlt pat rhs | (pat,rhs) <- to0_alts ]
91 loc = srcLocSpan (getSrcLoc tycon)
92 datacons = tyConDataCons tycon
94 -- Recurse over the sum first
95 from0_alts, to0_alts :: [Alt]
96 (from0_alts, to0_alts) = mkSum (1 :: US) tycon datacons
98 --------------------------------------------------------------------------------
99 -- Type representation
100 --------------------------------------------------------------------------------
102 tc_mkRep0Ty :: -- The type to generate representation for
104 -- Metadata datatypes to refer to
106 -- Generated representation0 type
108 tc_mkRep0Ty tycon metaDts =
110 d1 <- tcLookupTyCon d1TyConName
111 c1 <- tcLookupTyCon c1TyConName
112 s1 <- tcLookupTyCon s1TyConName
113 rec0 <- tcLookupTyCon rec0TyConName
114 par0 <- tcLookupTyCon par0TyConName
115 u1 <- tcLookupTyCon u1TyConName
116 v1 <- tcLookupTyCon v1TyConName
117 plus <- tcLookupTyCon sumTyConName
118 times <- tcLookupTyCon prodTyConName
120 let mkSum' a b = mkTyConApp plus [a,b]
121 mkProd a b = mkTyConApp times [a,b]
122 mkRec0 a = mkTyConApp rec0 [a]
123 mkPar0 a = mkTyConApp par0 [a]
124 mkD a = mkTyConApp d1 [metaDTyCon, sumP (tyConDataCons a)]
125 mkC i d a = mkTyConApp c1 [d, prod i (dataConOrigArgTys a)]
126 mkS d a = mkTyConApp s1 [d, a]
128 sumP [] = mkTyConTy v1
129 sumP l = ASSERT (length metaCTyCons == length l)
130 foldBal mkSum' [ mkC i d a
131 | (d,(a,i)) <- zip metaCTyCons (zip l [0..])]
132 prod :: Int -> [Type] -> Type
133 prod i [] = ASSERT (length metaSTyCons > i)
134 ASSERT (length (metaSTyCons !! i) == 0)
136 prod i l = ASSERT (length metaSTyCons > i)
137 ASSERT (length l == length (metaSTyCons !! i))
138 foldBal mkProd [ arg d a
139 | (d,a) <- zip (metaSTyCons !! i) l ]
141 arg d t = trace (showPpr t) $ mkS d (recOrPar t (getTyVar_maybe t))
142 -- Argument is not a type variable, use Rec0
143 recOrPar t Nothing = trace "Rec0" $ mkRec0 t
144 -- Argument is a type variable, use Par0
145 recOrPar t (Just _) = trace "Par0" $ mkPar0 t
147 metaDTyCon = mkTyConTy (metaD metaDts)
148 metaCTyCons = map mkTyConTy (metaC metaDts)
149 metaSTyCons = map (map mkTyConTy) (metaS metaDts)
153 tc_mkRep0TyCon :: TyCon -- The type to generate representation for
154 -> MetaTyCons -- Metadata datatypes to refer to
155 -> TcM TyCon -- Generated representation0 type
156 tc_mkRep0TyCon tycon metaDts =
157 -- Consider the example input tycon `D`, where data D a b = D_ a
161 -- `rep0Ty` = D1 ... (C1 ... (S1 ... (Rec0 a))) :: * -> *
162 rep0Ty <- tc_mkRep0Ty tycon metaDts
163 -- `rep0` = GHC.Generics.Rep0 (type family)
164 rep0 <- tcLookupTyCon rep0TyConName
166 let modl = nameModule (tyConName tycon)
167 loc = nameSrcSpan (tyConName tycon)
168 -- `repName` is a name we generate for the synonym
169 repName = mkExternalName uniq1 modl (mkGenR0 (nameOccName (tyConName tycon))) loc
170 -- `coName` is a name for the coercion
171 coName = mkExternalName uniq2 modl (mkGenR0 (nameOccName (tyConName tycon))) loc
173 tyvars = tyConTyVars tycon
175 appT = [mkTyConApp tycon (mkTyVarTys tyvars)]
177 res = mkSynTyCon repName
178 -- rep0Ty has kind `kind of D` -> *
179 (tyConKind tycon `mkArrowKind` liftedTypeKind)
180 tyvars (SynonymTyCon rep0Ty)
181 (FamInstTyCon rep0 appT
182 (mkCoercionTyCon coName (tyConArity tycon)
183 -- co : forall a b. Rep0 (D a b) ~ `rep0Ty` a b
184 (CoAxiom tyvars (mkTyConApp rep0 appT) rep0Ty)))
188 --------------------------------------------------------------------------------
190 --------------------------------------------------------------------------------
192 data MetaTyCons = MetaTyCons { -- One meta datatype per dataype
194 -- One meta datatype per constructor
196 -- One meta datatype per selector per constructor
197 , metaS :: [[TyCon]] }
199 instance Outputable MetaTyCons where
200 ppr (MetaTyCons d c s) = ppr d <+> ppr c <+> ppr s
202 metaTyCons2TyCons :: MetaTyCons -> [TyCon]
203 metaTyCons2TyCons (MetaTyCons d c s) = d : c ++ concat s
206 -- Bindings for Datatype, Constructor, and Selector instances
207 mkBindsMetaD :: FixityEnv -> TyCon
208 -> ( LHsBinds RdrName -- Datatype instance
209 , [LHsBinds RdrName] -- Constructor instances
210 , [[LHsBinds RdrName]]) -- Selector instances
211 mkBindsMetaD fix_env tycon = (dtBinds, allConBinds, allSelBinds)
213 mkBag l = foldr1 unionBags
214 [ unitBag (L loc (mkFunBind (L loc name) matches))
215 | (name, matches) <- l ]
216 dtBinds = mkBag [ (datatypeName_RDR, dtName_matches)
217 , (moduleName_RDR, moduleName_matches)]
219 allConBinds = map conBinds datacons
220 conBinds c = mkBag ( [ (conName_RDR, conName_matches c)]
221 ++ ifElseEmpty (dataConIsInfix c)
222 [ (conFixity_RDR, conFixity_matches c) ]
223 ++ ifElseEmpty (length (dataConFieldLabels c) > 0)
224 [ (conIsRecord_RDR, conIsRecord_matches c) ]
227 ifElseEmpty p x = if p then x else []
228 fixity c = case lookupFixity fix_env (dataConName c) of
229 Fixity n InfixL -> buildFix n leftAssocDataCon_RDR
230 Fixity n InfixR -> buildFix n rightAssocDataCon_RDR
231 Fixity n InfixN -> buildFix n notAssocDataCon_RDR
232 buildFix n assoc = nlHsApps infixDataCon_RDR [nlHsVar assoc
233 , nlHsIntLit (toInteger n)]
235 allSelBinds = map (map selBinds) datasels
236 selBinds s = mkBag [(selName_RDR, selName_matches s)]
238 loc = srcLocSpan (getSrcLoc tycon)
239 mkStringLHS s = [mkSimpleHsAlt nlWildPat (nlHsLit (mkHsString s))]
240 datacons = tyConDataCons tycon
241 datasels = map dataConFieldLabels datacons
243 dtName_matches = mkStringLHS . showPpr . nameOccName . tyConName
245 moduleName_matches = mkStringLHS . moduleNameString . moduleName
246 . nameModule . tyConName $ tycon
248 conName_matches c = mkStringLHS . showPpr . nameOccName
250 conFixity_matches c = [mkSimpleHsAlt nlWildPat (fixity c)]
251 conIsRecord_matches _ = [mkSimpleHsAlt nlWildPat (nlHsVar true_RDR)]
253 selName_matches s = mkStringLHS (showPpr (nameOccName s))
256 --------------------------------------------------------------------------------
258 --------------------------------------------------------------------------------
260 mkSum :: US -- Base for generating unique names
261 -> TyCon -- The type constructor
262 -> [DataCon] -- The data constructors
263 -> ([Alt], -- Alternatives for the T->Trep "from" function
264 [Alt]) -- Alternatives for the Trep->T "to" function
266 -- Datatype without any constructors
267 mkSum _us tycon [] = ([from_alt], [to_alt])
269 from_alt = (nlWildPat, mkM1_E (makeError errMsgFrom))
270 to_alt = (mkM1_P nlWildPat, makeError errMsgTo)
271 -- These M1s are meta-information for the datatype
272 makeError s = nlHsApp (nlHsVar error_RDR) (nlHsLit (mkHsString s))
273 errMsgFrom = "No generic representation for empty datatype " ++ showPpr tycon
274 errMsgTo = "No values for empty datatype " ++ showPpr tycon
276 -- Datatype with at least one constructor
277 mkSum us _tycon datacons =
278 unzip [ mk1Sum us i (length datacons) d | (d,i) <- zip datacons [1..] ]
280 -- Build the sum for a particular constructor
281 mk1Sum :: US -- Base for generating unique names
282 -> Int -- The index of this constructor
283 -> Int -- Total number of constructors
284 -> DataCon -- The data constructor
285 -> (Alt, -- Alternative for the T->Trep "from" function
286 Alt) -- Alternative for the Trep->T "to" function
287 mk1Sum us i n datacon = (from_alt, to_alt)
289 n_args = dataConSourceArity datacon -- Existentials already excluded
291 datacon_vars = map mkGenericLocal [us .. us+n_args-1]
294 datacon_rdr = getRdrName datacon
295 app_exp = nlHsVarApps datacon_rdr datacon_vars
297 from_alt = (nlConVarPat datacon_rdr datacon_vars, from_alt_rhs)
298 from_alt_rhs = mkM1_E (genLR_E i n (mkProd_E us' datacon_vars))
300 to_alt = (mkM1_P (genLR_P i n (mkProd_P us' datacon_vars)), to_alt_rhs)
301 -- These M1s are meta-information for the datatype
304 -- Generates the L1/R1 sum pattern
305 genLR_P :: Int -> Int -> LPat RdrName -> LPat RdrName
307 | n == 0 = error "impossible"
309 | i <= div n 2 = nlConPat l1DataCon_RDR [genLR_P i (div n 2) p]
310 | otherwise = nlConPat r1DataCon_RDR [genLR_P (i-m) (n-m) p]
313 -- Generates the L1/R1 sum expression
314 genLR_E :: Int -> Int -> LHsExpr RdrName -> LHsExpr RdrName
316 | n == 0 = error "impossible"
318 | i <= div n 2 = nlHsVar l1DataCon_RDR `nlHsApp` genLR_E i (div n 2) e
319 | otherwise = nlHsVar r1DataCon_RDR `nlHsApp` genLR_E (i-m) (n-m) e
322 --------------------------------------------------------------------------------
323 -- Dealing with products
324 --------------------------------------------------------------------------------
326 -- Build a product expression
327 mkProd_E :: US -- Base for unique names
328 -> [RdrName] -- List of variables matched on the lhs
329 -> LHsExpr RdrName -- Resulting product expression
330 mkProd_E _ [] = mkM1_E (nlHsVar u1DataCon_RDR)
331 mkProd_E _ vars = mkM1_E (foldBal prod appVars)
332 -- These M1s are meta-information for the constructor
334 appVars = map wrapArg_E vars
335 prod a b = prodDataCon_RDR `nlHsApps` [a,b]
337 -- TODO: Produce a P0 when v is a parameter
338 wrapArg_E :: RdrName -> LHsExpr RdrName
339 wrapArg_E v = mkM1_E (k1DataCon_RDR `nlHsVarApps` [v])
340 -- This M1 is meta-information for the selector
342 -- Build a product pattern
343 mkProd_P :: US -- Base for unique names
344 -> [RdrName] -- List of variables to match
345 -> LPat RdrName -- Resulting product pattern
346 mkProd_P _ [] = mkM1_P (nlNullaryConPat u1DataCon_RDR)
347 mkProd_P _ vars = mkM1_P (foldBal prod appVars)
348 -- These M1s are meta-information for the constructor
350 appVars = map wrapArg_P vars
351 prod a b = prodDataCon_RDR `nlConPat` [a,b]
353 -- TODO: Produce a P0 when v is a parameter
354 wrapArg_P :: RdrName -> LPat RdrName
355 wrapArg_P v = mkM1_P (k1DataCon_RDR `nlConVarPat` [v])
356 -- This M1 is meta-information for the selector
358 mkGenericLocal :: US -> RdrName
359 mkGenericLocal u = mkVarUnqual (mkFastString ("g" ++ show u))
361 mkM1_E :: LHsExpr RdrName -> LHsExpr RdrName
362 mkM1_E e = nlHsVar m1DataCon_RDR `nlHsApp` e
364 mkM1_P :: LPat RdrName -> LPat RdrName
365 mkM1_P p = m1DataCon_RDR `nlConPat` [p]
367 -- | Variant of foldr1 for producing balanced lists
368 foldBal :: (a -> a -> a) -> [a] -> a
369 foldBal op = foldBal' op (error "foldBal: empty list")
371 foldBal' :: (a -> a -> a) -> a -> [a] -> a
374 foldBal' op x l = let (a,b) = splitAt (length l `div` 2) l
375 in foldBal' op x a `op` foldBal' op x b