Make output ports optional.
[matthijs/master-project/cλash.git] / cλash / CLasH / VHDL / VHDLTools.hs
1 {-# LANGUAGE RelaxedPolyRec #-} -- Needed for vhdl_ty_either', for some reason...
2 module CLasH.VHDL.VHDLTools where
3
4 -- Standard modules
5 import qualified Maybe
6 import qualified Data.Either as Either
7 import qualified Data.List as List
8 import qualified Data.Map as Map
9 import qualified Control.Monad as Monad
10 import qualified Control.Arrow as Arrow
11 import qualified Control.Monad.Trans.State as State
12 import qualified Data.Monoid as Monoid
13 import Data.Accessor
14 import Data.Accessor.MonadState as MonadState
15 import Debug.Trace
16
17 -- ForSyDe
18 import qualified Language.VHDL.AST as AST
19
20 -- GHC API
21 import CoreSyn
22 import qualified Name
23 import qualified OccName
24 import qualified Var
25 import qualified Id
26 import qualified IdInfo
27 import qualified TyCon
28 import qualified Type
29 import qualified DataCon
30 import qualified CoreSubst
31 import qualified Outputable
32
33 -- Local imports
34 import CLasH.VHDL.VHDLTypes
35 import CLasH.Translator.TranslatorTypes
36 import CLasH.Utils.Core.CoreTools
37 import CLasH.Utils
38 import CLasH.Utils.Pretty
39 import CLasH.VHDL.Constants
40
41 -----------------------------------------------------------------------------
42 -- Functions to generate concurrent statements
43 -----------------------------------------------------------------------------
44
45 -- Create an unconditional assignment statement
46 mkUncondAssign ::
47   Either CoreBndr AST.VHDLName -- ^ The signal to assign to
48   -> AST.Expr -- ^ The expression to assign
49   -> AST.ConcSm -- ^ The resulting concurrent statement
50 mkUncondAssign dst expr = mkAssign dst Nothing expr
51
52 -- Create a conditional assignment statement
53 mkCondAssign ::
54   Either CoreBndr AST.VHDLName -- ^ The signal to assign to
55   -> AST.Expr -- ^ The condition
56   -> AST.Expr -- ^ The value when true
57   -> AST.Expr -- ^ The value when false
58   -> AST.ConcSm -- ^ The resulting concurrent statement
59 mkCondAssign dst cond true false = mkAssign dst (Just (cond, true)) false
60
61 -- Create a conditional or unconditional assignment statement
62 mkAssign ::
63   Either CoreBndr AST.VHDLName -- ^ The signal to assign to
64   -> Maybe (AST.Expr , AST.Expr) -- ^ Optionally, the condition to test for
65                                  -- and the value to assign when true.
66   -> AST.Expr -- ^ The value to assign when false or no condition
67   -> AST.ConcSm -- ^ The resulting concurrent statement
68 mkAssign dst cond false_expr =
69   let
70     -- I'm not 100% how this assignment AST works, but this gets us what we
71     -- want...
72     whenelse = case cond of
73       Just (cond_expr, true_expr) -> 
74         let 
75           true_wform = AST.Wform [AST.WformElem true_expr Nothing] 
76         in
77           [AST.WhenElse true_wform cond_expr]
78       Nothing -> []
79     false_wform = AST.Wform [AST.WformElem false_expr Nothing]
80     dst_name  = case dst of
81       Left bndr -> AST.NSimple (varToVHDLId bndr)
82       Right name -> name
83     assign    = dst_name AST.:<==: (AST.ConWforms whenelse false_wform Nothing)
84   in
85     AST.CSSASm assign
86
87 mkAssocElems :: 
88   [AST.Expr]                    -- ^ The argument that are applied to function
89   -> AST.VHDLName               -- ^ The binder in which to store the result
90   -> Entity                     -- ^ The entity to map against.
91   -> TranslatorSession [AST.AssocElem] -- ^ The resulting port maps
92 mkAssocElems args res entity =
93     return $ arg_maps ++ (Maybe.maybeToList res_map_maybe)
94   where
95     arg_ports = ent_args entity
96     res_port_maybe = ent_res entity
97     -- Create an expression of res to map against the output port
98     res_expr = vhdlNameToVHDLExpr res
99     -- Map each of the input ports
100     arg_maps = zipWith mkAssocElem (map fst arg_ports) args
101     -- Map the output port, if present
102     res_map_maybe = fmap (\port -> mkAssocElem (fst port) res_expr) res_port_maybe
103
104 -- | Create an VHDL port -> signal association
105 mkAssocElem :: AST.VHDLId -> AST.Expr -> AST.AssocElem
106 mkAssocElem port signal = Just port AST.:=>: (AST.ADExpr signal) 
107
108 -- | Create an aggregate signal
109 mkAggregateSignal :: [AST.Expr] -> AST.Expr
110 mkAggregateSignal x = AST.Aggregate (map (\z -> AST.ElemAssoc Nothing z) x)
111
112 mkComponentInst ::
113   String -- ^ The portmap label
114   -> AST.VHDLId -- ^ The entity name
115   -> [AST.AssocElem] -- ^ The port assignments
116   -> AST.ConcSm
117 mkComponentInst label entity_id portassigns = AST.CSISm compins
118   where
119     -- We always have a clock port, so no need to map it anywhere but here
120     clk_port = mkAssocElem clockId (idToVHDLExpr clockId)
121     compins = AST.CompInsSm (mkVHDLExtId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect (portassigns ++ [clk_port]))
122
123 -----------------------------------------------------------------------------
124 -- Functions to generate VHDL Exprs
125 -----------------------------------------------------------------------------
126
127 varToVHDLExpr :: Var.Var -> TypeSession AST.Expr
128 varToVHDLExpr var = do
129   case Id.isDataConWorkId_maybe var of
130     Just dc -> return $ dataconToVHDLExpr dc
131     -- This is a dataconstructor.
132     -- Not a datacon, just another signal. Perhaps we should check for
133     -- local/global here as well?
134     -- Sadly so.. tfp decimals are types, not data constructors, but instances
135     -- should still be translated to integer literals. It is probebly not the
136     -- best solution to translate them here.
137     -- FIXME: Find a better solution for translating instances of tfp integers
138     Nothing -> do
139         let ty  = Var.varType var
140         case Type.splitTyConApp_maybe ty of
141                 Just (tycon, args) ->
142                   case Name.getOccString (TyCon.tyConName tycon) of
143                     "Dec" -> do
144                       len <- tfp_to_int ty
145                       return $ AST.PrimLit $ (show len)
146                     otherwise -> return $ AST.PrimName $ AST.NSimple $ varToVHDLId var
147
148 -- Turn a VHDLName into an AST expression
149 vhdlNameToVHDLExpr = AST.PrimName
150
151 -- Turn a VHDL Id into an AST expression
152 idToVHDLExpr = vhdlNameToVHDLExpr . AST.NSimple
153
154 -- Turn a Core expression into an AST expression
155 exprToVHDLExpr core = varToVHDLExpr (exprToVar core)
156
157 -- Turn a alternative constructor into an AST expression. For
158 -- dataconstructors, this is only the constructor itself, not any arguments it
159 -- has. Should not be called with a DEFAULT constructor.
160 altconToVHDLExpr :: CoreSyn.AltCon -> AST.Expr
161 altconToVHDLExpr (DataAlt dc) = dataconToVHDLExpr dc
162
163 altconToVHDLExpr (LitAlt _) = error "\nVHDL.conToVHDLExpr: Literals not support in case alternatives yet"
164 altconToVHDLExpr DEFAULT = error "\nVHDL.conToVHDLExpr: DEFAULT alternative should not occur here!"
165
166 -- Turn a datacon (without arguments!) into a VHDL expression.
167 dataconToVHDLExpr :: DataCon.DataCon -> AST.Expr
168 dataconToVHDLExpr dc = AST.PrimLit lit
169   where
170     tycon = DataCon.dataConTyCon dc
171     tyname = TyCon.tyConName tycon
172     dcname = DataCon.dataConName dc
173     lit = case Name.getOccString tyname of
174       -- TODO: Do something more robust than string matching
175       "Bit"      -> case Name.getOccString dcname of "High" -> "'1'"; "Low" -> "'0'"
176       "Bool" -> case Name.getOccString dcname of "True" -> "true"; "False" -> "false"
177
178 -----------------------------------------------------------------------------
179 -- Functions dealing with names, variables and ids
180 -----------------------------------------------------------------------------
181
182 -- Creates a VHDL Id from a binder
183 varToVHDLId ::
184   CoreSyn.CoreBndr
185   -> AST.VHDLId
186 varToVHDLId = mkVHDLExtId . varToString
187
188 -- Creates a VHDL Name from a binder
189 varToVHDLName ::
190   CoreSyn.CoreBndr
191   -> AST.VHDLName
192 varToVHDLName = AST.NSimple . varToVHDLId
193
194 -- Extracts the binder name as a String
195 varToString ::
196   CoreSyn.CoreBndr
197   -> String
198 varToString = OccName.occNameString . Name.nameOccName . Var.varName
199
200 -- Get the string version a Var's unique
201 varToStringUniq :: Var.Var -> String
202 varToStringUniq = show . Var.varUnique
203
204 -- Extracts the string version of the name
205 nameToString :: Name.Name -> String
206 nameToString = OccName.occNameString . Name.nameOccName
207
208 -- Shortcut for Basic VHDL Ids.
209 -- Can only contain alphanumerics and underscores. The supplied string must be
210 -- a valid basic id, otherwise an error value is returned. This function is
211 -- not meant to be passed identifiers from a source file, use mkVHDLExtId for
212 -- that.
213 mkVHDLBasicId :: String -> AST.VHDLId
214 mkVHDLBasicId s = 
215   AST.unsafeVHDLBasicId $ (strip_multiscore . strip_leading . strip_invalid) s
216   where
217     -- Strip invalid characters.
218     strip_invalid = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.")
219     -- Strip leading numbers and underscores
220     strip_leading = dropWhile (`elem` ['0'..'9'] ++ "_")
221     -- Strip multiple adjacent underscores
222     strip_multiscore = concat . map (\cs -> 
223         case cs of 
224           ('_':_) -> "_"
225           _ -> cs
226       ) . List.group
227
228 -- Shortcut for Extended VHDL Id's. These Id's can contain a lot more
229 -- different characters than basic ids, but can never be used to refer to
230 -- basic ids.
231 -- Use extended Ids for any values that are taken from the source file.
232 mkVHDLExtId :: String -> AST.VHDLId
233 mkVHDLExtId s = 
234   AST.unsafeVHDLExtId $ strip_invalid s
235   where 
236     -- Allowed characters, taken from ForSyde's mkVHDLExtId
237     allowed = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ " \"#&\\'()*+,./:;<=>_|!$%@?[]^`{}~-"
238     strip_invalid = filter (`elem` allowed)
239
240 -- Create a record field selector that selects the given label from the record
241 -- stored in the given binder.
242 mkSelectedName :: AST.VHDLName -> AST.VHDLId -> AST.VHDLName
243 mkSelectedName name label =
244    AST.NSelected $ name AST.:.: (AST.SSimple label) 
245
246 -- Create an indexed name that selects a given element from a vector.
247 mkIndexedName :: AST.VHDLName -> AST.Expr -> AST.VHDLName
248 -- Special case for already indexed names. Just add an index
249 mkIndexedName (AST.NIndexed (AST.IndexedName name indexes)) index =
250  AST.NIndexed (AST.IndexedName name (indexes++[index]))
251 -- General case for other names
252 mkIndexedName name index = AST.NIndexed (AST.IndexedName name [index])
253
254 -----------------------------------------------------------------------------
255 -- Functions dealing with VHDL types
256 -----------------------------------------------------------------------------
257
258 -- | Maps the string name (OccName) of a type to the corresponding VHDL type,
259 -- for a few builtin types.
260 builtin_types = 
261   Map.fromList [
262     ("Bit", Just std_logicTM),
263     ("Bool", Just booleanTM), -- TysWiredIn.boolTy
264     ("Dec", Just integerTM)
265   ]
266
267 -- Translate a Haskell type to a VHDL type, generating a new type if needed.
268 -- Returns an error value, using the given message, when no type could be
269 -- created. Returns Nothing when the type is valid, but empty.
270 vhdl_ty :: (TypedThing t, Outputable.Outputable t) => 
271   String -> t -> TypeSession (Maybe AST.TypeMark)
272 vhdl_ty msg ty = do
273   tm_either <- vhdl_ty_either ty
274   case tm_either of
275     Right tm -> return tm
276     Left err -> error $ msg ++ "\n" ++ err
277
278 -- Translate a Haskell type to a VHDL type, generating a new type if needed.
279 -- Returns either an error message or the resulting type.
280 vhdl_ty_either :: (TypedThing t, Outputable.Outputable t) => 
281   t -> TypeSession (Either String (Maybe AST.TypeMark))
282 vhdl_ty_either tything =
283   case getType tything of
284     Nothing -> return $ Left $ "VHDLTools.vhdl_ty: Typed thing without a type: " ++ pprString tything
285     Just ty -> vhdl_ty_either' ty
286
287 vhdl_ty_either' :: Type.Type -> TypeSession (Either String (Maybe AST.TypeMark))
288 vhdl_ty_either' ty = do
289   typemap <- getA tsTypes
290   htype_either <- mkHType ty
291   case htype_either of
292     -- No errors
293     Right htype -> do
294       let builtin_ty = do -- See if this is a tycon and lookup its name
295             (tycon, args) <- Type.splitTyConApp_maybe ty
296             let name = Name.getOccString (TyCon.tyConName tycon)
297             Map.lookup name builtin_types
298       -- If not a builtin type, try the custom types
299       let existing_ty = (Monad.liftM $ fmap fst) $ Map.lookup htype typemap
300       case Monoid.getFirst $ Monoid.mconcat (map Monoid.First [builtin_ty, existing_ty]) of
301         -- Found a type, return it
302         Just t -> return (Right t)
303         -- No type yet, try to construct it
304         Nothing -> do
305           newty_either <- (construct_vhdl_ty ty)
306           case newty_either of
307             Right newty  -> do
308               -- TODO: Check name uniqueness
309               modA tsTypes (Map.insert htype newty)
310               case newty of
311                 Just (ty_id, ty_def) -> do
312                   modA tsTypeDecls (\typedefs -> typedefs ++ [mktydecl (ty_id, ty_def)])
313                   return (Right $ Just ty_id)
314                 Nothing -> return $ Right Nothing
315             Left err -> return $ Left $
316               "VHDLTools.vhdl_ty: Unsupported Haskell type: " ++ pprString ty ++ "\n"
317               ++ err
318     -- Error when constructing htype
319     Left err -> return $ Left err 
320
321 -- Construct a new VHDL type for the given Haskell type. Returns an error
322 -- message or the resulting typemark and typedef.
323 construct_vhdl_ty :: Type.Type -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
324 -- State types don't generate VHDL
325 construct_vhdl_ty ty | isStateType ty = return $ Right Nothing
326 construct_vhdl_ty ty = do
327   case Type.splitTyConApp_maybe ty of
328     Just (tycon, args) -> do
329       let name = Name.getOccString (TyCon.tyConName tycon)
330       case name of
331         "TFVec" -> mk_vector_ty ty
332         "SizedWord" -> mk_unsigned_ty ty
333         "SizedInt"  -> mk_signed_ty ty
334         "RangedWord" -> do 
335           bound <- tfp_to_int (ranged_word_bound_ty ty)
336           mk_natural_ty 0 bound
337         -- Create a custom type from this tycon
338         otherwise -> mk_tycon_ty ty tycon args
339     Nothing -> return (Left $ "VHDLTools.construct_vhdl_ty: Cannot create type for non-tycon type: " ++ pprString ty ++ "\n")
340
341 -- | Create VHDL type for a custom tycon
342 mk_tycon_ty :: Type.Type -> TyCon.TyCon -> [Type.Type] -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
343 mk_tycon_ty ty tycon args =
344   case TyCon.tyConDataCons tycon of
345     -- Not an algebraic type
346     [] -> return (Left $ "VHDLTools.mk_tycon_ty: Only custom algebraic types are supported: " ++ pprString tycon ++ "\n")
347     [dc] -> do
348       let arg_tys = DataCon.dataConRepArgTys dc
349       -- TODO: CoreSubst docs say each Subs can be applied only once. Is this a
350       -- violation? Or does it only mean not to apply it again to the same
351       -- subject?
352       let real_arg_tys = map (CoreSubst.substTy subst) arg_tys
353       elem_tys_either <- mapM vhdl_ty_either real_arg_tys
354       case Either.partitionEithers elem_tys_either of
355         -- No errors in element types
356         ([], elem_tys') -> do
357           -- Throw away all empty members
358           case Maybe.catMaybes elem_tys' of
359             [] -> -- No non-empty members
360               return $ Right Nothing
361             elem_tys -> do
362               let elems = zipWith AST.ElementDec recordlabels elem_tys
363               -- For a single construct datatype, build a record with one field for
364               -- each argument.
365               -- TODO: Add argument type ids to this, to ensure uniqueness
366               -- TODO: Special handling for tuples?
367               let elem_names = concat $ map prettyShow elem_tys
368               let ty_id = mkVHDLExtId $ nameToString (TyCon.tyConName tycon) ++ elem_names
369               let ty_def = AST.TDR $ AST.RecordTypeDef elems
370               let tupshow = mkTupleShow elem_tys ty_id
371               modA tsTypeFuns $ Map.insert (OrdType ty, showIdString) (showId, tupshow)
372               return $ Right $ Just (ty_id, Left ty_def)
373         -- There were errors in element types
374         (errors, _) -> return $ Left $
375           "VHDLTools.mk_tycon_ty: Can not construct type for: " ++ pprString tycon ++ "\n because no type can be construced for some of the arguments.\n"
376           ++ (concat errors)
377     dcs -> return $ Left $ "VHDLTools.mk_tycon_ty: Only single constructor datatypes supported: " ++ pprString tycon ++ "\n"
378   where
379     -- Create a subst that instantiates all types passed to the tycon
380     -- TODO: I'm not 100% sure that this is the right way to do this. It seems
381     -- to work so far, though..
382     tyvars = TyCon.tyConTyVars tycon
383     subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
384     -- Generate a bunch of labels for fields of a record
385     recordlabels = map (\c -> mkVHDLBasicId [c]) ['A'..'Z']
386
387 -- | Create a VHDL vector type
388 mk_vector_ty ::
389   Type.Type -- ^ The Haskell type of the Vector
390   -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
391       -- ^ An error message or The typemark created.
392
393 mk_vector_ty ty = do
394   types_map <- getA tsTypes
395   env <- getA tsHscEnv
396   let (nvec_l, nvec_el) = Type.splitAppTy ty
397   let (nvec, leng) = Type.splitAppTy nvec_l
398   let vec_ty = Type.mkAppTy nvec nvec_el
399   len <- tfp_to_int (tfvec_len_ty ty)
400   let el_ty = tfvec_elem ty
401   el_ty_tm_either <- vhdl_ty_either el_ty
402   case el_ty_tm_either of
403     -- Could create element type
404     Right (Just el_ty_tm) -> do
405       let ty_id = mkVHDLExtId $ "vector-"++ (AST.fromVHDLId el_ty_tm) ++ "-0_to_" ++ (show len)
406       let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len - 1))]
407       let existing_elem_ty = (fmap $ fmap fst) $ Map.lookup (StdType $ OrdType vec_ty) types_map
408       case existing_elem_ty of
409         Just (Just t) -> do
410           let ty_def = AST.SubtypeIn t (Just range)
411           return (Right $ Just (ty_id, Right ty_def))
412         Nothing -> do
413           let vec_id = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId el_ty_tm)
414           let vec_def = AST.TDA $ AST.UnconsArrayDef [tfvec_indexTM] el_ty_tm
415           modA tsTypes (Map.insert (StdType $ OrdType vec_ty) (Just (vec_id, (Left vec_def))))
416           modA tsTypeDecls (\typedefs -> typedefs ++ [mktydecl (vec_id, (Left vec_def))])
417           let vecShowFuns = mkVectorShow el_ty_tm vec_id
418           mapM_ (\(id, subprog) -> modA tsTypeFuns $ Map.insert (OrdType vec_ty, id) ((mkVHDLExtId id), subprog)) vecShowFuns
419           let ty_def = AST.SubtypeIn vec_id (Just range)
420           return (Right $ Just (ty_id, Right ty_def))
421     -- Empty element type? Empty vector type then. TODO: Does this make sense?
422     -- Probably needs changes in the builtin functions as well...
423     Right Nothing -> return $ Right Nothing
424     -- Could not create element type
425     Left err -> return $ Left $ 
426       "VHDLTools.mk_vector_ty: Can not construct vectortype for elementtype: " ++ pprString el_ty  ++ "\n"
427       ++ err
428
429 mk_natural_ty ::
430   Int -- ^ The minimum bound (> 0)
431   -> Int -- ^ The maximum bound (> minimum bound)
432   -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
433       -- ^ An error message or The typemark created.
434 mk_natural_ty min_bound max_bound = do
435   let ty_id = mkVHDLExtId $ "nat_" ++ (show min_bound) ++ "_to_" ++ (show max_bound)
436   let range = AST.ConstraintRange $ AST.SubTypeRange (AST.PrimLit $ (show min_bound)) (AST.PrimLit $ (show max_bound))
437   let ty_def = AST.SubtypeIn naturalTM (Just range)
438   return (Right $ Just (ty_id, Right ty_def))
439
440 mk_unsigned_ty ::
441   Type.Type -- ^ Haskell type of the unsigned integer
442   -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
443 mk_unsigned_ty ty = do
444   size <- tfp_to_int (sized_word_len_ty ty)
445   let ty_id = mkVHDLExtId $ "unsigned_" ++ show (size - 1)
446   let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (size - 1))]
447   let ty_def = AST.SubtypeIn unsignedTM (Just range)
448   let unsignedshow = mkIntegerShow ty_id
449   modA tsTypeFuns $ Map.insert (OrdType ty, showIdString) (showId, unsignedshow)
450   return (Right $ Just (ty_id, Right ty_def))
451   
452 mk_signed_ty ::
453   Type.Type -- ^ Haskell type of the signed integer
454   -> TypeSession (Either String (Maybe (AST.TypeMark, Either AST.TypeDef AST.SubtypeIn)))
455 mk_signed_ty ty = do
456   size <- tfp_to_int (sized_int_len_ty ty)
457   let ty_id = mkVHDLExtId $ "signed_" ++ show (size - 1)
458   let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (size - 1))]
459   let ty_def = AST.SubtypeIn signedTM (Just range)
460   let signedshow = mkIntegerShow ty_id
461   modA tsTypeFuns $ Map.insert (OrdType ty, showIdString) (showId, signedshow)
462   return (Right $ Just (ty_id, Right ty_def))
463
464 -- Finds the field labels for VHDL type generated for the given Core type,
465 -- which must result in a record type.
466 getFieldLabels :: Type.Type -> TypeSession [AST.VHDLId]
467 getFieldLabels ty = do
468   -- Ensure that the type is generated (but throw away it's VHDLId)
469   let error_msg = "\nVHDLTools.getFieldLabels: Can not get field labels, because: " ++ pprString ty ++ "can not be generated." 
470   vhdl_ty error_msg ty
471   -- Get the types map, lookup and unpack the VHDL TypeDef
472   types <- getA tsTypes
473   -- Assume the type for which we want labels is really translatable
474   Right htype <- mkHType ty
475   case Map.lookup htype types of
476     Just (Just (_, Left (AST.TDR (AST.RecordTypeDef elems)))) -> return $ map (\(AST.ElementDec id _) -> id) elems
477     Just Nothing -> return [] -- The type is empty
478     _ -> error $ "\nVHDL.getFieldLabels: Type not found or not a record type? This should not happen! Type: " ++ (show ty)
479     
480 mktydecl :: (AST.VHDLId, Either AST.TypeDef AST.SubtypeIn) -> AST.PackageDecItem
481 mktydecl (ty_id, Left ty_def) = AST.PDITD $ AST.TypeDec ty_id ty_def
482 mktydecl (ty_id, Right ty_def) = AST.PDISD $ AST.SubtypeDec ty_id ty_def
483
484 mkHType :: Type.Type -> TypeSession (Either String HType)
485 mkHType ty = do
486   -- FIXME: Do we really need to do this here again?
487   let builtin_ty = do -- See if this is a tycon and lookup its name
488         (tycon, args) <- Type.splitTyConApp_maybe ty
489         let name = Name.getOccString (TyCon.tyConName tycon)
490         Map.lookup name builtin_types
491   case builtin_ty of
492     Just typ ->
493       return $ Right $ BuiltinType $ prettyShow typ
494     Nothing ->
495       case Type.splitTyConApp_maybe ty of
496         Just (tycon, args) -> do
497           let name = Name.getOccString (TyCon.tyConName tycon)
498           case name of
499             "TFVec" -> do
500               let el_ty = tfvec_elem ty
501               elem_htype_either <- mkHType el_ty
502               case elem_htype_either of
503                 -- Could create element type
504                 Right elem_htype -> do
505                   len <- tfp_to_int (tfvec_len_ty ty)
506                   return $ Right $ VecType len elem_htype
507                 -- Could not create element type
508                 Left err -> return $ Left $ 
509                   "VHDLTools.mkHType: Can not construct vectortype for elementtype: " ++ pprString el_ty  ++ "\n"
510                   ++ err
511             "SizedWord" -> do
512               len <- tfp_to_int (sized_word_len_ty ty)
513               return $ Right $ SizedWType len
514             "SizedInt" -> do
515               len <- tfp_to_int (sized_word_len_ty ty)
516               return $ Right $ SizedIType len
517             "RangedWord" -> do
518               bound <- tfp_to_int (ranged_word_bound_ty ty)
519               return $ Right $ RangedWType bound
520             otherwise -> do
521               mkTyConHType tycon args
522         Nothing -> return $ Right $ StdType $ OrdType ty
523
524 -- FIXME: Do we really need to do this here again?
525 mkTyConHType :: TyCon.TyCon -> [Type.Type] -> TypeSession (Either String HType)
526 mkTyConHType tycon args =
527   case TyCon.tyConDataCons tycon of
528     -- Not an algebraic type
529     [] -> return $ Left $ "VHDLTools.mkHType: Only custom algebraic types are supported: " ++ pprString tycon ++ "\n"
530     [dc] -> do
531       let arg_tys = DataCon.dataConRepArgTys dc
532       let real_arg_tys = map (CoreSubst.substTy subst) arg_tys
533       elem_htys_either <- mapM mkHType real_arg_tys
534       case Either.partitionEithers elem_htys_either of
535         -- No errors in element types
536         ([], elem_htys) -> do
537           return $ Right $ ADTType (nameToString (TyCon.tyConName tycon)) elem_htys
538         -- There were errors in element types
539         (errors, _) -> return $ Left $
540           "VHDLTools.mkHType: Can not construct type for: " ++ pprString tycon ++ "\n because no type can be construced for some of the arguments.\n"
541           ++ (concat errors)
542     dcs -> return $ Left $ "VHDLTools.mkHType: Only single constructor datatypes supported: " ++ pprString tycon ++ "\n"
543   where
544     tyvars = TyCon.tyConTyVars tycon
545     subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
546
547 -- Is the given type representable at runtime?
548 isReprType :: Type.Type -> TypeSession Bool
549 isReprType ty = do
550   ty_either <- vhdl_ty_either ty
551   return $ case ty_either of
552     Left _ -> False
553     Right _ -> True
554
555
556 tfp_to_int :: Type.Type -> TypeSession Int
557 tfp_to_int ty = do
558   hscenv <- getA tsHscEnv
559   let norm_ty = normalise_tfp_int hscenv ty
560   case Type.splitTyConApp_maybe norm_ty of
561     Just (tycon, args) -> do
562       let name = Name.getOccString (TyCon.tyConName tycon)
563       case name of
564         "Dec" -> do
565           len <- tfp_to_int' ty
566           return len
567         otherwise -> do
568           modA tsTfpInts (Map.insert (OrdType norm_ty) (-1))
569           return $ error ("Callin tfp_to_int on non-dec:" ++ (show ty))
570     Nothing -> return $ error ("Callin tfp_to_int on non-dec:" ++ (show ty))
571
572 tfp_to_int' :: Type.Type -> TypeSession Int
573 tfp_to_int' ty = do
574   lens <- getA tsTfpInts
575   hscenv <- getA tsHscEnv
576   let norm_ty = normalise_tfp_int hscenv ty
577   let existing_len = Map.lookup (OrdType norm_ty) lens
578   case existing_len of
579     Just len -> return len
580     Nothing -> do
581       let new_len = eval_tfp_int hscenv ty
582       modA tsTfpInts (Map.insert (OrdType norm_ty) (new_len))
583       return new_len
584       
585 mkTupleShow :: 
586   [AST.TypeMark] -- ^ type of each tuple element
587   -> AST.TypeMark -- ^ type of the tuple
588   -> AST.SubProgBody
589 mkTupleShow elemTMs tupleTM = AST.SubProgBody showSpec [] [showExpr]
590   where
591     tupPar    = AST.unsafeVHDLBasicId "tup"
592     showSpec  = AST.Function showId [AST.IfaceVarDec tupPar tupleTM] stringTM
593     showExpr  = AST.ReturnSm (Just $
594                   AST.PrimLit "'('" AST.:&: showMiddle AST.:&: AST.PrimLit "')'")
595       where
596         showMiddle = if null elemTMs then
597             AST.PrimLit "''"
598           else
599             foldr1 (\e1 e2 -> e1 AST.:&: AST.PrimLit "','" AST.:&: e2) $
600               map ((genExprFCall showId).
601                     AST.PrimName .
602                     AST.NSelected .
603                     (AST.NSimple tupPar AST.:.:).
604                     tupVHDLSuffix)
605                   (take tupSize recordlabels)
606     recordlabels = map (\c -> mkVHDLBasicId [c]) ['A'..'Z']
607     tupSize = length elemTMs
608
609 mkVectorShow ::
610   AST.TypeMark -- ^ elemtype
611   -> AST.TypeMark -- ^ vectype
612   -> [(String,AST.SubProgBody)]
613 mkVectorShow elemTM vectorTM = 
614   [ (headId, AST.SubProgBody headSpec []                   [headExpr])
615   , (tailId, AST.SubProgBody tailSpec [AST.SPVD tailVar]   [tailExpr, tailRet])
616   , (showIdString, AST.SubProgBody showSpec [AST.SPSB doShowDef] [showRet])
617   ]
618   where
619     vecPar  = AST.unsafeVHDLBasicId "vec"
620     resId   = AST.unsafeVHDLBasicId "res"
621     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
622     -- return vec(0);
623     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
624                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
625     vecSlice init last =  AST.PrimName (AST.NSlice 
626                                       (AST.SliceName 
627                                             (AST.NSimple vecPar) 
628                                             (AST.ToRange init last)))
629     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
630        -- variable res : fsvec_x (0 to vec'length-2); 
631     tailVar = 
632          AST.VarDec resId 
633                 (AST.SubtypeIn vectorTM
634                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
635                    [AST.ToRange (AST.PrimLit "0")
636                             (AST.PrimName (AST.NAttribute $ 
637                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
638                                 (AST.PrimLit "2"))   ]))
639                 Nothing       
640        -- res AST.:= vec(1 to vec'length-1)
641     tailExpr = AST.NSimple resId AST.:= (vecSlice 
642                                (AST.PrimLit "1") 
643                                (AST.PrimName (AST.NAttribute $ 
644                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
645                                                              AST.:-: AST.PrimLit "1"))
646     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
647     showSpec  = AST.Function showId [AST.IfaceVarDec vecPar vectorTM] stringTM
648     doShowId  = AST.unsafeVHDLExtId "doshow"
649     doShowDef = AST.SubProgBody doShowSpec [] [doShowRet]
650       where doShowSpec = AST.Function doShowId [AST.IfaceVarDec vecPar vectorTM] 
651                                            stringTM
652             -- case vec'len is
653             --  when  0 => return "";
654             --  when  1 => return head(vec);
655             --  when others => return show(head(vec)) & ',' &
656             --                        doshow (tail(vec));
657             -- end case;
658             doShowRet = 
659               AST.CaseSm (AST.PrimName (AST.NAttribute $ 
660                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
661               [AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit "0"] 
662                          [AST.ReturnSm (Just $ AST.PrimLit "\"\"")],
663                AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit "1"] 
664                          [AST.ReturnSm (Just $ 
665                           genExprFCall showId 
666                                (genExprFCall (mkVHDLExtId headId) (AST.PrimName $ AST.NSimple vecPar)) )],
667                AST.CaseSmAlt [AST.Others] 
668                          [AST.ReturnSm (Just $ 
669                            genExprFCall showId 
670                              (genExprFCall (mkVHDLExtId headId) (AST.PrimName $ AST.NSimple vecPar)) AST.:&:
671                            AST.PrimLit "','" AST.:&:
672                            genExprFCall doShowId 
673                              (genExprFCall (mkVHDLExtId tailId) (AST.PrimName $ AST.NSimple vecPar)) ) ]]
674     -- return '<' & doshow(vec) & '>';
675     showRet =  AST.ReturnSm (Just $ AST.PrimLit "'<'" AST.:&:
676                                genExprFCall doShowId (AST.PrimName $ AST.NSimple vecPar) AST.:&:
677                                AST.PrimLit "'>'" )
678
679 mkIntegerShow ::
680   AST.TypeMark -- ^ The specific signed
681   -> AST.SubProgBody
682 mkIntegerShow signedTM = AST.SubProgBody showSpec [] [showExpr]
683   where
684     signedPar = AST.unsafeVHDLBasicId "sint"
685     showSpec = AST.Function showId [AST.IfaceVarDec signedPar signedTM] stringTM
686     showExpr = AST.ReturnSm (Just $
687                 AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerId) 
688                   (AST.NIndexed $ AST.IndexedName (AST.NSimple imageId) [signToInt]) Nothing )
689       where
690         signToInt = genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple $ signedPar)
691
692 mkBuiltInShow :: [AST.SubProgBody]
693 mkBuiltInShow = [ AST.SubProgBody showBitSpec [] [showBitExpr]
694                 , AST.SubProgBody showBoolSpec [] [showBoolExpr]
695                 ]
696   where
697     bitPar    = AST.unsafeVHDLBasicId "s"
698     boolPar    = AST.unsafeVHDLBasicId "b"
699     showBitSpec = AST.Function showId [AST.IfaceVarDec bitPar std_logicTM] stringTM
700     -- if s = '1' then return "'1'" else return "'0'"
701     showBitExpr = AST.IfSm (AST.PrimName (AST.NSimple bitPar) AST.:=: AST.PrimLit "'1'")
702                         [AST.ReturnSm (Just $ AST.PrimLit "\"High\"")]
703                         []
704                         (Just $ AST.Else [AST.ReturnSm (Just $ AST.PrimLit "\"Low\"")])
705     showBoolSpec = AST.Function showId [AST.IfaceVarDec boolPar booleanTM] stringTM
706     -- if b then return "True" else return "False"
707     showBoolExpr = AST.IfSm (AST.PrimName (AST.NSimple boolPar))
708                         [AST.ReturnSm (Just $ AST.PrimLit "\"True\"")]
709                         []
710                         (Just $ AST.Else [AST.ReturnSm (Just $ AST.PrimLit "\"False\"")])
711   
712 genExprFCall :: AST.VHDLId -> AST.Expr -> AST.Expr
713 genExprFCall fName args = 
714    AST.PrimFCall $ AST.FCall (AST.NSimple fName)  $
715              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) [args] 
716
717 genExprPCall2 :: AST.VHDLId -> AST.Expr -> AST.Expr -> AST.SeqSm             
718 genExprPCall2 entid arg1 arg2 =
719         AST.ProcCall (AST.NSimple entid) $
720          map (\exp -> Nothing AST.:=>: AST.ADExpr exp) [arg1,arg2]
721
722 mkSigDec :: CoreSyn.CoreBndr -> TranslatorSession (Maybe AST.SigDec)
723 mkSigDec bndr = do
724   let error_msg = "\nVHDL.mkSigDec: Can not make signal declaration for type: \n" ++ pprString bndr 
725   type_mark_maybe <- MonadState.lift tsType $ vhdl_ty error_msg (Var.varType bndr)
726   case type_mark_maybe of
727     Just type_mark -> return $ Just (AST.SigDec (varToVHDLId bndr) type_mark Nothing)
728     Nothing -> return Nothing
729
730 -- | Does the given thing have a non-empty type?
731 hasNonEmptyType :: (TypedThing t, Outputable.Outputable t) => 
732   t -> TranslatorSession Bool
733 hasNonEmptyType thing = MonadState.lift tsType $ isJustM (vhdl_ty "hasNonEmptyType: Non representable type?" thing)