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