fde81d06dae32e7fbc0b381f16f24e0cb685c602
[matthijs/master-project/cλash.git] / clash / 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.Char as Char
9 import qualified Data.Map as Map
10 import qualified Control.Monad as Monad
11 import qualified Data.Accessor.Monad.Trans.State as MonadState
12
13 -- VHDL Imports
14 import qualified Language.VHDL.AST as AST
15
16 -- GHC API
17 import qualified CoreSyn
18 import qualified Name
19 import qualified OccName
20 import qualified Var
21 import qualified Id
22 import qualified TyCon
23 import qualified Type
24 import qualified DataCon
25 import qualified CoreSubst
26 import qualified Outputable
27
28 -- Local imports
29 import CLasH.VHDL.VHDLTypes
30 import CLasH.Translator.TranslatorTypes
31 import CLasH.Utils.Core.CoreTools
32 import CLasH.Utils
33 import CLasH.Utils.Pretty
34 import CLasH.VHDL.Constants
35
36 -----------------------------------------------------------------------------
37 -- Functions to generate concurrent statements
38 -----------------------------------------------------------------------------
39
40 -- Create an unconditional assignment statement
41 mkUncondAssign ::
42   Either CoreSyn.CoreBndr AST.VHDLName -- ^ The signal to assign to
43   -> AST.Expr -- ^ The expression to assign
44   -> AST.ConcSm -- ^ The resulting concurrent statement
45 mkUncondAssign dst expr = mkAssign dst Nothing expr
46
47 -- Create a conditional assignment statement
48 mkCondAssign ::
49   Either CoreSyn.CoreBndr AST.VHDLName -- ^ The signal to assign to
50   -> AST.Expr -- ^ The condition
51   -> AST.Expr -- ^ The value when true
52   -> AST.Expr -- ^ The value when false
53   -> AST.ConcSm -- ^ The resulting concurrent statement
54 mkCondAssign dst cond true false = mkAssign dst (Just (cond, true)) false
55
56 -- Create a conditional or unconditional assignment statement
57 mkAssign ::
58   Either CoreSyn.CoreBndr AST.VHDLName -- ^ The signal to assign to
59   -> Maybe (AST.Expr , AST.Expr) -- ^ Optionally, the condition to test for
60                                  -- and the value to assign when true.
61   -> AST.Expr -- ^ The value to assign when false or no condition
62   -> AST.ConcSm -- ^ The resulting concurrent statement
63 mkAssign dst cond false_expr =
64   let
65     -- I'm not 100% how this assignment AST works, but this gets us what we
66     -- want...
67     whenelse = case cond of
68       Just (cond_expr, true_expr) -> 
69         let 
70           true_wform = AST.Wform [AST.WformElem true_expr Nothing]
71         in
72           [AST.WhenElse true_wform cond_expr]
73       Nothing -> []
74     false_wform = AST.Wform [AST.WformElem false_expr Nothing]
75     dst_name  = case dst of
76       Left bndr -> AST.NSimple (varToVHDLId bndr)
77       Right name -> name
78     assign    = dst_name AST.:<==: (AST.ConWforms whenelse false_wform Nothing)
79   in
80     AST.CSSASm assign
81
82 mkAltsAssign ::
83   Either CoreSyn.CoreBndr AST.VHDLName            -- ^ The signal to assign to
84   -> [AST.Expr]       -- ^ The conditions
85   -> [AST.Expr]       -- ^ The expressions
86   -> AST.ConcSm   -- ^ The Alt assigns
87 mkAltsAssign dst conds exprs
88         | (length conds) /= ((length exprs) - 1) = error "\nVHDLTools.mkAltsAssign: conditions expression mismatch"
89         | otherwise =
90   let
91     whenelses   = zipWith mkWhenElse conds exprs
92     false_wform = AST.Wform [AST.WformElem (last exprs) Nothing]
93     dst_name  = case dst of
94       Left bndr -> AST.NSimple (varToVHDLId bndr)
95       Right name -> name
96     assign    = dst_name AST.:<==: (AST.ConWforms whenelses false_wform Nothing)
97   in
98     AST.CSSASm assign
99   where
100     mkWhenElse :: AST.Expr -> AST.Expr -> AST.WhenElse
101     mkWhenElse cond true_expr =
102       let
103         true_wform = AST.Wform [AST.WformElem true_expr Nothing]
104       in
105         AST.WhenElse true_wform cond
106
107 mkAssocElems :: 
108   [AST.Expr]                    -- ^ The argument that are applied to function
109   -> AST.VHDLName               -- ^ The binder in which to store the result
110   -> Entity                     -- ^ The entity to map against.
111   -> [AST.AssocElem]            -- ^ The resulting port maps
112 mkAssocElems args res entity =
113     arg_maps ++ (Maybe.maybeToList res_map_maybe)
114   where
115     arg_ports = ent_args entity
116     res_port_maybe = ent_res entity
117     -- Create an expression of res to map against the output port
118     res_expr = vhdlNameToVHDLExpr res
119     -- Map each of the input ports
120     arg_maps = zipWith mkAssocElem (map fst arg_ports) args
121     -- Map the output port, if present
122     res_map_maybe = fmap (\port -> mkAssocElem (fst port) res_expr) res_port_maybe
123
124 -- | Create an VHDL port -> signal association
125 mkAssocElem :: AST.VHDLId -> AST.Expr -> AST.AssocElem
126 mkAssocElem port signal = Just port AST.:=>: (AST.ADExpr signal) 
127
128 -- | Create an aggregate signal
129 mkAggregateSignal :: [AST.Expr] -> AST.Expr
130 mkAggregateSignal x = AST.Aggregate (map (\z -> AST.ElemAssoc Nothing z) x)
131
132 mkComponentInst ::
133   String -- ^ The portmap label
134   -> AST.VHDLId -- ^ The entity name
135   -> [AST.AssocElem] -- ^ The port assignments
136   -> AST.ConcSm
137 mkComponentInst label entity_id portassigns = AST.CSISm compins
138   where
139     -- We always have a clock port, so no need to map it anywhere but here
140     clk_port = mkAssocElem clockId (idToVHDLExpr clockId)
141     resetn_port = mkAssocElem resetId (idToVHDLExpr resetId)
142     compins = AST.CompInsSm (mkVHDLExtId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect (portassigns ++ [clk_port,resetn_port]))
143
144 -----------------------------------------------------------------------------
145 -- Functions to generate VHDL Exprs
146 -----------------------------------------------------------------------------
147
148 varToVHDLExpr :: Var.Var -> TypeSession AST.Expr
149 varToVHDLExpr var =
150   case Id.isDataConWorkId_maybe var of
151     -- This is a dataconstructor.
152     Just dc -> dataconToVHDLExpr dc
153     -- Not a datacon, just another signal.
154     Nothing -> return $ AST.PrimName $ AST.NSimple $ varToVHDLId var
155
156 -- Turn a VHDLName into an AST expression
157 vhdlNameToVHDLExpr = AST.PrimName
158
159 -- Turn a VHDL Id into an AST expression
160 idToVHDLExpr = vhdlNameToVHDLExpr . AST.NSimple
161
162 -- Turn a Core expression into an AST expression
163 exprToVHDLExpr core = varToVHDLExpr (exprToVar core)
164
165 -- Turn a String into a VHDL expr containing an id
166 stringToVHDLExpr :: String -> AST.Expr
167 stringToVHDLExpr = idToVHDLExpr . mkVHDLExtId 
168
169
170 -- Turn a alternative constructor into an AST expression. For
171 -- dataconstructors, this is only the constructor itself, not any arguments it
172 -- has. Should not be called with a DEFAULT constructor.
173 altconToVHDLExpr :: CoreSyn.AltCon -> TypeSession AST.Expr
174 altconToVHDLExpr (CoreSyn.DataAlt dc) = dataconToVHDLExpr dc
175
176 altconToVHDLExpr (CoreSyn.LitAlt _) = error "\nVHDL.conToVHDLExpr: Literals not support in case alternatives yet"
177 altconToVHDLExpr CoreSyn.DEFAULT = error "\nVHDL.conToVHDLExpr: DEFAULT alternative should not occur here!"
178
179 -- Turn a datacon (without arguments!) into a VHDL expression.
180 dataconToVHDLExpr :: DataCon.DataCon -> TypeSession AST.Expr
181 dataconToVHDLExpr dc = do
182   typemap <- MonadState.get tsTypes
183   htype_either <- mkHTypeEither (DataCon.dataConRepType dc)
184   case htype_either of
185     -- No errors
186     Right htype -> do
187       let dcname = DataCon.dataConName dc
188       case htype of
189         (BuiltinType "Bit") -> return $ AST.PrimLit $ case Name.getOccString dcname of "High" -> "'1'"; "Low" -> "'0'"
190         (BuiltinType "Bool") -> return $ AST.PrimLit $ case Name.getOccString dcname of "True" -> "true"; "False" -> "false"
191         otherwise -> do
192           let existing_ty = Monad.liftM (fmap fst) $ Map.lookup htype typemap
193           case existing_ty of
194             Just ty -> do
195               let lit    = idToVHDLExpr $ mkVHDLExtId $ Name.getOccString dcname
196               return lit
197             Nothing -> error $ "\nVHDLTools.dataconToVHDLExpr: Trying to make value for non-representable DataCon: " ++ pprString dc
198     -- Error when constructing htype
199     Left err -> error err
200
201 -----------------------------------------------------------------------------
202 -- Functions dealing with names, variables and ids
203 -----------------------------------------------------------------------------
204
205 -- Creates a VHDL Id from a binder
206 varToVHDLId ::
207   CoreSyn.CoreBndr
208   -> AST.VHDLId
209 varToVHDLId var = mkVHDLExtId (varToString var ++ varToStringUniq var ++ show (lowers $ varToStringUniq var))
210   where
211     lowers :: String -> Int
212     lowers xs = length [x | x <- xs, Char.isLower x]
213
214 -- Creates a VHDL Name from a binder
215 varToVHDLName ::
216   CoreSyn.CoreBndr
217   -> AST.VHDLName
218 varToVHDLName = AST.NSimple . varToVHDLId
219
220 -- Extracts the binder name as a String
221 varToString ::
222   CoreSyn.CoreBndr
223   -> String
224 varToString = OccName.occNameString . Name.nameOccName . Var.varName
225
226 -- Get the string version a Var's unique
227 varToStringUniq :: Var.Var -> String
228 varToStringUniq = show . Var.varUnique
229
230 -- Extracts the string version of the name
231 nameToString :: Name.Name -> String
232 nameToString = OccName.occNameString . Name.nameOccName
233
234 -- Shortcut for Basic VHDL Ids.
235 -- Can only contain alphanumerics and underscores. The supplied string must be
236 -- a valid basic id, otherwise an error value is returned. This function is
237 -- not meant to be passed identifiers from a source file, use mkVHDLExtId for
238 -- that.
239 mkVHDLBasicId :: String -> AST.VHDLId
240 mkVHDLBasicId s = 
241   AST.unsafeVHDLBasicId $ (strip_multiscore . strip_leading . strip_invalid) s
242   where
243     -- Strip invalid characters.
244     strip_invalid = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.")
245     -- Strip leading numbers and underscores
246     strip_leading = dropWhile (`elem` ['0'..'9'] ++ "_")
247     -- Strip multiple adjacent underscores
248     strip_multiscore = concatMap (\cs -> 
249         case cs of 
250           ('_':_) -> "_"
251           _ -> cs
252       ) . List.group
253
254 -- Shortcut for Extended VHDL Id's. These Id's can contain a lot more
255 -- different characters than basic ids, but can never be used to refer to
256 -- basic ids.
257 -- Use extended Ids for any values that are taken from the source file.
258 mkVHDLExtId :: String -> AST.VHDLId
259 mkVHDLExtId s = 
260   AST.unsafeVHDLExtId $ strip_invalid s
261   where 
262     -- Allowed characters, taken from ForSyde's mkVHDLExtId
263     allowed = ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ " \"#&'()*+,./:;<=>_|!$%@?[]^`{}~-"
264     strip_invalid = filter (`elem` allowed)
265
266 -- Create a record field selector that selects the given label from the record
267 -- stored in the given binder.
268 mkSelectedName :: AST.VHDLName -> AST.VHDLId -> AST.VHDLName
269 mkSelectedName name label =
270    AST.NSelected $ name AST.:.: (AST.SSimple label) 
271
272 -- Create an indexed name that selects a given element from a vector.
273 mkIndexedName :: AST.VHDLName -> AST.Expr -> AST.VHDLName
274 -- Special case for already indexed names. Just add an index
275 mkIndexedName (AST.NIndexed (AST.IndexedName name indexes)) index =
276  AST.NIndexed (AST.IndexedName name (indexes++[index]))
277 -- General case for other names
278 mkIndexedName name index = AST.NIndexed (AST.IndexedName name [index])
279
280 -----------------------------------------------------------------------------
281 -- Functions dealing with VHDL types
282 -----------------------------------------------------------------------------
283 builtin_types :: TypeMap
284 builtin_types = 
285   Map.fromList [
286     (BuiltinType "Bit", Just (std_logicTM, Nothing)),
287     (BuiltinType "Bool", Just (booleanTM, Nothing)) -- TysWiredIn.boolTy
288   ]
289
290 -- Is the given type representable at runtime?
291 isReprType :: Type.Type -> TypeSession Bool
292 isReprType ty = do
293   ty_either <- mkHTypeEither ty
294   return $ case ty_either of
295     Left _ -> False
296     Right _ -> True
297
298 -- | Turn a Core type into a HType, returning an error using the given
299 -- error string if the type was not representable.
300 mkHType :: (TypedThing t, Outputable.Outputable t) => 
301   String -> t -> TypeSession HType
302 mkHType msg ty = do
303   htype_either <- mkHTypeEither ty
304   case htype_either of
305     Right htype -> return htype
306     Left err -> error $ msg ++ err  
307
308 -- | Turn a Core type into a HType. Returns either an error message if
309 -- the type was not representable, or the HType generated.
310 mkHTypeEither :: (TypedThing t, Outputable.Outputable t) => 
311   t -> TypeSession (Either String HType)
312 mkHTypeEither tything =
313   case getType tything of
314     Nothing -> return $ Left $ "\nVHDLTools.mkHTypeEither: Typed thing without a type: " ++ pprString tything
315     Just ty -> mkHTypeEither' ty
316
317 mkHTypeEither' :: Type.Type -> TypeSession (Either String HType)
318 mkHTypeEither' ty | ty_has_free_tyvars ty = return $ Left $ "\nVHDLTools.mkHTypeEither': Cannot create type: type has free type variables: " ++ pprString ty
319                   | isStateType ty = return $ Right StateType
320                   | otherwise =
321   case Type.splitTyConApp_maybe ty of
322     Just (tycon, args) -> do
323       typemap <- MonadState.get tsTypes
324       let name = Name.getOccString (TyCon.tyConName tycon)
325       let builtinTyMaybe = Map.lookup (BuiltinType name) typemap  
326       case builtinTyMaybe of
327         (Just x) -> return $ Right $ BuiltinType name
328         Nothing ->
329           case name of
330                 "Vector" -> do
331                   let el_ty = tfvec_elem ty
332                   elem_htype_either <- mkHTypeEither el_ty
333                   case elem_htype_either of
334                     -- Could create element type
335                     Right elem_htype -> do
336                       len <- tfp_to_int (tfvec_len_ty ty)
337                       return $ Right $ VecType len elem_htype
338                     -- Could not create element type
339                     Left err -> return $ Left $ 
340                       "\nVHDLTools.mkHTypeEither': Can not construct vectortype for elementtype: " ++ pprString el_ty ++ err
341                 "Unsigned" -> do
342                   len <- tfp_to_int (sized_word_len_ty ty)
343                   return $ Right $ SizedWType len
344                 "Signed" -> do
345                   len <- tfp_to_int (sized_word_len_ty ty)
346                   return $ Right $ SizedIType len
347                 "Index" -> do
348                   bound <- tfp_to_int (ranged_word_bound_ty ty)
349                   -- Upperbound is exclusive, hence the -1
350                   return $ Right $ RangedWType (bound - 1)
351                 otherwise ->
352                   mkTyConHType tycon args
353     Nothing -> return $ Left $ "\nVHDLTools.mkHTypeEither': Do not know what to do with type: " ++ pprString ty
354
355 mkTyConHType :: TyCon.TyCon -> [Type.Type] -> TypeSession (Either String HType)
356 mkTyConHType tycon args =
357   case TyCon.tyConDataCons tycon of
358     -- Not an algebraic type
359     [] -> return $ Left $ "VHDLTools.mkTyConHType: Only custom algebraic types are supported: " ++ pprString tycon
360     dcs -> do
361       let arg_tyss = map DataCon.dataConRepArgTys dcs
362       let enum_ty = EnumType name (map (nameToString . DataCon.dataConName) dcs)
363       case (concat arg_tyss) of
364         -- No arguments, this is just an enumeration type
365         [] -> return (Right enum_ty)
366         -- At least one argument, this becomes an aggregate type
367         _ -> do
368           -- Resolve any type arguments to this type
369           let real_arg_tyss = map (map (CoreSubst.substTy subst)) arg_tyss
370           -- Remove any state type fields
371           let real_arg_tyss_nostate = map (filter (\x -> not (isStateType x))) real_arg_tyss
372           elem_htyss_either <- mapM (mapM mkHTypeEither) real_arg_tyss_nostate
373           let (errors, elem_htyss) = unzip (map Either.partitionEithers elem_htyss_either)
374           case (all null errors) of
375             True -> case (dcs, concat elem_htyss) of
376                 -- A single constructor with a single (non-state) field?
377                 ([dc], [elem_hty]) -> return $ Right elem_hty
378                 -- If we get here, then all of the argument types were state
379                 -- types (we check for enumeration types at the top). Not
380                 -- sure how to handle this, so error out for now.
381                 (_, []) -> error $ "ADT with only State elements (or something like that?) Dunno how to handle this yet. Tycon: " ++ pprString tycon ++ " Arguments: " ++ pprString args
382                 -- A full ADT (with multiple fields and one or multiple
383                 -- constructors).
384                 (_, elem_htys) -> do
385                   let (_, fieldss) = List.mapAccumL (List.mapAccumL label_field) labels elem_htyss
386                   -- Only put in an enumeration as part of the aggregation
387                   -- when there are multiple datacons
388                   let enum_ty_part = case dcs of
389                                       [dc] -> Nothing
390                                       _ -> Just ("constructor", enum_ty)
391                   -- Create the AggrType HType
392                   return $ Right $ AggrType name enum_ty_part fieldss
393                 -- There were errors in element types
394             False -> return $ Left $
395               "\nVHDLTools.mkTyConHType: Can not construct type for: " ++ pprString tycon ++ "\n because no type can be construced for some of the arguments.\n" 
396               ++ (concat $ concat errors)
397   where
398     name = (nameToString (TyCon.tyConName tycon))
399     tyvars = TyCon.tyConTyVars tycon
400     subst = CoreSubst.extendTvSubstList CoreSubst.emptySubst (zip tyvars args)
401     -- Label a field by taking the first available label and returning
402     -- the rest.
403     label_field :: [String] -> HType -> ([String], (String, HType))
404     label_field (l:ls) htype = (ls, (l, htype))
405     labels = map (:[]) ['A'..'Z']
406
407 vhdlTy :: (TypedThing t, Outputable.Outputable t) => 
408   String -> t -> TypeSession (Maybe AST.TypeMark)
409 vhdlTy msg ty = do
410   htype <- mkHType msg ty
411   vhdlTyMaybe htype
412
413 -- | Translate a Haskell type to a VHDL type, generating a new type if needed.
414 -- Returns an error value, using the given message, when no type could be
415 -- created. Returns Nothing when the type is valid, but empty.
416 vhdlTyMaybe :: HType -> TypeSession (Maybe AST.TypeMark)
417 vhdlTyMaybe htype = do
418   typemap <- MonadState.get tsTypes
419   -- If not a builtin type, try the custom types
420   let existing_ty = Map.lookup htype typemap
421   case existing_ty of
422     -- Found a type, return it
423     Just (Just (t, _)) -> return $ Just t
424     Just (Nothing) -> return Nothing
425     -- No type yet, try to construct it
426     Nothing -> do
427       newty <- (construct_vhdl_ty htype)
428       MonadState.modify tsTypes (Map.insert htype newty)
429       case newty of
430         Just (ty_id, ty_def) -> do
431           MonadState.modify tsTypeDecls (\typedefs -> typedefs ++ [mktydecl (ty_id, ty_def)])
432           return $ Just ty_id
433         Nothing -> return Nothing
434
435 -- Construct a new VHDL type for the given Haskell type. Returns an error
436 -- message or the resulting typemark and typedef.
437 construct_vhdl_ty :: HType -> TypeSession TypeMapRec
438 -- State types don't generate VHDL
439 construct_vhdl_ty htype =
440     case htype of
441       StateType -> return  Nothing
442       (SizedWType w) -> mkUnsignedTy w
443       (SizedIType i) -> mkSignedTy i
444       (RangedWType u) -> mkNaturalTy 0 u
445       (VecType n e) -> mkVectorTy (VecType n e)
446       -- Create a custom type from this tycon
447       otherwise -> mkTyconTy htype
448
449 -- | Create VHDL type for a custom tycon
450 mkTyconTy :: HType -> TypeSession TypeMapRec
451 mkTyconTy htype =
452   case htype of
453     (AggrType name enum_field_maybe fieldss) -> do
454       let (labelss, elem_htypess) = unzip (map unzip fieldss)
455       elemTyMaybess <- mapM (mapM vhdlTyMaybe) elem_htypess
456       let elem_tyss = map Maybe.catMaybes elemTyMaybess
457       case concat elem_tyss of
458         [] -> -- No non-empty fields
459           return Nothing
460         _ -> do
461           let reclabelss = map (map mkVHDLBasicId) labelss
462           let elemss = zipWith (zipWith AST.ElementDec) reclabelss elem_tyss
463           let elem_names = concatMap (concatMap prettyShow) elem_tyss
464           let ty_id = mkVHDLExtId $ name ++ elem_names
465           -- Find out if we need to add an extra field at the start of
466           -- the record type containing the constructor (only needed
467           -- when there's more than one constructor).
468           enum_ty_maybe <- case enum_field_maybe of
469             Nothing -> return Nothing
470             Just (_, enum_htype) -> do
471               enum_ty_maybe' <- vhdlTyMaybe enum_htype
472               case enum_ty_maybe' of
473                 Nothing -> error $ "Couldn't translate enumeration type part of AggrType: " ++ show htype
474                 -- Note that the first Just means the type is
475                 -- translateable, while the second Just means that there
476                 -- is a enum_ty at all (e.g., there's multiple
477                 -- constructors).
478                 Just enum_ty -> return $ Just enum_ty
479           -- Create an record field declaration for the first
480           -- constructor field, if needed.
481           enum_dec_maybe <- case enum_field_maybe of
482             Nothing -> return $ Nothing
483             Just (enum_name, enum_htype) -> do
484               enum_vhdl_ty_maybe <- vhdlTyMaybe  enum_htype
485               let enum_vhdl_ty = Maybe.fromMaybe (error $ "\nVHDLTools.mkTyconTy: Enumeration field should not have empty type: " ++ show enum_htype) enum_vhdl_ty_maybe
486               return $ Just $ AST.ElementDec (mkVHDLBasicId enum_name) enum_vhdl_ty
487           -- Turn the maybe into a list, so we can prepend it.
488           let enum_decs = Maybe.maybeToList enum_dec_maybe
489           let enum_tys = Maybe.maybeToList enum_ty_maybe
490           let ty_def = AST.TDR $ AST.RecordTypeDef (enum_decs ++ concat elemss)
491           let aggrshow = case enum_field_maybe of 
492                           Nothing -> mkTupleShow (enum_tys ++ concat elem_tyss) ty_id
493                           Just (conLbl, EnumType tycon dcs) -> mkAdtShow conLbl dcs (map (map fst) fieldss) ty_id
494           MonadState.modify tsTypeFuns $ Map.insert (htype, showIdString) (showId, aggrshow)
495           return $ Just (ty_id, Just $ Left ty_def)
496     (EnumType tycon dcs) -> do
497       let ty_id = mkVHDLExtId tycon
498       let possibilaties = case (length dcs) of 1 -> 1; x -> (x-1)
499       let bitsize = floor (logBase 2 (fromInteger (toInteger possibilaties)))
500       let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.DownRange (AST.PrimLit $ show bitsize) (AST.PrimLit "0")]
501       let ty_def = AST.SubtypeIn unsignedTM (Just range)
502       let enumShow = mkEnumShow dcs ty_id
503       MonadState.modify tsTypeFuns $ Map.insert (htype, showIdString) (showId, enumShow)
504       return $ Just (ty_id, Just $ Right ty_def)
505     otherwise -> error $ "\nVHDLTools.mkTyconTy: Called for HType that is neiter a AggrType or EnumType: " ++ show htype
506
507 -- | Create a VHDL vector type
508 mkVectorTy ::
509   HType -- ^ The Haskell type of the Vector
510   -> TypeSession TypeMapRec
511       -- ^ An error message or The typemark created.
512
513 mkVectorTy (VecType len elHType) = do
514   typesMap <- MonadState.get tsTypes
515   elTyTmMaybe <- vhdlTyMaybe elHType
516   case elTyTmMaybe of
517     (Just elTyTm) -> do
518       let ty_id = mkVHDLExtId $ "vector-"++ (AST.fromVHDLId elTyTm) ++ "-0_to_" ++ (show len)
519       let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len - 1))]
520       let existing_uvec_ty = fmap (fmap fst) $ Map.lookup (UVecType elHType) typesMap
521       case existing_uvec_ty of
522         Just (Just t) -> do
523           let ty_def = AST.SubtypeIn t (Just range)
524           return (Just (ty_id, Just $ Right ty_def))
525         Nothing -> do
526           let vec_id  = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elTyTm)
527           let vec_def = AST.TDA $ AST.UnconsArrayDef [tfvec_indexTM] elTyTm
528           MonadState.modify tsTypes (Map.insert (UVecType elHType) (Just (vec_id, (Just $ Left vec_def))))
529           MonadState.modify tsTypeDecls (\typedefs -> typedefs ++ [mktydecl (vec_id, (Just $ Left vec_def))])
530           let vecShowFuns = mkVectorShow elTyTm vec_id
531           mapM_ (\(id, subprog) -> MonadState.modify tsTypeFuns $ Map.insert (UVecType elHType, id) ((mkVHDLExtId id), subprog)) vecShowFuns
532           let ty_def = AST.SubtypeIn vec_id (Just range)
533           return (Just (ty_id, Just $ Right ty_def))
534     -- Vector of empty elements becomes empty itself.
535     Nothing -> return Nothing
536 mkVectorTy htype = error $ "\nVHDLTools.mkVectorTy: Called for HType that is not a VecType: " ++ show htype
537
538 mkNaturalTy ::
539   Int -- ^ The minimum bound (> 0)
540   -> Int -- ^ The maximum bound (> minimum bound)
541   -> TypeSession TypeMapRec
542       -- ^ An error message or The typemark created.
543 mkNaturalTy min_bound max_bound = do
544   let bitsize = floor (logBase 2 (fromInteger (toInteger max_bound)))
545   let ty_id = mkVHDLExtId $ "natural_" ++ (show min_bound) ++ "_to_" ++ (show max_bound)
546   let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit $ show min_bound) (AST.PrimLit $ show bitsize)]
547   let ty_def = AST.SubtypeIn unsignedTM (Just range)
548   return (Just (ty_id, Just $ Right ty_def))
549
550 mkUnsignedTy ::
551   Int -- ^ Haskell type of the unsigned integer
552   -> TypeSession TypeMapRec
553 mkUnsignedTy size = do
554   let ty_id = mkVHDLExtId $ "unsigned_" ++ show (size - 1)
555   let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (size - 1))]
556   let ty_def = AST.SubtypeIn unsignedTM (Just range)
557   return (Just (ty_id, Just $ Right ty_def))
558   
559 mkSignedTy ::
560   Int -- ^ Haskell type of the signed integer
561   -> TypeSession TypeMapRec
562 mkSignedTy size = do
563   let ty_id = mkVHDLExtId $ "signed_" ++ show (size - 1)
564   let range = AST.ConstraintIndex $ AST.IndexConstraint [AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (size - 1))]
565   let ty_def = AST.SubtypeIn signedTM (Just range)
566   return (Just (ty_id, Just $ Right ty_def))
567
568 -- Finds the field labels and types for aggregation HType. Returns an
569 -- error on other types.
570 getFields ::
571   HType                -- ^ The HType to get fields for
572   -> Int               -- ^ The constructor to get fields for (e.g., 0
573                        --   for the first constructor, etc.)
574   -> [(String, HType)] -- ^ A list of fields, with their name and type
575 getFields htype dc_i = case htype of
576   (AggrType name _ fieldss) 
577     | dc_i >= 0 && dc_i < length fieldss -> fieldss!!dc_i
578     | otherwise -> error $ "VHDLTool.getFields: Invalid constructor index: " ++ (show dc_i) ++ ". No such constructor in HType: " ++ (show htype)
579   _ -> error $ "VHDLTool.getFields: Can't get fields from non-aggregate HType: " ++ show htype
580
581 -- Finds the field labels for an aggregation type, as VHDLIds.
582 getFieldLabels ::
583   HType                -- ^ The HType to get field labels for
584   -> Int               -- ^ The constructor to get fields for (e.g., 0
585                        --   for the first constructor, etc.)
586   -> [AST.VHDLId]      -- ^ The labels
587 getFieldLabels htype dc_i = ((map mkVHDLBasicId) . (map fst)) (getFields htype dc_i)
588
589 -- Finds the field label for the constructor field, if any.
590 getConstructorFieldLabel ::
591   HType
592   -> Maybe AST.VHDLId
593 getConstructorFieldLabel (AggrType _ (Just con) _) =
594         Just $ mkVHDLBasicId (fst con)
595 getConstructorFieldLabel (AggrType _ Nothing _) =
596         Nothing
597 getConstructorFieldLabel htype =
598         error $ "Can't get constructor field label from non-aggregate HType: " ++ show htype
599
600
601 getConstructorIndex ::
602   HType ->
603   String ->
604   Int
605 getConstructorIndex (EnumType etype cons) dc = case List.elemIndex dc cons of
606   Just (index) -> index
607   Nothing -> error $ "VHDLTools.getConstructor: constructor: " ++ show dc ++ " is not part of type: " ++ show etype ++ ", which only has constructors: " ++ show cons
608 getConstructorIndex htype _ = error $ "Can't get constructor index for non-Enum type: " ++ show htype
609
610
611 mktydecl :: (AST.VHDLId, Maybe (Either AST.TypeDef AST.SubtypeIn)) -> Maybe AST.PackageDecItem
612 mytydecl (_, Nothing) = Nothing
613 mktydecl (ty_id, Just (Left ty_def)) = Just $ AST.PDITD $ AST.TypeDec ty_id ty_def
614 mktydecl (ty_id, Just (Right ty_def)) = Just $ AST.PDISD $ AST.SubtypeDec ty_id ty_def
615
616 mkTupleShow :: 
617   [AST.TypeMark] -- ^ type of each tuple element
618   -> AST.TypeMark -- ^ type of the tuple
619   -> AST.SubProgBody
620 mkTupleShow elemTMs tupleTM = AST.SubProgBody showSpec [] [showExpr]
621   where
622     tupPar    = AST.unsafeVHDLBasicId "tup"
623     showSpec  = AST.Function showId [AST.IfaceVarDec tupPar tupleTM] stringTM
624     showExpr  = AST.ReturnSm (Just $
625                   AST.PrimLit "'('" AST.:&: showMiddle AST.:&: AST.PrimLit "')'")
626       where
627         showMiddle = if null elemTMs then
628             AST.PrimLit "''"
629           else
630             foldr1 (\e1 e2 -> e1 AST.:&: AST.PrimLit "','" AST.:&: e2) $
631               map ((genExprFCall showId).
632                     AST.PrimName .
633                     AST.NSelected .
634                     (AST.NSimple tupPar AST.:.:).
635                     tupVHDLSuffix)
636                   (take tupSize recordlabels)
637     recordlabels = map (\c -> mkVHDLBasicId [c]) ['A'..'Z']
638     tupSize = length elemTMs
639
640 mkAdtShow ::
641   String
642   -> [String] -- Constructors
643   -> [[String]] -- Fields for every constructor
644   -> AST.TypeMark
645   -> AST.SubProgBody
646 mkAdtShow conLbl conIds elemIdss adtTM = AST.SubProgBody showSpec [] [showExpr]
647   where  
648     adtPar   = AST.unsafeVHDLBasicId "adt"
649     showSpec  = AST.Function showId [AST.IfaceVarDec adtPar adtTM] stringTM
650     showExpr  = AST.CaseSm (AST.PrimName $ AST.NSelected $ (AST.NSimple adtPar) AST.:.: (AST.SSimple $ (mkVHDLBasicId conLbl)))
651                   [AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit $ show x] [AST.ReturnSm (Just $ ((AST.PrimLit $ '"':(conIds!!x)++[' ','"'])) AST.:&: showFields x)] | x <- [0..(length conIds) -1]]
652     showFields i = if (null (elemIdss!!i)) then
653         AST.PrimLit "''"
654       else
655         foldr1 (\e1 e2 -> e1 AST.:&: AST.PrimLit "' '" AST.:&: e2) $
656               map ((genExprFCall showId).
657                     AST.PrimName .
658                     AST.NSelected .
659                     (AST.NSimple adtPar AST.:.:).
660                     tupVHDLSuffix)
661                   (map mkVHDLBasicId (elemIdss!!i))              
662     
663 mkEnumShow ::
664   [String]
665   -> AST.TypeMark
666   -> AST.SubProgBody
667 mkEnumShow elemIds enumTM = AST.SubProgBody showSpec [] [showExpr]
668   where  
669     enumPar   = AST.unsafeVHDLBasicId "enum"
670     showSpec  = AST.Function showId [AST.IfaceVarDec enumPar enumTM] stringTM
671     showExpr  = AST.CaseSm (AST.PrimName $ AST.NSimple enumPar)
672                   [AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit $ show x] [AST.ReturnSm (Just $ AST.PrimLit $ '"':(elemIds!!x)++['"'])] | x <- [0..(length elemIds) -1]]
673             
674
675 mkVectorShow ::
676   AST.TypeMark -- ^ elemtype
677   -> AST.TypeMark -- ^ vectype
678   -> [(String,AST.SubProgBody)]
679 mkVectorShow elemTM vectorTM = 
680   [ (headId, AST.SubProgBody headSpec []                   [headExpr])
681   , (tailId, AST.SubProgBody tailSpec [AST.SPVD tailVar]   [tailExpr, tailRet])
682   , (showIdString, AST.SubProgBody showSpec [AST.SPSB doShowDef] [showRet])
683   ]
684   where
685     vecPar  = AST.unsafeVHDLBasicId "vec"
686     resId   = AST.unsafeVHDLBasicId "res"
687     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
688     -- return vec(0);
689     headExpr = AST.ReturnSm (Just (AST.PrimName $ AST.NIndexed (AST.IndexedName 
690                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
691     vecSlice init last =  AST.PrimName (AST.NSlice 
692                                       (AST.SliceName 
693                                             (AST.NSimple vecPar) 
694                                             (AST.ToRange init last)))
695     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
696        -- variable res : fsvec_x (0 to vec'length-2); 
697     tailVar = 
698          AST.VarDec resId 
699                 (AST.SubtypeIn vectorTM
700                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
701                    [AST.ToRange (AST.PrimLit "0")
702                             (AST.PrimName (AST.NAttribute $ 
703                               AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) AST.:-:
704                                 (AST.PrimLit "2"))   ]))
705                 Nothing       
706        -- res AST.:= vec(1 to vec'length-1)
707     tailExpr = AST.NSimple resId AST.:= (vecSlice 
708                                (AST.PrimLit "1") 
709                                (AST.PrimName (AST.NAttribute $ 
710                                   AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing) 
711                                                              AST.:-: AST.PrimLit "1"))
712     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
713     showSpec  = AST.Function showId [AST.IfaceVarDec vecPar vectorTM] stringTM
714     doShowId  = AST.unsafeVHDLExtId "doshow"
715     doShowDef = AST.SubProgBody doShowSpec [] [doShowRet]
716       where doShowSpec = AST.Function doShowId [AST.IfaceVarDec vecPar vectorTM] 
717                                            stringTM
718             -- case vec'len is
719             --  when  0 => return "";
720             --  when  1 => return head(vec);
721             --  when others => return show(head(vec)) & ',' &
722             --                        doshow (tail(vec));
723             -- end case;
724             doShowRet = 
725               AST.CaseSm (AST.PrimName (AST.NAttribute $ 
726                           AST.AttribName (AST.NSimple vecPar) (AST.NSimple $ mkVHDLBasicId lengthId) Nothing))
727               [AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit "0"] 
728                          [AST.ReturnSm (Just $ AST.PrimLit "\"\"")],
729                AST.CaseSmAlt [AST.ChoiceE $ AST.PrimLit "1"] 
730                          [AST.ReturnSm (Just $ 
731                           genExprFCall showId 
732                                (genExprFCall (mkVHDLExtId headId) (AST.PrimName $ AST.NSimple vecPar)) )],
733                AST.CaseSmAlt [AST.Others] 
734                          [AST.ReturnSm (Just $ 
735                            genExprFCall showId 
736                              (genExprFCall (mkVHDLExtId headId) (AST.PrimName $ AST.NSimple vecPar)) AST.:&:
737                            AST.PrimLit "','" AST.:&:
738                            genExprFCall doShowId 
739                              (genExprFCall (mkVHDLExtId tailId) (AST.PrimName $ AST.NSimple vecPar)) ) ]]
740     -- return '<' & doshow(vec) & '>';
741     showRet =  AST.ReturnSm (Just $ AST.PrimLit "'<'" AST.:&:
742                                genExprFCall doShowId (AST.PrimName $ AST.NSimple vecPar) AST.:&:
743                                AST.PrimLit "'>'" )
744
745 mkBuiltInShow :: [AST.SubProgBody]
746 mkBuiltInShow = [ AST.SubProgBody showBitSpec [] [showBitExpr]
747                 , AST.SubProgBody showBoolSpec [] [showBoolExpr]
748                 , AST.SubProgBody showSingedSpec [] [showSignedExpr]
749                 , AST.SubProgBody showUnsignedSpec [] [showUnsignedExpr]
750                 -- , AST.SubProgBody showNaturalSpec [] [showNaturalExpr]
751                 ]
752   where
753     bitPar      = AST.unsafeVHDLBasicId "s"
754     boolPar     = AST.unsafeVHDLBasicId "b"
755     signedPar   = AST.unsafeVHDLBasicId "sint"
756     unsignedPar = AST.unsafeVHDLBasicId "uint"
757     -- naturalPar  = AST.unsafeVHDLBasicId "nat"
758     showBitSpec = AST.Function showId [AST.IfaceVarDec bitPar std_logicTM] stringTM
759     -- if s = '1' then return "'1'" else return "'0'"
760     showBitExpr = AST.IfSm (AST.PrimName (AST.NSimple bitPar) AST.:=: AST.PrimLit "'1'")
761                         [AST.ReturnSm (Just $ AST.PrimLit "\"High\"")]
762                         []
763                         (Just $ AST.Else [AST.ReturnSm (Just $ AST.PrimLit "\"Low\"")])
764     showBoolSpec = AST.Function showId [AST.IfaceVarDec boolPar booleanTM] stringTM
765     -- if b then return "True" else return "False"
766     showBoolExpr = AST.IfSm (AST.PrimName (AST.NSimple boolPar))
767                         [AST.ReturnSm (Just $ AST.PrimLit "\"True\"")]
768                         []
769                         (Just $ AST.Else [AST.ReturnSm (Just $ AST.PrimLit "\"False\"")])
770     showSingedSpec = AST.Function showId [AST.IfaceVarDec signedPar signedTM] stringTM
771     showSignedExpr =  AST.ReturnSm (Just $
772                         AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerId) 
773                         (AST.NIndexed $ AST.IndexedName (AST.NSimple imageId) [signToInt]) Nothing )
774                       where
775                         signToInt = genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple signedPar)
776     showUnsignedSpec =  AST.Function showId [AST.IfaceVarDec unsignedPar unsignedTM] stringTM
777     showUnsignedExpr =  AST.ReturnSm (Just $
778                           AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerId) 
779                           (AST.NIndexed $ AST.IndexedName (AST.NSimple imageId) [unsignToInt]) Nothing )
780                         where
781                           unsignToInt = genExprFCall (mkVHDLBasicId toIntegerId) (AST.PrimName $ AST.NSimple unsignedPar)
782     -- showNaturalSpec = AST.Function showId [AST.IfaceVarDec naturalPar naturalTM] stringTM
783     -- showNaturalExpr = AST.ReturnSm (Just $
784     --                     AST.PrimName $ AST.NAttribute $ AST.AttribName (AST.NSimple integerId)
785     --                     (AST.NIndexed $ AST.IndexedName (AST.NSimple imageId) [AST.PrimName $ AST.NSimple $ naturalPar]) Nothing )
786                       
787   
788 genExprFCall :: AST.VHDLId -> AST.Expr -> AST.Expr
789 genExprFCall fName args = 
790    AST.PrimFCall $ AST.FCall (AST.NSimple fName)  $
791              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) [args] 
792
793 genExprPCall2 :: AST.VHDLId -> AST.Expr -> AST.Expr -> AST.SeqSm             
794 genExprPCall2 entid arg1 arg2 =
795         AST.ProcCall (AST.NSimple entid) $
796          map (\exp -> Nothing AST.:=>: AST.ADExpr exp) [arg1,arg2]
797
798 mkSigDec :: CoreSyn.CoreBndr -> TranslatorSession (Maybe AST.SigDec)
799 mkSigDec bndr = do
800   let error_msg = "\nVHDL.mkSigDec: Can not make signal declaration for type: \n" ++ pprString bndr 
801   type_mark_maybe <- MonadState.lift tsType $ vhdlTy error_msg (Var.varType bndr)
802   case type_mark_maybe of
803     Just type_mark -> return $ Just (AST.SigDec (varToVHDLId bndr) type_mark Nothing)
804     Nothing -> return Nothing
805
806 -- | Does the given thing have a non-empty type?
807 hasNonEmptyType :: (TypedThing t, Outputable.Outputable t) => 
808   t -> TranslatorSession Bool
809 hasNonEmptyType thing = MonadState.lift tsType $ isJustM (vhdlTy "hasNonEmptyType: Non representable type?" thing)