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