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