Add StandalonDeriving language option to Pretty.
[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 (getOwnStates hsfunc 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 mkStateProcSm :: (StateId, SignalInfo, SignalInfo) -> AST.ProcSm
146 mkStateProcSm (num, old, new) =
147   AST.ProcSm label [clk] [statement]
148   where
149     label       = mkVHDLId $ "state_" ++ (show num)
150     clk         = mkVHDLId "clk"
151     rising_edge = AST.NSimple $ mkVHDLId "rising_edge"
152     wform       = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple $ getSignalId new) Nothing]
153     assign      = AST.SigAssign (AST.NSimple $ getSignalId old) wform
154     rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
155     statement   = AST.IfSm rising_edge_clk [assign] [] Nothing
156
157 mkSigDec :: SignalInfo -> Maybe AST.SigDec
158 mkSigDec info =
159   let use = sigUse info in
160   if isInternalSigUse use || isStateSigUse use then
161     Just $ AST.SigDec (getSignalId info) (vhdl_ty ty) Nothing
162   else
163     Nothing
164   where
165     ty = sigTy info
166
167 -- | Creates a VHDL Id from a named SignalInfo. Errors out if the SignalInfo
168 --   is not named.
169 getSignalId :: SignalInfo -> AST.VHDLId
170 getSignalId info =
171     mkVHDLId $ Maybe.fromMaybe
172       (error $ "Unnamed signal? This should not happen!")
173       (sigName info)
174
175 -- | Transforms a signal definition into a VHDL concurrent statement
176 mkConcSm ::
177   [(SignalId, SignalInfo)] -- | The signals in the current architecture
178   -> SigDef                -- | The signal definition
179   -> VHDLState AST.ConcSm    -- | The corresponding VHDL component instantiation.
180
181 mkConcSm sigs (FApp hsfunc args res) = do
182   fdata_maybe <- getFunc hsfunc
183   let fdata = Maybe.fromMaybe
184         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' that is not in the session? This should not happen!")
185         fdata_maybe
186   let entity = Maybe.fromMaybe
187         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' without entity declaration? This should not happen!")
188         (funcEntity fdata)
189   let entity_id = ent_id entity
190   label <- uniqueName (AST.fromVHDLId entity_id)
191   let portmaps = mkAssocElems sigs args res entity
192   return $ AST.CSISm $ AST.CompInsSm (mkVHDLId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect portmaps)
193
194 mkConcSm sigs (UncondDef src dst) = do
195   let src_expr  = vhdl_expr src
196   let src_wform = AST.Wform [AST.WformElem src_expr Nothing]
197   let dst_name  = AST.NSimple (getSignalId $ signalInfo sigs dst)
198   let assign    = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
199   return $ AST.CSSASm assign
200   where
201     vhdl_expr (Left id) = mkIdExpr sigs id
202     vhdl_expr (Right expr) =
203       case expr of
204         (EqLit id lit) ->
205           (mkIdExpr sigs id) AST.:=: (AST.PrimLit lit)
206         (Literal lit) ->
207           AST.PrimLit lit
208         (Eq a b) ->
209           (mkIdExpr sigs a) AST.:=: (mkIdExpr sigs b)
210
211 mkConcSm sigs (CondDef cond true false dst) = do
212   let cond_expr  = mkIdExpr sigs cond
213   let true_expr  = mkIdExpr sigs true
214   let false_expr  = mkIdExpr sigs false
215   let false_wform = AST.Wform [AST.WformElem false_expr Nothing]
216   let true_wform = AST.Wform [AST.WformElem true_expr Nothing]
217   let whenelse = AST.WhenElse true_wform cond_expr
218   let dst_name  = AST.NSimple (getSignalId $ signalInfo sigs dst)
219   let assign    = dst_name AST.:<==: (AST.ConWforms [whenelse] false_wform Nothing)
220   return $ AST.CSSASm assign
221
222 -- | Turn a SignalId into a VHDL Expr
223 mkIdExpr :: [(SignalId, SignalInfo)] -> SignalId -> AST.Expr
224 mkIdExpr sigs id =
225   let src_name  = AST.NSimple (getSignalId $ signalInfo sigs id) in
226   AST.PrimName src_name
227
228 mkAssocElems :: 
229   [(SignalId, SignalInfo)]      -- | The signals in the current architecture
230   -> [SignalMap]                -- | The signals that are applied to function
231   -> SignalMap                  -- | the signals in which to store the function result
232   -> Entity                     -- | The entity to map against.
233   -> [AST.AssocElem]            -- | The resulting port maps
234
235 mkAssocElems sigmap args res entity =
236     -- Create the actual AssocElems
237     Maybe.catMaybes $ zipWith mkAssocElem ports sigs
238   where
239     -- Turn the ports and signals from a map into a flat list. This works,
240     -- since the maps must have an identical form by definition. TODO: Check
241     -- the similar form?
242     arg_ports = concat (map Foldable.toList (ent_args entity))
243     res_ports = Foldable.toList (ent_res entity)
244     arg_sigs  = (concat (map Foldable.toList args))
245     res_sigs  = Foldable.toList res
246     -- Extract the id part from the (id, type) tuple
247     ports     = (map (fmap fst) (arg_ports ++ res_ports)) 
248     -- Translate signal numbers into names
249     sigs      = (map (lookupSigName sigmap) (arg_sigs ++ res_sigs))
250
251 -- | Look up a signal in the signal name map
252 lookupSigName :: [(SignalId, SignalInfo)] -> SignalId -> String
253 lookupSigName sigs sig = name
254   where
255     info = Maybe.fromMaybe
256       (error $ "Unknown signal " ++ (show sig) ++ " used? This should not happen!")
257       (lookup sig sigs)
258     name = Maybe.fromMaybe
259       (error $ "Unnamed signal " ++ (show sig) ++ " used? This should not happen!")
260       (sigName info)
261
262 -- | Create an VHDL port -> signal association
263 mkAssocElem :: Maybe AST.VHDLId -> String -> Maybe AST.AssocElem
264 mkAssocElem (Just port) signal = Just $ Just port AST.:=>: (AST.ADName (AST.NSimple (mkVHDLId signal))) 
265 mkAssocElem Nothing _ = Nothing
266
267 -- | Extracts the generated entity id from the given funcdata
268 getEntityId :: FuncData -> Maybe AST.VHDLId
269 getEntityId fdata =
270   case funcEntity fdata of
271     Nothing -> Nothing
272     Just e  -> case ent_decl e of
273       Nothing -> Nothing
274       Just (AST.EntityDec id _) -> Just id
275
276 getLibraryUnits ::
277   (HsFunction, FuncData)      -- | A function from the session
278   -> Maybe (AST.LibraryUnit, AST.LibraryUnit) -- | The entity and architecture for the function
279
280 getLibraryUnits (hsfunc, fdata) =
281   case funcEntity fdata of 
282     Nothing -> Nothing
283     Just ent -> 
284       case ent_decl ent of
285       Nothing -> Nothing
286       Just decl ->
287         case funcArch fdata of
288           Nothing -> Nothing
289           Just arch ->
290             Just (AST.LUEntity decl, AST.LUArch arch)
291
292 -- | The VHDL Bit type
293 bit_ty :: AST.TypeMark
294 bit_ty = AST.unsafeVHDLBasicId "Bit"
295
296 -- | The VHDL Boolean type
297 bool_ty :: AST.TypeMark
298 bool_ty = AST.unsafeVHDLBasicId "Boolean"
299
300 -- | The VHDL std_logic
301 std_logic_ty :: AST.TypeMark
302 std_logic_ty = AST.unsafeVHDLBasicId "std_logic"
303
304 -- Translate a Haskell type to a VHDL type
305 vhdl_ty :: Type.Type -> AST.TypeMark
306 vhdl_ty ty = Maybe.fromMaybe
307   (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
308   (vhdl_ty_maybe ty)
309
310 -- Translate a Haskell type to a VHDL type
311 vhdl_ty_maybe :: Type.Type -> Maybe AST.TypeMark
312 vhdl_ty_maybe ty =
313   if Type.coreEqType ty TysWiredIn.boolTy
314     then
315       Just bool_ty
316     else
317       case Type.splitTyConApp_maybe ty of
318         Just (tycon, args) ->
319           let name = TyCon.tyConName tycon in
320             -- TODO: Do something more robust than string matching
321             case Name.getOccString name of
322               "Bit"      -> Just std_logic_ty
323               otherwise  -> Nothing
324         otherwise -> Nothing
325
326 -- Shortcut
327 mkVHDLId :: String -> AST.VHDLId
328 mkVHDLId s = 
329   AST.unsafeVHDLBasicId s'
330   where
331     -- Strip invalid characters.
332     s' = filter (`elem` ['A'..'Z'] ++ ['a'..'z'] ++ ['0'..'9'] ++ "_.") s