2 -- Functions to generate VHDL from FlatFunctions
7 import qualified Data.Foldable as Foldable
8 import qualified Data.List as List
9 import qualified Data.Map as Map
10 import qualified Maybe
11 import qualified Control.Monad as Monad
12 import qualified Control.Arrow as Arrow
13 import qualified Control.Monad.Trans.State as State
14 import qualified Data.Traversable as Traversable
15 import qualified Data.Monoid as Monoid
17 import qualified Data.Accessor.MonadState as MonadState
18 import Text.Regex.Posix
22 import qualified ForSyDe.Backend.VHDL.AST as AST
28 import qualified OccName
31 import qualified IdInfo
32 import qualified TyCon
33 import qualified TcType
34 import qualified DataCon
35 import qualified CoreSubst
36 import qualified CoreUtils
37 import Outputable ( showSDoc, ppr )
43 import TranslatorTypes
49 import GlobalNameTable
52 [(CoreSyn.CoreBndr, CoreSyn.CoreExpr)]
53 -> [(AST.VHDLId, AST.DesignFile)]
55 createDesignFiles binds =
56 (mkVHDLBasicId "types", AST.DesignFile ieee_context [type_package_dec, type_package_body]) :
57 map (Arrow.second $ AST.DesignFile full_context) units
60 init_session = VHDLSession Map.empty Map.empty Map.empty Map.empty globalNameTable
61 (units, final_session) =
62 State.runState (createLibraryUnits binds) init_session
63 tyfun_decls = Map.elems (final_session ^.vsTypeFuns)
64 ty_decls = map mktydecl $ Map.elems (final_session ^. vsTypes)
65 vec_decls = map (\(v_id, v_def) -> AST.PDITD $ AST.TypeDec v_id v_def) (Map.elems (final_session ^. vsElemTypes))
66 tfvec_index_decl = AST.PDISD $ AST.SubtypeDec tfvec_indexTM tfvec_index_def
67 tfvec_range = AST.ConstraintRange $ AST.SubTypeRange (AST.PrimLit "-1") (AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerTM) highId Nothing)
68 tfvec_index_def = AST.SubtypeIn integerTM (Just tfvec_range)
70 AST.Library $ mkVHDLBasicId "IEEE",
71 mkUseAll ["IEEE", "std_logic_1164"],
72 mkUseAll ["IEEE", "numeric_std"]
75 mkUseAll ["work", "types"]
77 type_package_dec = AST.LUPackageDec $ AST.PackageDec (mkVHDLBasicId "types") ([tfvec_index_decl] ++ vec_decls ++ ty_decls ++ subProgSpecs)
78 type_package_body = AST.LUPackageBody $ AST.PackageBody typesId (concat tyfun_decls)
79 subProgSpecs = concat (map subProgSpec tyfun_decls)
80 subProgSpec = map (\(AST.SubProgBody spec _ _) -> AST.PDISS spec)
81 mktydecl :: (AST.VHDLId, Either AST.TypeDef AST.SubtypeIn) -> AST.PackageDecItem
82 mktydecl (ty_id, Left ty_def) = AST.PDITD $ AST.TypeDec ty_id ty_def
83 mktydecl (ty_id, Right ty_def) = AST.PDISD $ AST.SubtypeDec ty_id ty_def
85 -- Create a use foo.bar.all statement. Takes a list of components in the used
86 -- name. Must contain at least two components
87 mkUseAll :: [String] -> AST.ContextItem
89 AST.Use $ from AST.:.: AST.All
91 base_prefix = (AST.NSimple $ mkVHDLBasicId $ head ss)
92 from = foldl select base_prefix (tail ss)
93 select prefix s = AST.NSelected $ prefix AST.:.: (AST.SSimple $ mkVHDLBasicId s)
96 [(CoreSyn.CoreBndr, CoreSyn.CoreExpr)]
97 -> VHDLState [(AST.VHDLId, [AST.LibraryUnit])]
99 createLibraryUnits binds = do
100 entities <- Monad.mapM createEntity binds
101 archs <- Monad.mapM createArchitecture binds
104 let AST.EntityDec id _ = ent in
105 (id, [AST.LUEntity ent, AST.LUArch arch])
109 -- | Create an entity for a given function
111 (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- | The function
112 -> VHDLState AST.EntityDec -- | The resulting entity
114 createEntity (fname, expr) = do
115 -- Strip off lambda's, these will be arguments
116 let (args, letexpr) = CoreSyn.collectBinders expr
117 args' <- Monad.mapM mkMap args
118 -- There must be a let at top level
119 let (CoreSyn.Let binds (CoreSyn.Var res)) = letexpr
121 let vhdl_id = mkVHDLBasicId $ bndrToString fname ++ "_" ++ varToStringUniq fname
122 let ent_decl' = createEntityAST vhdl_id args' res'
123 let AST.EntityDec entity_id _ = ent_decl'
124 let signature = Entity entity_id args' res'
125 modA vsSignatures (Map.insert fname signature)
129 --[(SignalId, SignalInfo)]
131 -> VHDLState VHDLSignalMapElement
132 -- We only need the vsTypes element from the state
135 --info = Maybe.fromMaybe
136 -- (error $ "Signal not found in the name map? This should not happen!")
137 -- (lookup id sigmap)
138 -- Assume the bndr has a valid VHDL id already
139 id = bndrToVHDLId bndr
140 ty = Var.varType bndr
142 if True -- isPortSigUse $ sigUse info
144 type_mark <- vhdl_ty ty
145 return $ Just (id, type_mark)
150 -- | Create the VHDL AST for an entity
152 AST.VHDLId -- | The name of the function
153 -> [VHDLSignalMapElement] -- | The entity's arguments
154 -> VHDLSignalMapElement -- | The entity's result
155 -> AST.EntityDec -- | The entity with the ent_decl filled in as well
157 createEntityAST vhdl_id args res =
158 AST.EntityDec vhdl_id ports
160 -- Create a basic Id, since VHDL doesn't grok filenames with extended Ids.
161 ports = Maybe.catMaybes $
162 map (mkIfaceSigDec AST.In) args
163 ++ [mkIfaceSigDec AST.Out res]
165 -- Add a clk port if we have state
166 clk_port = if True -- hasState hsfunc
168 Just $ AST.IfaceSigDec (mkVHDLExtId "clk") AST.In VHDL.std_logic_ty
172 -- | Create a port declaration
174 AST.Mode -- | The mode for the port (In / Out)
175 -> Maybe (AST.VHDLId, AST.TypeMark) -- | The id and type for the port
176 -> Maybe AST.IfaceSigDec -- | The resulting port declaration
178 mkIfaceSigDec mode (Just (id, ty)) = Just $ AST.IfaceSigDec id mode ty
179 mkIfaceSigDec _ Nothing = Nothing
181 -- | Generate a VHDL entity name for the given hsfunc
183 -- TODO: This doesn't work for functions with multiple signatures!
184 -- Use a Basic Id, since using extended id's for entities throws off
185 -- precision and causes problems when generating filenames.
186 mkVHDLBasicId $ hsFuncName hsfunc
188 -- | Create an architecture for a given function
189 createArchitecture ::
190 (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The function
191 -> VHDLState AST.ArchBody -- ^ The architecture for this function
193 createArchitecture (fname, expr) = do
194 signaturemap <- getA vsSignatures
195 let signature = Maybe.fromMaybe
196 (error $ "Generating architecture for function " ++ (pprString fname) ++ "without signature? This should not happen!")
197 (Map.lookup fname signaturemap)
198 let entity_id = ent_id signature
199 -- Strip off lambda's, these will be arguments
200 let (args, letexpr) = CoreSyn.collectBinders expr
201 -- There must be a let at top level
202 let (CoreSyn.Let (CoreSyn.Rec binds) (Var res)) = letexpr
204 -- Create signal declarations for all binders in the let expression, except
205 -- for the output port (that will already have an output port declared in
207 sig_dec_maybes <- mapM (mkSigDec' . fst) (filter ((/=res).fst) binds)
208 let sig_decs = Maybe.catMaybes $ sig_dec_maybes
210 statementss <- Monad.mapM mkConcSm binds
211 let statements = concat statementss
212 return $ AST.ArchBody (mkVHDLBasicId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) (statements ++ procs')
214 procs = map mkStateProcSm [] -- (makeStatePairs flatfunc)
215 procs' = map AST.CSPSm procs
216 -- mkSigDec only uses vsTypes from the state
219 -- | Looks up all pairs of old state, new state signals, together with
220 -- the state id they represent.
221 makeStatePairs :: FlatFunction -> [(StateId, SignalInfo, SignalInfo)]
222 makeStatePairs flatfunc =
223 [(Maybe.fromJust $ oldStateId $ sigUse old_info, old_info, new_info)
224 | old_info <- map snd (flat_sigs flatfunc)
225 , new_info <- map snd (flat_sigs flatfunc)
226 -- old_info must be an old state (and, because of the next equality,
227 -- new_info must be a new state).
228 , Maybe.isJust $ oldStateId $ sigUse old_info
229 -- And the state numbers must match
230 , (oldStateId $ sigUse old_info) == (newStateId $ sigUse new_info)]
232 -- Replace the second tuple element with the corresponding SignalInfo
233 --args_states = map (Arrow.second $ signalInfo sigs) args
234 mkStateProcSm :: (StateId, SignalInfo, SignalInfo) -> AST.ProcSm
235 mkStateProcSm (num, old, new) =
236 AST.ProcSm label [clk] [statement]
238 label = mkVHDLExtId $ "state_" ++ (show num)
239 clk = mkVHDLExtId "clk"
240 rising_edge = AST.NSimple $ mkVHDLBasicId "rising_edge"
241 wform = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple $ getSignalId new) Nothing]
242 assign = AST.SigAssign (AST.NSimple $ getSignalId old) wform
243 rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
244 statement = AST.IfSm rising_edge_clk [assign] [] Nothing
246 mkSigDec :: CoreSyn.CoreBndr -> VHDLState (Maybe AST.SigDec)
248 if True then do --isInternalSigUse use || isStateSigUse use then do
249 type_mark <- vhdl_ty $ Var.varType bndr
250 return $ Just (AST.SigDec (bndrToVHDLId bndr) type_mark Nothing)
254 -- | Creates a VHDL Id from a named SignalInfo. Errors out if the SignalInfo
256 getSignalId :: SignalInfo -> AST.VHDLId
258 mkVHDLExtId $ Maybe.fromMaybe
259 (error $ "Unnamed signal? This should not happen!")
262 -- | Transforms a core binding into a VHDL concurrent statement
264 (CoreSyn.CoreBndr, CoreSyn.CoreExpr) -- ^ The binding to process
265 -> VHDLState [AST.ConcSm] -- ^ The corresponding VHDL component instantiations.
268 -- Ignore Cast expressions, they should not longer have any meaning as long as
269 -- the type works out.
270 mkConcSm (bndr, Cast expr ty) = mkConcSm (bndr, expr)
272 mkConcSm (bndr, app@(CoreSyn.App _ _))= do
273 let (CoreSyn.Var f, args) = CoreSyn.collectArgs app
274 let valargs' = filter isValArg args
275 let valargs = filter (\(CoreSyn.Var bndr) -> not (Id.isDictId bndr)) valargs'
276 case Var.globalIdVarDetails f of
277 IdInfo.DataConWorkId dc ->
278 -- It's a datacon. Create a record from its arguments.
279 -- First, filter out type args. TODO: Is this the best way to do this?
280 -- The types should already have been taken into acocunt when creating
281 -- the signal, so this should probably work...
282 --let valargs = filter isValArg args in
283 if all is_var valargs then do
284 labels <- getFieldLabels (CoreUtils.exprType app)
285 return $ zipWith mkassign labels valargs
287 error $ "VHDL.mkConcSm Not in normal form: One ore more complex arguments: " ++ pprString args
289 mkassign :: AST.VHDLId -> CoreExpr -> AST.ConcSm
290 mkassign label (Var arg) =
291 let sel_name = mkSelectedName bndr label in
292 mkUncondAssign (Right sel_name) (varToVHDLExpr arg)
293 IdInfo.VanillaGlobal -> do
294 -- It's a global value imported from elsewhere. These can be builtin
296 funSignatures <- getA vsNameTable
297 case (Map.lookup (bndrToString f) funSignatures) of
298 Just (arg_count, builder) ->
299 if length valargs == arg_count then
301 sigs = map (bndrToString.varBndr) valargs
302 sigsNames = map (\signal -> (AST.PrimName (AST.NSimple (mkVHDLExtId signal)))) sigs
303 func = builder sigsNames
304 src_wform = AST.Wform [AST.WformElem func Nothing]
305 dst_name = AST.NSimple (mkVHDLExtId (bndrToString bndr))
306 assign = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
308 return [AST.CSSASm assign]
310 error $ "VHDL.mkConcSm Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ pprString valargs
311 Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
312 IdInfo.NotGlobalId -> do
313 signatures <- getA vsSignatures
314 -- This is a local id, so it should be a function whose definition we
315 -- have and which can be turned into a component instantiation.
317 signature = Maybe.fromMaybe
318 (error $ "Using function '" ++ (bndrToString f) ++ "' without signature? This should not happen!")
319 (Map.lookup f signatures)
320 entity_id = ent_id signature
321 label = "comp_ins_" ++ bndrToString bndr
322 -- Add a clk port if we have state
323 --clk_port = Maybe.fromJust $ mkAssocElem (Just $ mkVHDLExtId "clk") "clk"
324 clk_port = Maybe.fromJust $ mkAssocElem (Just $ mkVHDLExtId "clk") "clk"
325 --portmaps = mkAssocElems sigs args res signature ++ (if hasState hsfunc then [clk_port] else [])
326 portmaps = clk_port : mkAssocElems args bndr signature
328 return [AST.CSISm $ AST.CompInsSm (mkVHDLExtId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect portmaps)]
329 details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
331 -- A single alt case must be a selector. This means thee scrutinee is a simple
332 -- variable, the alternative is a dataalt with a single non-wild binder that
334 mkConcSm (bndr, expr@(Case (Var scrut) b ty [alt])) =
336 (DataAlt dc, bndrs, (Var sel_bndr)) -> do
337 case List.elemIndex sel_bndr bndrs of
339 labels <- getFieldLabels (Id.idType scrut)
340 let label = labels!!i
341 let sel_name = mkSelectedName scrut label
342 let sel_expr = AST.PrimName sel_name
343 return [mkUncondAssign (Left bndr) sel_expr]
344 Nothing -> error $ "VHDL.mkConcSM Not in normal form: Not a selector case:\n" ++ (pprString expr)
346 _ -> error $ "VHDL.mkConcSM Not in normal form: Not a selector case:\n" ++ (pprString expr)
348 -- Multiple case alt are be conditional assignments and have only wild
349 -- binders in the alts and only variables in the case values and a variable
350 -- for a scrutinee. We check the constructor of the second alt, since the
351 -- first is the default case, if there is any.
352 mkConcSm (bndr, (Case (Var scrut) b ty [(_, _, Var false), (con, _, Var true)])) =
354 cond_expr = (varToVHDLExpr scrut) AST.:=: (conToVHDLExpr con)
355 true_expr = (varToVHDLExpr true)
356 false_expr = (varToVHDLExpr false)
358 return [mkCondAssign (Left bndr) cond_expr true_expr false_expr]
359 mkConcSm (_, (Case (Var _) _ _ alts)) = error "VHDL.mkConcSm Not in normal form: Case statement with more than two alternatives"
360 mkConcSm (_, Case _ _ _ _) = error "VHDL.mkConcSm Not in normal form: Case statement has does not have a simple variable as scrutinee"
361 mkConcSm (bndr, expr) = error $ "VHDL.mkConcSM Unsupported binding in let expression: " ++ pprString bndr ++ " = " ++ pprString expr
363 -- Create an unconditional assignment statement
365 Either CoreBndr AST.VHDLName -- ^ The signal to assign to
366 -> AST.Expr -- ^ The expression to assign
367 -> AST.ConcSm -- ^ The resulting concurrent statement
368 mkUncondAssign dst expr = mkAssign dst Nothing expr
370 -- Create a conditional assignment statement
372 Either CoreBndr AST.VHDLName -- ^ The signal to assign to
373 -> AST.Expr -- ^ The condition
374 -> AST.Expr -- ^ The value when true
375 -> AST.Expr -- ^ The value when false
376 -> AST.ConcSm -- ^ The resulting concurrent statement
377 mkCondAssign dst cond true false = mkAssign dst (Just (cond, true)) false
379 -- Create a conditional or unconditional assignment statement
381 Either CoreBndr AST.VHDLName -> -- ^ The signal to assign to
382 Maybe (AST.Expr , AST.Expr) -> -- ^ Optionally, the condition to test for
383 -- and the value to assign when true.
384 AST.Expr -> -- ^ The value to assign when false or no condition
385 AST.ConcSm -- ^ The resulting concurrent statement
387 mkAssign dst cond false_expr =
389 -- I'm not 100% how this assignment AST works, but this gets us what we
391 whenelse = case cond of
392 Just (cond_expr, true_expr) ->
394 true_wform = AST.Wform [AST.WformElem true_expr Nothing]
396 [AST.WhenElse true_wform cond_expr]
398 false_wform = AST.Wform [AST.WformElem false_expr Nothing]
399 dst_name = case dst of
400 Left bndr -> AST.NSimple (bndrToVHDLId bndr)
402 assign = dst_name AST.:<==: (AST.ConWforms whenelse false_wform Nothing)
406 -- Create a record field selector that selects the given label from the record
407 -- stored in the given binder.
408 mkSelectedName :: CoreBndr -> AST.VHDLId -> AST.VHDLName
409 mkSelectedName bndr label =
411 sel_prefix = AST.NSimple $ bndrToVHDLId bndr
412 sel_suffix = AST.SSimple $ label
414 AST.NSelected $ sel_prefix AST.:.: sel_suffix
416 -- Finds the field labels for VHDL type generated for the given Core type,
417 -- which must result in a record type.
418 getFieldLabels :: Type.Type -> VHDLState [AST.VHDLId]
419 getFieldLabels ty = do
420 -- Ensure that the type is generated (but throw away it's VHDLId)
422 -- Get the types map, lookup and unpack the VHDL TypeDef
423 types <- getA vsTypes
424 case Map.lookup (OrdType ty) types of
425 Just (_, Left (AST.TDR (AST.RecordTypeDef elems))) -> return $ map (\(AST.ElementDec id _) -> id) elems
426 _ -> error $ "VHDL.getFieldLabels Type not found or not a record type? This should not happen! Type: " ++ (show ty)
428 -- Turn a variable reference into a AST expression
429 varToVHDLExpr :: Var.Var -> AST.Expr
430 varToVHDLExpr var = AST.PrimName $ AST.NSimple $ bndrToVHDLId var
432 -- Turn a constructor into an AST expression. For dataconstructors, this is
433 -- only the constructor itself, not any arguments it has. Should not be called
434 -- with a DEFAULT constructor.
435 conToVHDLExpr :: CoreSyn.AltCon -> AST.Expr
436 conToVHDLExpr (DataAlt dc) = AST.PrimLit lit
438 tycon = DataCon.dataConTyCon dc
439 tyname = TyCon.tyConName tycon
440 dcname = DataCon.dataConName dc
441 lit = case Name.getOccString tyname of
442 -- TODO: Do something more robust than string matching
443 "Bit" -> case Name.getOccString dcname of "High" -> "'1'"; "Low" -> "'0'"
444 "Bool" -> case Name.getOccString dcname of "True" -> "true"; "False" -> "false"
445 conToVHDLExpr (LitAlt _) = error "VHDL.conToVHDLExpr Literals not support in case alternatives yet"
446 conToVHDLExpr DEFAULT = error "VHDL.conToVHDLExpr DEFAULT alternative should not occur here!"
451 mkConcSm sigs (UncondDef src dst) _ = do
452 src_expr <- vhdl_expr src
453 let src_wform = AST.Wform [AST.WformElem src_expr Nothing]
454 let dst_name = AST.NSimple (getSignalId $ signalInfo sigs dst)
455 let assign = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
456 return $ AST.CSSASm assign
458 vhdl_expr (Left id) = return $ mkIdExpr sigs id
459 vhdl_expr (Right expr) =
462 return $ (mkIdExpr sigs id) AST.:=: (AST.PrimLit lit)
463 (Literal lit Nothing) ->
464 return $ AST.PrimLit lit
465 (Literal lit (Just ty)) -> do
466 -- Create a cast expression, which is just a function call using the
467 -- type name as the function name.
468 let litexpr = AST.PrimLit lit
470 let ty_name = AST.NSimple ty_id
471 let args = [Nothing AST.:=>: (AST.ADExpr litexpr)]
472 return $ AST.PrimFCall $ AST.FCall ty_name args
474 return $ (mkIdExpr sigs a) AST.:=: (mkIdExpr sigs b)
476 mkConcSm sigs (CondDef cond true false dst) _ =
478 cond_expr = mkIdExpr sigs cond
479 true_expr = mkIdExpr sigs true
480 false_expr = mkIdExpr sigs false
481 false_wform = AST.Wform [AST.WformElem false_expr Nothing]
482 true_wform = AST.Wform [AST.WformElem true_expr Nothing]
483 whenelse = AST.WhenElse true_wform cond_expr
484 dst_name = AST.NSimple (getSignalId $ signalInfo sigs dst)
485 assign = dst_name AST.:<==: (AST.ConWforms [whenelse] false_wform Nothing)
487 return $ AST.CSSASm assign
489 -- | Turn a SignalId into a VHDL Expr
490 mkIdExpr :: [(SignalId, SignalInfo)] -> SignalId -> AST.Expr
492 let src_name = AST.NSimple (getSignalId $ signalInfo sigs id) in
493 AST.PrimName src_name
496 [CoreSyn.CoreExpr] -- | The argument that are applied to function
497 -> CoreSyn.CoreBndr -- | The binder in which to store the result
498 -> Entity -- | The entity to map against.
499 -> [AST.AssocElem] -- | The resulting port maps
501 mkAssocElems args res entity =
502 -- Create the actual AssocElems
503 Maybe.catMaybes $ zipWith mkAssocElem ports sigs
505 -- Turn the ports and signals from a map into a flat list. This works,
506 -- since the maps must have an identical form by definition. TODO: Check
508 arg_ports = ent_args entity
509 res_port = ent_res entity
510 -- Extract the id part from the (id, type) tuple
511 ports = map (Monad.liftM fst) (res_port : arg_ports)
512 -- Translate signal numbers into names
513 sigs = (bndrToString res : map (bndrToString.varBndr) args)
515 -- Turns a Var CoreExpr into the Id inside it. Will of course only work for
516 -- simple Var CoreExprs, not complexer ones.
517 varBndr :: CoreSyn.CoreExpr -> Var.Id
518 varBndr (CoreSyn.Var id) = id
520 -- | Look up a signal in the signal name map
521 lookupSigName :: [(SignalId, SignalInfo)] -> SignalId -> String
522 lookupSigName sigs sig = name
524 info = Maybe.fromMaybe
525 (error $ "Unknown signal " ++ (show sig) ++ " used? This should not happen!")
527 name = Maybe.fromMaybe
528 (error $ "Unnamed signal " ++ (show sig) ++ " used? This should not happen!")
531 -- | Create an VHDL port -> signal association
532 mkAssocElem :: Maybe AST.VHDLId -> String -> Maybe AST.AssocElem
533 mkAssocElem (Just port) signal = Just $ Just port AST.:=>: (AST.ADName (AST.NSimple (mkVHDLExtId signal)))
534 mkAssocElem Nothing _ = Nothing
536 -- | The VHDL Bit type
537 bit_ty :: AST.TypeMark
538 bit_ty = AST.unsafeVHDLBasicId "Bit"
540 -- | The VHDL Boolean type
541 bool_ty :: AST.TypeMark
542 bool_ty = AST.unsafeVHDLBasicId "Boolean"
544 -- | The VHDL std_logic
545 std_logic_ty :: AST.TypeMark
546 std_logic_ty = AST.unsafeVHDLBasicId "std_logic"
548 -- Translate a Haskell type to a VHDL type
549 vhdl_ty :: Type.Type -> VHDLState AST.TypeMark
551 typemap <- getA vsTypes
552 let builtin_ty = do -- See if this is a tycon and lookup its name
553 (tycon, args) <- Type.splitTyConApp_maybe ty
554 let name = Name.getOccString (TyCon.tyConName tycon)
555 Map.lookup name builtin_types
556 -- If not a builtin type, try the custom types
557 let existing_ty = (fmap fst) $ Map.lookup (OrdType ty) typemap
558 case Monoid.getFirst $ Monoid.mconcat (map Monoid.First [builtin_ty, existing_ty]) of
559 -- Found a type, return it
561 -- No type yet, try to construct it
563 newty_maybe <- (construct_vhdl_ty ty)
565 Just (ty_id, ty_def) -> do
566 -- TODO: Check name uniqueness
567 modA vsTypes (Map.insert (OrdType ty) (ty_id, ty_def))
569 Nothing -> error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty)
571 -- Construct a new VHDL type for the given Haskell type.
572 construct_vhdl_ty :: Type.Type -> VHDLState (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
573 construct_vhdl_ty ty = do
574 case Type.splitTyConApp_maybe ty of
575 Just (tycon, args) -> do
576 let name = Name.getOccString (TyCon.tyConName tycon)
579 res <- mk_vector_ty (tfvec_len ty) (tfvec_elem ty)
580 return $ Just $ (Arrow.second Right) res
582 -- res <- mk_vector_ty (sized_word_len ty) ty
583 -- return $ Just $ (Arrow.second Left) res
585 res <- mk_natural_ty 0 (ranged_word_bound ty)
586 return $ Just $ (Arrow.second Right) res
587 -- Create a custom type from this tycon
588 otherwise -> mk_tycon_ty tycon args
589 Nothing -> return $ Nothing
591 -- | Create VHDL type for a custom tycon
592 mk_tycon_ty :: TyCon.TyCon -> [Type.Type] -> VHDLState (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn))
593 mk_tycon_ty tycon args =
594 case TyCon.tyConDataCons tycon of
595 -- Not an algebraic type
596 [] -> error $ "Only custom algebraic types are supported: " ++ (showSDoc $ ppr tycon)
598 let arg_tys = DataCon.dataConRepArgTys dc
599 -- TODO: CoreSubst docs say each Subs can be applied only once. Is this a
600 -- violation? Or does it only mean not to apply it again to the same
602 let real_arg_tys = map (CoreSubst.substTy subst) arg_tys
603 elem_tys <- mapM vhdl_ty real_arg_tys
604 let elems = zipWith AST.ElementDec recordlabels elem_tys
605 -- For a single construct datatype, build a record with one field for
607 -- TODO: Add argument type ids to this, to ensure uniqueness
608 -- TODO: Special handling for tuples?
609 let ty_id = mkVHDLExtId $ nameToString (TyCon.tyConName tycon)
610 let ty_def = AST.TDR $ AST.RecordTypeDef elems
611 return $ Just (ty_id, Left ty_def)
612 dcs -> error $ "Only single constructor datatypes supported: " ++ (showSDoc $ ppr tycon)
614 -- Create a subst that instantiates all types passed to the tycon
615 -- TODO: I'm not 100% sure that this is the right way to do this. It seems
616 -- to work so far, though..
617 tyvars = TyCon.tyConTyVars tycon
618 subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
620 -- | Create a VHDL vector type
622 Int -- ^ The length of the vector
623 -> Type.Type -- ^ The Haskell element type of the Vector
624 -> VHDLState (AST.TypeMark, AST.SubtypeIn) -- The typemark created.
626 mk_vector_ty len el_ty = do
627 elem_types_map <- getA vsElemTypes
628 el_ty_tm <- vhdl_ty el_ty
629 let ty_id = mkVHDLExtId $ "vector-"++ (AST.fromVHDLId el_ty_tm) ++ "-0_to_" ++ (show len)
630 let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len - 1))]
631 let existing_elem_ty = (fmap fst) $ Map.lookup (OrdType el_ty) elem_types_map
632 case existing_elem_ty of
634 let ty_def = AST.SubtypeIn t (Just range)
635 return (ty_id, ty_def)
637 let vec_id = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId el_ty_tm)
638 let vec_def = AST.TDA $ AST.UnconsArrayDef [tfvec_indexTM] el_ty_tm
639 modA vsElemTypes (Map.insert (OrdType el_ty) (vec_id, vec_def))
640 modA vsTypeFuns (Map.insert (OrdType el_ty) (genUnconsVectorFuns el_ty_tm vec_id))
641 let ty_def = AST.SubtypeIn vec_id (Just range)
642 return (ty_id, ty_def)
645 Int -- ^ The minimum bound (> 0)
646 -> Int -- ^ The maximum bound (> minimum bound)
647 -> VHDLState (AST.TypeMark, AST.SubtypeIn) -- The typemark created.
648 mk_natural_ty min_bound max_bound = do
649 let ty_id = mkVHDLExtId $ "nat_" ++ (show min_bound) ++ "_to_" ++ (show max_bound)
650 let range = AST.ConstraintRange $ AST.SubTypeRange (AST.PrimLit $ (show min_bound)) (AST.PrimLit $ (show max_bound))
651 let ty_def = AST.SubtypeIn naturalTM (Just range)
652 return (ty_id, ty_def)
656 ("Bit", std_logic_ty),
657 ("Bool", bool_ty) -- TysWiredIn.boolTy
661 -- Can only contain alphanumerics and underscores. The supplied string must be
662 -- a valid basic id, otherwise an error value is returned. This function is
663 -- not meant to be passed identifiers from a source file, use mkVHDLExtId for
665 mkVHDLBasicId :: String -> AST.VHDLId
667 AST.unsafeVHDLBasicId $ (strip_multiscore . strip_leading . strip_invalid) s
669 -- Strip invalid characters.
670 strip_invalid = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.")
671 -- Strip leading numbers and underscores
672 strip_leading = dropWhile (`elem` ['0'..'9'] ++ "_")
673 -- Strip multiple adjacent underscores
674 strip_multiscore = concat . map (\cs ->
680 -- Shortcut for Extended VHDL Id's. These Id's can contain a lot more
681 -- different characters than basic ids, but can never be used to refer to
683 -- Use extended Ids for any values that are taken from the source file.
684 mkVHDLExtId :: String -> AST.VHDLId
686 AST.unsafeVHDLExtId $ strip_invalid s
688 -- Allowed characters, taken from ForSyde's mkVHDLExtId
689 allowed = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ " \"#&\\'()*+,./:;<=>_|!$%@?[]^`{}~-"
690 strip_invalid = filter (`elem` allowed)
692 -- Creates a VHDL Id from a binder
697 bndrToVHDLId = mkVHDLExtId . OccName.occNameString . Name.nameOccName . Var.varName
699 -- Extracts the binder name as a String
703 bndrToString = OccName.occNameString . Name.nameOccName . Var.varName
705 -- Get the string version a Var's unique
706 varToStringUniq = show . Var.varUnique
708 -- Extracts the string version of the name
709 nameToString :: Name.Name -> String
710 nameToString = OccName.occNameString . Name.nameOccName
712 recordlabels = map (\c -> mkVHDLBasicId [c]) ['A'..'Z']
714 -- | Map a port specification of a builtin function to a VHDL Signal to put in
716 toVHDLSignalMapElement :: (String, AST.TypeMark) -> VHDLSignalMapElement
717 toVHDLSignalMapElement (name, ty) = Just (mkVHDLBasicId name, ty)