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