Remove the now obsolete getOwnStates.
[matthijs/master-project/cλash.git] / VHDL.hs
1 --
2 -- Functions to generate VHDL from FlatFunctions
3 --
4 module VHDL where
5
6 import qualified Data.Foldable as Foldable
7 import qualified Maybe
8 import qualified Control.Monad as Monad
9
10 import qualified Type
11 import qualified TysWiredIn
12 import qualified Name
13 import qualified TyCon
14 import Outputable ( showSDoc, ppr )
15
16 import qualified ForSyDe.Backend.VHDL.AST as AST
17
18 import VHDLTypes
19 import Flatten
20 import FlattenTypes
21 import TranslatorTypes
22 import Pretty
23
24 getDesignFiles :: VHDLState [AST.DesignFile]
25 getDesignFiles = do
26   -- Extract the library units generated from all the functions in the
27   -- session.
28   funcs <- getFuncs
29   let units = Maybe.mapMaybe getLibraryUnits funcs
30   let context = [
31         AST.Library $ mkVHDLId "IEEE",
32         AST.Use $ (AST.NSimple $ mkVHDLId "IEEE.std_logic_1164") AST.:.: AST.All]
33   return $ map (\(ent, arch) -> AST.DesignFile context [ent, arch]) units
34   
35 -- | Create an entity for a given function
36 createEntity ::
37   HsFunction        -- | The function signature
38   -> FuncData       -- | The function data collected so far
39   -> VHDLState ()
40
41 createEntity hsfunc fdata = 
42   let func = flatFunc fdata in
43   case func of
44     -- Skip (builtin) functions without a FlatFunction
45     Nothing -> do return ()
46     -- Create an entity for all other functions
47     Just flatfunc ->
48       
49       let 
50         sigs    = flat_sigs flatfunc
51         args    = flat_args flatfunc
52         res     = flat_res  flatfunc
53         args'   = map (fmap (mkMap sigs)) args
54         res'    = fmap (mkMap sigs) res
55         ent_decl' = createEntityAST hsfunc args' res'
56         AST.EntityDec entity_id _ = ent_decl' 
57         entity' = Entity entity_id args' res' (Just ent_decl')
58       in
59         setEntity hsfunc entity'
60   where
61     mkMap :: Eq id => [(id, SignalInfo)] -> id -> Maybe (AST.VHDLId, AST.TypeMark)
62     mkMap sigmap id =
63       if isPortSigUse $ sigUse info
64         then
65           Just (mkVHDLId nm, vhdl_ty ty)
66         else
67           Nothing
68       where
69         info = Maybe.fromMaybe
70           (error $ "Signal not found in the name map? This should not happen!")
71           (lookup id sigmap)
72         nm = Maybe.fromMaybe
73           (error $ "Signal not named? This should not happen!")
74           (sigName info)
75         ty = sigTy info
76
77   -- | Create the VHDL AST for an entity
78 createEntityAST ::
79   HsFunction            -- | The signature of the function we're working with
80   -> [VHDLSignalMap]    -- | The entity's arguments
81   -> VHDLSignalMap      -- | The entity's result
82   -> AST.EntityDec      -- | The entity with the ent_decl filled in as well
83
84 createEntityAST hsfunc args res =
85   AST.EntityDec vhdl_id ports
86   where
87     vhdl_id = mkEntityId hsfunc
88     ports = concatMap (mapToPorts AST.In) args
89             ++ mapToPorts AST.Out res
90             ++ clk_port
91     mapToPorts :: AST.Mode -> VHDLSignalMap -> [AST.IfaceSigDec] 
92     mapToPorts mode m =
93       Maybe.catMaybes $ map (mkIfaceSigDec mode) (Foldable.toList m)
94     -- Add a clk port if we have state
95     clk_port = if hasState hsfunc
96       then
97         [AST.IfaceSigDec (mkVHDLId "clk") AST.In VHDL.std_logic_ty]
98       else
99         []
100
101 -- | Create a port declaration
102 mkIfaceSigDec ::
103   AST.Mode                         -- | The mode for the port (In / Out)
104   -> Maybe (AST.VHDLId, AST.TypeMark)    -- | The id and type for the port
105   -> Maybe AST.IfaceSigDec               -- | The resulting port declaration
106
107 mkIfaceSigDec mode (Just (id, ty)) = Just $ AST.IfaceSigDec id mode ty
108 mkIfaceSigDec _ Nothing = Nothing
109
110 -- | Generate a VHDL entity name for the given hsfunc
111 mkEntityId hsfunc =
112   -- TODO: This doesn't work for functions with multiple signatures!
113   mkVHDLId $ hsFuncName hsfunc
114
115 -- | Create an architecture for a given function
116 createArchitecture ::
117   HsFunction        -- | The function signature
118   -> FuncData       -- | The function data collected so far
119   -> VHDLState ()
120
121 createArchitecture hsfunc fdata = 
122   let func = flatFunc fdata in
123   case func of
124     -- Skip (builtin) functions without a FlatFunction
125     Nothing -> do return ()
126     -- Create an architecture for all other functions
127     Just flatfunc -> do
128       let sigs = flat_sigs flatfunc
129       let args = flat_args flatfunc
130       let res  = flat_res  flatfunc
131       let defs = flat_defs flatfunc
132       let entity_id = Maybe.fromMaybe
133                       (error $ "Building architecture without an entity? This should not happen!")
134                       (getEntityId fdata)
135       -- Create signal declarations for all signals that are not in args and
136       -- res
137       let sig_decs = Maybe.catMaybes $ map (mkSigDec . snd) sigs
138       -- Create concurrent statements for all signal definitions
139       statements <- mapM (mkConcSm sigs) defs
140       let procs = map mkStateProcSm (makeStatePairs flatfunc)
141       let procs' = map AST.CSPSm procs
142       let arch = AST.ArchBody (mkVHDLId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) (statements ++ procs')
143       setArchitecture hsfunc arch
144
145 -- | Looks up all pairs of old state, new state signals, together with
146 --   the state id they represent.
147 makeStatePairs :: FlatFunction -> [(StateId, SignalInfo, SignalInfo)]
148 makeStatePairs flatfunc =
149   [(Maybe.fromJust $ oldStateId $ sigUse old_info, old_info, new_info) 
150     | old_info <- map snd (flat_sigs flatfunc)
151     , new_info <- map snd (flat_sigs flatfunc)
152         -- old_info must be an old state (and, because of the next equality,
153         -- new_info must be a new state).
154         , Maybe.isJust $ oldStateId $ sigUse old_info
155         -- And the state numbers must match
156     , (oldStateId $ sigUse old_info) == (newStateId $ sigUse new_info)]
157
158     -- Replace the second tuple element with the corresponding SignalInfo
159     --args_states = map (Arrow.second $ signalInfo sigs) args
160 mkStateProcSm :: (StateId, SignalInfo, SignalInfo) -> AST.ProcSm
161 mkStateProcSm (num, old, new) =
162   AST.ProcSm label [clk] [statement]
163   where
164     label       = mkVHDLId $ "state_" ++ (show num)
165     clk         = mkVHDLId "clk"
166     rising_edge = AST.NSimple $ mkVHDLId "rising_edge"
167     wform       = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple $ getSignalId new) Nothing]
168     assign      = AST.SigAssign (AST.NSimple $ getSignalId old) wform
169     rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
170     statement   = AST.IfSm rising_edge_clk [assign] [] Nothing
171
172 mkSigDec :: SignalInfo -> Maybe AST.SigDec
173 mkSigDec info =
174   let use = sigUse info in
175   if isInternalSigUse use || isStateSigUse use then
176     Just $ AST.SigDec (getSignalId info) (vhdl_ty ty) Nothing
177   else
178     Nothing
179   where
180     ty = sigTy info
181
182 -- | Creates a VHDL Id from a named SignalInfo. Errors out if the SignalInfo
183 --   is not named.
184 getSignalId :: SignalInfo -> AST.VHDLId
185 getSignalId info =
186     mkVHDLId $ Maybe.fromMaybe
187       (error $ "Unnamed signal? This should not happen!")
188       (sigName info)
189
190 -- | Transforms a signal definition into a VHDL concurrent statement
191 mkConcSm ::
192   [(SignalId, SignalInfo)] -- | The signals in the current architecture
193   -> SigDef                -- | The signal definition
194   -> VHDLState AST.ConcSm    -- | The corresponding VHDL component instantiation.
195
196 mkConcSm sigs (FApp hsfunc args res) = do
197   fdata_maybe <- getFunc hsfunc
198   let fdata = Maybe.fromMaybe
199         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' that is not in the session? This should not happen!")
200         fdata_maybe
201   let entity = Maybe.fromMaybe
202         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' without entity declaration? This should not happen!")
203         (funcEntity fdata)
204   let entity_id = ent_id entity
205   label <- uniqueName (AST.fromVHDLId entity_id)
206   let portmaps = mkAssocElems sigs args res entity
207   return $ AST.CSISm $ AST.CompInsSm (mkVHDLId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect portmaps)
208
209 mkConcSm sigs (UncondDef src dst) = do
210   let src_expr  = vhdl_expr src
211   let src_wform = AST.Wform [AST.WformElem src_expr Nothing]
212   let dst_name  = AST.NSimple (getSignalId $ signalInfo sigs dst)
213   let assign    = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
214   return $ AST.CSSASm assign
215   where
216     vhdl_expr (Left id) = mkIdExpr sigs id
217     vhdl_expr (Right expr) =
218       case expr of
219         (EqLit id lit) ->
220           (mkIdExpr sigs id) AST.:=: (AST.PrimLit lit)
221         (Literal lit) ->
222           AST.PrimLit lit
223         (Eq a b) ->
224           (mkIdExpr sigs a) AST.:=: (mkIdExpr sigs b)
225
226 mkConcSm sigs (CondDef cond true false dst) = do
227   let cond_expr  = mkIdExpr sigs cond
228   let true_expr  = mkIdExpr sigs true
229   let false_expr  = mkIdExpr sigs false
230   let false_wform = AST.Wform [AST.WformElem false_expr Nothing]
231   let true_wform = AST.Wform [AST.WformElem true_expr Nothing]
232   let whenelse = AST.WhenElse true_wform cond_expr
233   let dst_name  = AST.NSimple (getSignalId $ signalInfo sigs dst)
234   let assign    = dst_name AST.:<==: (AST.ConWforms [whenelse] false_wform Nothing)
235   return $ AST.CSSASm assign
236
237 -- | Turn a SignalId into a VHDL Expr
238 mkIdExpr :: [(SignalId, SignalInfo)] -> SignalId -> AST.Expr
239 mkIdExpr sigs id =
240   let src_name  = AST.NSimple (getSignalId $ signalInfo sigs id) in
241   AST.PrimName src_name
242
243 mkAssocElems :: 
244   [(SignalId, SignalInfo)]      -- | The signals in the current architecture
245   -> [SignalMap]                -- | The signals that are applied to function
246   -> SignalMap                  -- | the signals in which to store the function result
247   -> Entity                     -- | The entity to map against.
248   -> [AST.AssocElem]            -- | The resulting port maps
249
250 mkAssocElems sigmap args res entity =
251     -- Create the actual AssocElems
252     Maybe.catMaybes $ zipWith mkAssocElem ports sigs
253   where
254     -- Turn the ports and signals from a map into a flat list. This works,
255     -- since the maps must have an identical form by definition. TODO: Check
256     -- the similar form?
257     arg_ports = concat (map Foldable.toList (ent_args entity))
258     res_ports = Foldable.toList (ent_res entity)
259     arg_sigs  = (concat (map Foldable.toList args))
260     res_sigs  = Foldable.toList res
261     -- Extract the id part from the (id, type) tuple
262     ports     = (map (fmap fst) (arg_ports ++ res_ports)) 
263     -- Translate signal numbers into names
264     sigs      = (map (lookupSigName sigmap) (arg_sigs ++ res_sigs))
265
266 -- | Look up a signal in the signal name map
267 lookupSigName :: [(SignalId, SignalInfo)] -> SignalId -> String
268 lookupSigName sigs sig = name
269   where
270     info = Maybe.fromMaybe
271       (error $ "Unknown signal " ++ (show sig) ++ " used? This should not happen!")
272       (lookup sig sigs)
273     name = Maybe.fromMaybe
274       (error $ "Unnamed signal " ++ (show sig) ++ " used? This should not happen!")
275       (sigName info)
276
277 -- | Create an VHDL port -> signal association
278 mkAssocElem :: Maybe AST.VHDLId -> String -> Maybe AST.AssocElem
279 mkAssocElem (Just port) signal = Just $ Just port AST.:=>: (AST.ADName (AST.NSimple (mkVHDLId signal))) 
280 mkAssocElem Nothing _ = Nothing
281
282 -- | Extracts the generated entity id from the given funcdata
283 getEntityId :: FuncData -> Maybe AST.VHDLId
284 getEntityId fdata =
285   case funcEntity fdata of
286     Nothing -> Nothing
287     Just e  -> case ent_decl e of
288       Nothing -> Nothing
289       Just (AST.EntityDec id _) -> Just id
290
291 getLibraryUnits ::
292   (HsFunction, FuncData)      -- | A function from the session
293   -> Maybe (AST.LibraryUnit, AST.LibraryUnit) -- | The entity and architecture for the function
294
295 getLibraryUnits (hsfunc, fdata) =
296   case funcEntity fdata of 
297     Nothing -> Nothing
298     Just ent -> 
299       case ent_decl ent of
300       Nothing -> Nothing
301       Just decl ->
302         case funcArch fdata of
303           Nothing -> Nothing
304           Just arch ->
305             Just (AST.LUEntity decl, AST.LUArch arch)
306
307 -- | The VHDL Bit type
308 bit_ty :: AST.TypeMark
309 bit_ty = AST.unsafeVHDLBasicId "Bit"
310
311 -- | The VHDL Boolean type
312 bool_ty :: AST.TypeMark
313 bool_ty = AST.unsafeVHDLBasicId "Boolean"
314
315 -- | The VHDL std_logic
316 std_logic_ty :: AST.TypeMark
317 std_logic_ty = AST.unsafeVHDLBasicId "std_logic"
318
319 -- Translate a Haskell type to a VHDL type
320 vhdl_ty :: Type.Type -> AST.TypeMark
321 vhdl_ty ty = Maybe.fromMaybe
322   (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
323   (vhdl_ty_maybe ty)
324
325 -- Translate a Haskell type to a VHDL type
326 vhdl_ty_maybe :: Type.Type -> Maybe AST.TypeMark
327 vhdl_ty_maybe ty =
328   if Type.coreEqType ty TysWiredIn.boolTy
329     then
330       Just bool_ty
331     else
332       case Type.splitTyConApp_maybe ty of
333         Just (tycon, args) ->
334           let name = TyCon.tyConName tycon in
335             -- TODO: Do something more robust than string matching
336             case Name.getOccString name of
337               "Bit"      -> Just std_logic_ty
338               otherwise  -> Nothing
339         otherwise -> Nothing
340
341 -- Shortcut
342 mkVHDLId :: String -> AST.VHDLId
343 mkVHDLId s = 
344   AST.unsafeVHDLBasicId s'
345   where
346     -- Strip invalid characters.
347     s' = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.") s