5 import qualified Data.Either as Either
6 import qualified Data.List as List
7 import qualified Data.Map as Map
8 import qualified Control.Monad as Monad
9 import qualified Control.Arrow as Arrow
10 import qualified Data.Monoid as Monoid
15 import qualified ForSyDe.Backend.VHDL.AST as AST
20 import qualified OccName
23 import qualified TyCon
25 import qualified DataCon
26 import qualified CoreSubst
34 -----------------------------------------------------------------------------
35 -- Functions to generate concurrent statements
36 -----------------------------------------------------------------------------
38 -- Create an unconditional assignment statement
40 Either CoreBndr AST.VHDLName -- ^ The signal to assign to
41 -> AST.Expr -- ^ The expression to assign
42 -> AST.ConcSm -- ^ The resulting concurrent statement
43 mkUncondAssign dst expr = mkAssign dst Nothing expr
45 -- Create a conditional assignment statement
47 Either CoreBndr AST.VHDLName -- ^ The signal to assign to
48 -> AST.Expr -- ^ The condition
49 -> AST.Expr -- ^ The value when true
50 -> AST.Expr -- ^ The value when false
51 -> AST.ConcSm -- ^ The resulting concurrent statement
52 mkCondAssign dst cond true false = mkAssign dst (Just (cond, true)) false
54 -- Create a conditional or unconditional assignment statement
56 Either CoreBndr AST.VHDLName -> -- ^ The signal to assign to
57 Maybe (AST.Expr , AST.Expr) -> -- ^ Optionally, the condition to test for
58 -- and the value to assign when true.
59 AST.Expr -> -- ^ The value to assign when false or no condition
60 AST.ConcSm -- ^ The resulting concurrent statement
61 mkAssign dst cond false_expr =
63 -- I'm not 100% how this assignment AST works, but this gets us what we
65 whenelse = case cond of
66 Just (cond_expr, true_expr) ->
68 true_wform = AST.Wform [AST.WformElem true_expr Nothing]
70 [AST.WhenElse true_wform cond_expr]
72 false_wform = AST.Wform [AST.WformElem false_expr Nothing]
73 dst_name = case dst of
74 Left bndr -> AST.NSimple (varToVHDLId bndr)
76 assign = dst_name AST.:<==: (AST.ConWforms whenelse false_wform Nothing)
81 [AST.Expr] -- | The argument that are applied to function
82 -> AST.VHDLName -- | The binder in which to store the result
83 -> Entity -- | The entity to map against.
84 -> [AST.AssocElem] -- | The resulting port maps
85 mkAssocElems args res entity =
86 -- Create the actual AssocElems
87 zipWith mkAssocElem ports sigs
89 -- Turn the ports and signals from a map into a flat list. This works,
90 -- since the maps must have an identical form by definition. TODO: Check
92 arg_ports = ent_args entity
93 res_port = ent_res entity
94 -- Extract the id part from the (id, type) tuple
95 ports = map fst (res_port : arg_ports)
96 -- Translate signal numbers into names
97 sigs = (vhdlNameToVHDLExpr res : args)
99 -- | Create an VHDL port -> signal association
100 mkAssocElem :: AST.VHDLId -> AST.Expr -> AST.AssocElem
101 mkAssocElem port signal = Just port AST.:=>: (AST.ADExpr signal)
103 -- | Create an VHDL port -> signal association
104 mkAssocElemIndexed :: AST.VHDLId -> AST.VHDLId -> AST.VHDLId -> AST.AssocElem
105 mkAssocElemIndexed port signal index = Just port AST.:=>: (AST.ADName (AST.NIndexed (AST.IndexedName
106 (AST.NSimple signal) [AST.PrimName $ AST.NSimple index])))
109 String -- ^ The portmap label
110 -> AST.VHDLId -- ^ The entity name
111 -> [AST.AssocElem] -- ^ The port assignments
113 mkComponentInst label entity_id portassigns = AST.CSISm compins
115 -- We always have a clock port, so no need to map it anywhere but here
116 clk_port = mkAssocElem (mkVHDLExtId "clk") (idToVHDLExpr $ mkVHDLExtId "clk")
117 compins = AST.CompInsSm (mkVHDLExtId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect (portassigns ++ [clk_port]))
119 -----------------------------------------------------------------------------
120 -- Functions to generate VHDL Exprs
121 -----------------------------------------------------------------------------
123 -- Turn a variable reference into a AST expression
124 varToVHDLExpr :: Var.Var -> AST.Expr
126 case Id.isDataConWorkId_maybe var of
127 Just dc -> dataconToVHDLExpr dc
128 -- This is a dataconstructor.
129 -- Not a datacon, just another signal. Perhaps we should check for
130 -- local/global here as well?
131 -- Sadly so.. tfp decimals are types, not data constructors, but instances
132 -- should still be translated to integer literals. It is probebly not the
133 -- best solution to translate them here.
134 -- FIXME: Find a better solution for translating instances of tfp integers
138 res = case Type.splitTyConApp_maybe ty of
139 Just (tycon, args) ->
140 case Name.getOccString (TyCon.tyConName tycon) of
141 "Dec" -> AST.PrimLit $ (show (eval_tfp_int ty))
142 otherwise -> AST.PrimName $ AST.NSimple $ varToVHDLId var
146 -- Turn a VHDLName into an AST expression
147 vhdlNameToVHDLExpr = AST.PrimName
149 -- Turn a VHDL Id into an AST expression
150 idToVHDLExpr = vhdlNameToVHDLExpr . AST.NSimple
152 -- Turn a Core expression into an AST expression
153 exprToVHDLExpr = varToVHDLExpr . exprToVar
155 -- Turn a alternative constructor into an AST expression. For
156 -- dataconstructors, this is only the constructor itself, not any arguments it
157 -- has. Should not be called with a DEFAULT constructor.
158 altconToVHDLExpr :: CoreSyn.AltCon -> AST.Expr
159 altconToVHDLExpr (DataAlt dc) = dataconToVHDLExpr dc
161 altconToVHDLExpr (LitAlt _) = error "\nVHDL.conToVHDLExpr: Literals not support in case alternatives yet"
162 altconToVHDLExpr DEFAULT = error "\nVHDL.conToVHDLExpr: DEFAULT alternative should not occur here!"
164 -- Turn a datacon (without arguments!) into a VHDL expression.
165 dataconToVHDLExpr :: DataCon.DataCon -> AST.Expr
166 dataconToVHDLExpr dc = AST.PrimLit lit
168 tycon = DataCon.dataConTyCon dc
169 tyname = TyCon.tyConName tycon
170 dcname = DataCon.dataConName dc
171 lit = case Name.getOccString tyname of
172 -- TODO: Do something more robust than string matching
173 "Bit" -> case Name.getOccString dcname of "High" -> "'1'"; "Low" -> "'0'"
174 "Bool" -> case Name.getOccString dcname of "True" -> "true"; "False" -> "false"
176 -----------------------------------------------------------------------------
177 -- Functions dealing with names, variables and ids
178 -----------------------------------------------------------------------------
180 -- Creates a VHDL Id from a binder
184 varToVHDLId = mkVHDLExtId . varToString
186 -- Creates a VHDL Name from a binder
190 varToVHDLName = AST.NSimple . varToVHDLId
192 -- Extracts the binder name as a String
196 varToString = OccName.occNameString . Name.nameOccName . Var.varName
198 -- Get the string version a Var's unique
199 varToStringUniq :: Var.Var -> String
200 varToStringUniq = show . Var.varUnique
202 -- Extracts the string version of the name
203 nameToString :: Name.Name -> String
204 nameToString = OccName.occNameString . Name.nameOccName
206 -- Shortcut for Basic VHDL Ids.
207 -- Can only contain alphanumerics and underscores. The supplied string must be
208 -- a valid basic id, otherwise an error value is returned. This function is
209 -- not meant to be passed identifiers from a source file, use mkVHDLExtId for
211 mkVHDLBasicId :: String -> AST.VHDLId
213 AST.unsafeVHDLBasicId $ (strip_multiscore . strip_leading . strip_invalid) s
215 -- Strip invalid characters.
216 strip_invalid = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.")
217 -- Strip leading numbers and underscores
218 strip_leading = dropWhile (`elem` ['0'..'9'] ++ "_")
219 -- Strip multiple adjacent underscores
220 strip_multiscore = concat . map (\cs ->
226 -- Shortcut for Extended VHDL Id's. These Id's can contain a lot more
227 -- different characters than basic ids, but can never be used to refer to
229 -- Use extended Ids for any values that are taken from the source file.
230 mkVHDLExtId :: String -> AST.VHDLId
232 AST.unsafeVHDLExtId $ strip_invalid s
234 -- Allowed characters, taken from ForSyde's mkVHDLExtId
235 allowed = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ " \"#&\\'()*+,./:;<=>_|!$%@?[]^`{}~-"
236 strip_invalid = filter (`elem` allowed)
238 -- Create a record field selector that selects the given label from the record
239 -- stored in the given binder.
240 mkSelectedName :: AST.VHDLName -> AST.VHDLId -> AST.VHDLName
241 mkSelectedName name label =
242 AST.NSelected $ name AST.:.: (AST.SSimple label)
244 -- Create an indexed name that selects a given element from a vector.
245 mkIndexedName :: AST.VHDLName -> AST.Expr -> AST.VHDLName
246 -- Special case for already indexed names. Just add an index
247 mkIndexedName (AST.NIndexed (AST.IndexedName name indexes)) index =
248 AST.NIndexed (AST.IndexedName name (indexes++[index]))
249 -- General case for other names
250 mkIndexedName name index = AST.NIndexed (AST.IndexedName name [index])
252 -----------------------------------------------------------------------------
253 -- Functions dealing with VHDL types
254 -----------------------------------------------------------------------------
256 -- | Maps the string name (OccName) of a type to the corresponding VHDL type,
257 -- for a few builtin types.
260 ("Bit", std_logicTM),
261 ("Bool", booleanTM), -- TysWiredIn.boolTy
265 -- Translate a Haskell type to a VHDL type, generating a new type if needed.
266 -- Returns an error value, using the given message, when no type could be
268 vhdl_ty :: String -> Type.Type -> TypeSession AST.TypeMark
270 tm_either <- vhdl_ty_either ty
272 Right tm -> return tm
273 Left err -> error $ msg ++ "\n" ++ err
275 -- Translate a Haskell type to a VHDL type, generating a new type if needed.
276 -- Returns either an error message or the resulting type.
277 vhdl_ty_either :: Type.Type -> TypeSession (Either String AST.TypeMark)
278 vhdl_ty_either ty = do
279 typemap <- getA vsTypes
280 htype_either <- mkHType ty
284 let builtin_ty = do -- See if this is a tycon and lookup its name
285 (tycon, args) <- Type.splitTyConApp_maybe ty
286 let name = Name.getOccString (TyCon.tyConName tycon)
287 Map.lookup name builtin_types
288 -- If not a builtin type, try the custom types
289 let existing_ty = (fmap fst) $ Map.lookup htype typemap
290 case Monoid.getFirst $ Monoid.mconcat (map Monoid.First [builtin_ty, existing_ty]) of
291 -- Found a type, return it
292 Just t -> return (Right t)
293 -- No type yet, try to construct it
295 newty_maybe <- (construct_vhdl_ty ty)
297 Right (ty_id, ty_def) -> do
298 -- TODO: Check name uniqueness
299 modA vsTypes (Map.insert htype (ty_id, ty_def))
300 modA vsTypeDecls (\typedefs -> typedefs ++ [mktydecl (ty_id, ty_def)])
302 Left err -> return $ Left $
303 "VHDLTools.vhdl_ty: Unsupported Haskell type: " ++ pprString ty ++ "\n"
305 -- Error when constructing htype
306 Left err -> return $ Left err
308 -- Construct a new VHDL type for the given Haskell type. Returns an error
309 -- message or the resulting typemark and typedef.
310 construct_vhdl_ty :: Type.Type -> TypeSession (Either String (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
311 construct_vhdl_ty ty = do
312 case Type.splitTyConApp_maybe ty of
313 Just (tycon, args) -> do
314 let name = Name.getOccString (TyCon.tyConName tycon)
316 "TFVec" -> mk_vector_ty ty
317 "SizedWord" -> mk_unsigned_ty ty
318 "RangedWord" -> mk_natural_ty 0 (ranged_word_bound ty)
319 -- Create a custom type from this tycon
320 otherwise -> mk_tycon_ty tycon args
321 Nothing -> return (Left $ "VHDLTools.construct_vhdl_ty: Cannot create type for non-tycon type: " ++ pprString ty ++ "\n")
323 -- | Create VHDL type for a custom tycon
324 mk_tycon_ty :: TyCon.TyCon -> [Type.Type] -> TypeSession (Either String (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
325 mk_tycon_ty tycon args =
326 case TyCon.tyConDataCons tycon of
327 -- Not an algebraic type
328 [] -> return (Left $ "VHDLTools.mk_tycon_ty: Only custom algebraic types are supported: " ++ pprString tycon ++ "\n")
330 let arg_tys = DataCon.dataConRepArgTys dc
331 -- TODO: CoreSubst docs say each Subs can be applied only once. Is this a
332 -- violation? Or does it only mean not to apply it again to the same
334 let real_arg_tys = map (CoreSubst.substTy subst) arg_tys
335 elem_tys_either <- mapM vhdl_ty_either real_arg_tys
336 case Either.partitionEithers elem_tys_either of
337 -- No errors in element types
339 let elems = zipWith AST.ElementDec recordlabels elem_tys
340 -- For a single construct datatype, build a record with one field for
342 -- TODO: Add argument type ids to this, to ensure uniqueness
343 -- TODO: Special handling for tuples?
344 let elem_names = concat $ map prettyShow elem_tys
345 let ty_id = mkVHDLExtId $ nameToString (TyCon.tyConName tycon) ++ elem_names
346 let ty_def = AST.TDR $ AST.RecordTypeDef elems
347 return $ Right (ty_id, Left ty_def)
348 -- There were errors in element types
349 (errors, _) -> return $ Left $
350 "VHDLTools.mk_tycon_ty: Can not construct type for: " ++ pprString tycon ++ "\n because no type can be construced for some of the arguments.\n"
352 dcs -> return $ Left $ "VHDLTools.mk_tycon_ty: Only single constructor datatypes supported: " ++ pprString tycon ++ "\n"
354 -- Create a subst that instantiates all types passed to the tycon
355 -- TODO: I'm not 100% sure that this is the right way to do this. It seems
356 -- to work so far, though..
357 tyvars = TyCon.tyConTyVars tycon
358 subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
359 -- Generate a bunch of labels for fields of a record
360 recordlabels = map (\c -> mkVHDLBasicId [c]) ['A'..'Z']
362 -- | Create a VHDL vector type
364 Type.Type -- ^ The Haskell type of the Vector
365 -> TypeSession (Either String (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
366 -- ^ An error message or The typemark created.
369 types_map <- getA vsTypes
370 let (nvec_l, nvec_el) = Type.splitAppTy ty
371 let (nvec, leng) = Type.splitAppTy nvec_l
372 let vec_ty = Type.mkAppTy nvec nvec_el
373 let len = tfvec_len ty
374 let el_ty = tfvec_elem ty
375 el_ty_tm_either <- vhdl_ty_either el_ty
376 case el_ty_tm_either of
377 -- Could create element type
379 let ty_id = mkVHDLExtId $ "vector-"++ (AST.fromVHDLId el_ty_tm) ++ "-0_to_" ++ (show len)
380 let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len - 1))]
381 let existing_elem_ty = (fmap fst) $ Map.lookup (StdType $ OrdType vec_ty) types_map
382 case existing_elem_ty of
384 let ty_def = AST.SubtypeIn t (Just range)
385 return (Right (ty_id, Right ty_def))
387 let vec_id = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId el_ty_tm)
388 let vec_def = AST.TDA $ AST.UnconsArrayDef [tfvec_indexTM] el_ty_tm
389 modA vsTypes (Map.insert (StdType $ OrdType vec_ty) (vec_id, (Left vec_def)))
390 modA vsTypeDecls (\typedefs -> typedefs ++ [mktydecl (vec_id, (Left vec_def))])
391 let ty_def = AST.SubtypeIn vec_id (Just range)
392 return (Right (ty_id, Right ty_def))
393 -- Could not create element type
394 Left err -> return $ Left $
395 "VHDLTools.mk_vector_ty: Can not construct vectortype for elementtype: " ++ pprString el_ty ++ "\n"
399 Int -- ^ The minimum bound (> 0)
400 -> Int -- ^ The maximum bound (> minimum bound)
401 -> TypeSession (Either String (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
402 -- ^ An error message or The typemark created.
403 mk_natural_ty min_bound max_bound = do
404 let ty_id = mkVHDLExtId $ "nat_" ++ (show min_bound) ++ "_to_" ++ (show max_bound)
405 let range = AST.ConstraintRange $ AST.SubTypeRange (AST.PrimLit $ (show min_bound)) (AST.PrimLit $ (show max_bound))
406 let ty_def = AST.SubtypeIn naturalTM (Just range)
407 return (Right (ty_id, Right ty_def))
410 Type.Type -- ^ Haskell type of the signed integer
411 -> TypeSession (Either String (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
412 mk_unsigned_ty ty = do
413 let size = sized_word_len ty
414 let ty_id = mkVHDLExtId $ "unsigned_" ++ show (size - 1)
415 let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (size - 1))]
416 let ty_def = AST.SubtypeIn signedTM (Just range)
417 return (Right (ty_id, Right ty_def))
419 -- Finds the field labels for VHDL type generated for the given Core type,
420 -- which must result in a record type.
421 getFieldLabels :: Type.Type -> TypeSession [AST.VHDLId]
422 getFieldLabels ty = do
423 -- Ensure that the type is generated (but throw away it's VHDLId)
424 let error_msg = "\nVHDLTools.getFieldLabels: Can not get field labels, because: " ++ pprString ty ++ "can not be generated."
426 -- Get the types map, lookup and unpack the VHDL TypeDef
427 types <- getA vsTypes
428 -- Assume the type for which we want labels is really translatable
429 Right htype <- mkHType ty
430 case Map.lookup htype types of
431 Just (_, Left (AST.TDR (AST.RecordTypeDef elems))) -> return $ map (\(AST.ElementDec id _) -> id) elems
432 _ -> error $ "\nVHDL.getFieldLabels: Type not found or not a record type? This should not happen! Type: " ++ (show ty)
434 mktydecl :: (AST.VHDLId, Either AST.TypeDef AST.SubtypeIn) -> AST.PackageDecItem
435 mktydecl (ty_id, Left ty_def) = AST.PDITD $ AST.TypeDec ty_id ty_def
436 mktydecl (ty_id, Right ty_def) = AST.PDISD $ AST.SubtypeDec ty_id ty_def
438 mkHType :: Type.Type -> TypeSession (Either String HType)
440 -- FIXME: Do we really need to do this here again?
441 let builtin_ty = do -- See if this is a tycon and lookup its name
442 (tycon, args) <- Type.splitTyConApp_maybe ty
443 let name = Name.getOccString (TyCon.tyConName tycon)
444 Map.lookup name builtin_types
447 return $ Right $ BuiltinType $ prettyShow typ
449 case Type.splitTyConApp_maybe ty of
450 Just (tycon, args) -> do
451 let name = Name.getOccString (TyCon.tyConName tycon)
454 let el_ty = tfvec_elem ty
455 elem_htype_either <- mkHType el_ty
456 case elem_htype_either of
457 -- Could create element type
458 Right elem_htype -> do
460 return $ Right $ VecType len elem_htype
461 -- Could not create element type
462 Left err -> return $ Left $
463 "VHDLTools.mkHType: Can not construct vectortype for elementtype: " ++ pprString el_ty ++ "\n"
465 "SizedWord" -> return $ Right $ StdType $ OrdType ty
466 "RangedWord" -> return $ Right $ StdType $ OrdType ty
468 mkTyConHType tycon args
469 Nothing -> return $ Right $ StdType $ OrdType ty
471 -- FIXME: Do we really need to do this here again?
472 mkTyConHType :: TyCon.TyCon -> [Type.Type] -> TypeSession (Either String HType)
473 mkTyConHType tycon args =
474 case TyCon.tyConDataCons tycon of
475 -- Not an algebraic type
476 [] -> return $ Left $ "VHDLTools.mkHType: Only custom algebraic types are supported: " ++ pprString tycon ++ "\n"
478 let arg_tys = DataCon.dataConRepArgTys dc
479 let real_arg_tys = map (CoreSubst.substTy subst) arg_tys
480 elem_htys_either <- mapM mkHType real_arg_tys
481 case Either.partitionEithers elem_htys_either of
482 -- No errors in element types
483 ([], elem_htys) -> do
484 return $ Right $ ADTType (nameToString (TyCon.tyConName tycon)) elem_htys
485 -- There were errors in element types
486 (errors, _) -> return $ Left $
487 "VHDLTools.mkHType: Can not construct type for: " ++ pprString tycon ++ "\n because no type can be construced for some of the arguments.\n"
489 dcs -> return $ Left $ "VHDLTools.mkHType: Only single constructor datatypes supported: " ++ pprString tycon ++ "\n"
491 tyvars = TyCon.tyConTyVars tycon
492 subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
494 -- Is the given type representable at runtime?
495 isReprType :: Type.Type -> TypeSession Bool
497 ty_either <- vhdl_ty_either ty
498 return $ case ty_either of
502 vec_len :: Type.Type -> TypeSession Int
504 veclens <- getA vsTfpInts
505 let len_ty = tfvec_len_ty ty
506 let existing_len = Map.lookup (OrdType len_ty) veclens
508 Just len -> return len
510 let new_len = tfvec_len ty
511 modA vsTfpInts (Map.insert (OrdType len_ty) (new_len))