Add clk port on any stateful entity.
[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 Name
12 import qualified TyCon
13 import Outputable ( showSDoc, ppr )
14
15 import qualified ForSyDe.Backend.VHDL.AST as AST
16
17 import VHDLTypes
18 import Flatten
19 import FlattenTypes
20 import TranslatorTypes
21 import Pretty
22
23 -- | Create an entity for a given function
24 createEntity ::
25   HsFunction        -- | The function signature
26   -> FuncData       -- | The function data collected so far
27   -> VHDLState ()
28
29 createEntity hsfunc fdata = 
30   let func = flatFunc fdata in
31   case func of
32     -- Skip (builtin) functions without a FlatFunction
33     Nothing -> do return ()
34     -- Create an entity for all other functions
35     Just flatfunc ->
36       
37       let 
38         sigs    = flat_sigs flatfunc
39         args    = flat_args flatfunc
40         res     = flat_res  flatfunc
41         args'   = map (fmap (mkMap sigs)) args
42         res'    = fmap (mkMap sigs) res
43         ent_decl' = createEntityAST hsfunc args' res'
44         AST.EntityDec entity_id _ = ent_decl' 
45         entity' = Entity entity_id args' res' (Just ent_decl')
46       in
47         setEntity hsfunc entity'
48   where
49     mkMap :: Eq id => [(id, SignalInfo)] -> id -> (AST.VHDLId, AST.TypeMark)
50     mkMap sigmap id =
51       (mkVHDLId nm, vhdl_ty ty)
52       where
53         info = Maybe.fromMaybe
54           (error $ "Signal not found in the name map? This should not happen!")
55           (lookup id sigmap)
56         nm = Maybe.fromMaybe
57           (error $ "Signal not named? This should not happen!")
58           (sigName info)
59         ty = sigTy info
60
61   -- | Create the VHDL AST for an entity
62 createEntityAST ::
63   HsFunction            -- | The signature of the function we're working with
64   -> [VHDLSignalMap]    -- | The entity's arguments
65   -> VHDLSignalMap      -- | The entity's result
66   -> AST.EntityDec      -- | The entity with the ent_decl filled in as well
67
68 createEntityAST hsfunc args res =
69   AST.EntityDec vhdl_id ports
70   where
71     vhdl_id = mkEntityId hsfunc
72     ports = concatMap (mapToPorts AST.In) args
73             ++ mapToPorts AST.Out res
74             ++ clk_port
75     mapToPorts :: AST.Mode -> VHDLSignalMap -> [AST.IfaceSigDec] 
76     mapToPorts mode m =
77       map (mkIfaceSigDec mode) (Foldable.toList m)
78     -- Add a clk port if we have state
79     clk_port = if hasState hsfunc
80       then
81         [AST.IfaceSigDec (mkVHDLId "clk") AST.In VHDL.std_logic_ty]
82       else
83         []
84
85 -- | Create a port declaration
86 mkIfaceSigDec ::
87   AST.Mode                         -- | The mode for the port (In / Out)
88   -> (AST.VHDLId, AST.TypeMark)    -- | The id and type for the port
89   -> AST.IfaceSigDec               -- | The resulting port declaration
90
91 mkIfaceSigDec mode (id, ty) = AST.IfaceSigDec id mode ty
92
93 -- | Generate a VHDL entity name for the given hsfunc
94 mkEntityId hsfunc =
95   -- TODO: This doesn't work for functions with multiple signatures!
96   mkVHDLId $ hsFuncName hsfunc
97
98 -- | Create an architecture for a given function
99 createArchitecture ::
100   HsFunction        -- | The function signature
101   -> FuncData       -- | The function data collected so far
102   -> VHDLState ()
103
104 createArchitecture hsfunc fdata = 
105   let func = flatFunc fdata in
106   case func of
107     -- Skip (builtin) functions without a FlatFunction
108     Nothing -> do return ()
109     -- Create an architecture for all other functions
110     Just flatfunc -> do
111       let sigs = flat_sigs flatfunc
112       let args = flat_args flatfunc
113       let res  = flat_res  flatfunc
114       let apps = flat_apps flatfunc
115       let entity_id = Maybe.fromMaybe
116                       (error $ "Building architecture without an entity? This should not happen!")
117                       (getEntityId fdata)
118       -- Create signal declarations for all signals that are not in args and
119       -- res
120       let sig_decs = [mkSigDec info | (id, info) <- sigs, (all (id `Foldable.notElem`) (res:args)) ]
121       -- Create component instantiations for all function applications
122       insts <- mapM (mkCompInsSm sigs) apps
123       let procs = map mkStateProcSm (getOwnStates hsfunc flatfunc)
124       let insts' = map AST.CSISm insts
125       let procs' = map AST.CSPSm procs
126       let arch = AST.ArchBody (mkVHDLId "structural") (AST.NSimple entity_id) (map AST.BDISD sig_decs) (insts' ++ procs')
127       setArchitecture hsfunc arch
128
129 mkStateProcSm :: (Int, SignalInfo, SignalInfo) -> AST.ProcSm
130 mkStateProcSm (num, old, new) =
131   AST.ProcSm label [clk] [statement]
132   where
133     label       = mkVHDLId $ "state_" ++ (show num)
134     clk         = mkVHDLId "clk"
135     rising_edge = AST.NSimple $ mkVHDLId "rising_edge"
136     wform       = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple $ getSignalId new) Nothing]
137     assign      = AST.SigAssign (AST.NSimple $ getSignalId old) wform
138     rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
139     statement   = AST.IfSm rising_edge_clk [assign] [] Nothing
140
141 mkSigDec :: SignalInfo -> AST.SigDec
142 mkSigDec info =
143     AST.SigDec (getSignalId info) (vhdl_ty ty) Nothing
144   where
145     ty = sigTy info
146
147 -- | Creates a VHDL Id from a named SignalInfo. Errors out if the SignalInfo
148 --   is not named.
149 getSignalId :: SignalInfo -> AST.VHDLId
150 getSignalId info =
151     mkVHDLId $ Maybe.fromMaybe
152       (error $ "Unnamed signal? This should not happen!")
153       (sigName info)
154
155 -- | Transforms a flat function application to a VHDL component instantiation.
156 mkCompInsSm ::
157   [(UnnamedSignal, SignalInfo)] -- | The signals in the current architecture
158   -> FApp UnnamedSignal         -- | The application to look at.
159   -> VHDLState AST.CompInsSm    -- | The corresponding VHDL component instantiation.
160
161 mkCompInsSm sigs app = do
162   let hsfunc = appFunc app
163   fdata_maybe <- getFunc hsfunc
164   let fdata = Maybe.fromMaybe
165         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' that is not in the session? This should not happen!")
166         fdata_maybe
167   let entity = Maybe.fromMaybe
168         (error $ "Using function '" ++ (prettyShow hsfunc) ++ "' without entity declaration? This should not happen!")
169         (funcEntity fdata)
170   let entity_id = ent_id entity
171   label <- uniqueName (AST.fromVHDLId entity_id)
172   let portmaps = mkAssocElems sigs app entity
173   return $ AST.CompInsSm (mkVHDLId label) (AST.IUEntity (AST.NSimple entity_id)) (AST.PMapAspect portmaps)
174
175 mkAssocElems :: 
176   [(UnnamedSignal, SignalInfo)] -- | The signals in the current architecture
177   -> FApp UnnamedSignal         -- | The application to look at.
178   -> Entity                     -- | The entity to map against.
179   -> [AST.AssocElem]            -- | The resulting port maps
180
181 mkAssocElems sigmap app entity =
182     -- Create the actual AssocElems
183     zipWith mkAssocElem ports sigs
184   where
185     -- Turn the ports and signals from a map into a flat list. This works,
186     -- since the maps must have an identical form by definition. TODO: Check
187     -- the similar form?
188     arg_ports = concat (map Foldable.toList (ent_args entity))
189     res_ports = Foldable.toList (ent_res entity)
190     arg_sigs  = (concat (map Foldable.toList (appArgs app)))
191     res_sigs  = Foldable.toList (appRes app)
192     -- Extract the id part from the (id, type) tuple
193     ports     = (map fst (arg_ports ++ res_ports)) 
194     -- Translate signal numbers into names
195     sigs      = (map (lookupSigName sigmap) (arg_sigs ++ res_sigs))
196
197 -- | Look up a signal in the signal name map
198 lookupSigName :: [(UnnamedSignal, SignalInfo)] -> UnnamedSignal -> String
199 lookupSigName sigs sig = name
200   where
201     info = Maybe.fromMaybe
202       (error $ "Unknown signal " ++ (show sig) ++ " used? This should not happen!")
203       (lookup sig sigs)
204     name = Maybe.fromMaybe
205       (error $ "Unnamed signal " ++ (show sig) ++ " used? This should not happen!")
206       (sigName info)
207
208 -- | Create an VHDL port -> signal association
209 mkAssocElem :: AST.VHDLId -> String -> AST.AssocElem
210 mkAssocElem port signal = Just port AST.:=>: (AST.ADName (AST.NSimple (mkVHDLId signal))) 
211
212 -- | Extracts the generated entity id from the given funcdata
213 getEntityId :: FuncData -> Maybe AST.VHDLId
214 getEntityId fdata =
215   case funcEntity fdata of
216     Nothing -> Nothing
217     Just e  -> case ent_decl e of
218       Nothing -> Nothing
219       Just (AST.EntityDec id _) -> Just id
220
221 getLibraryUnits ::
222   (HsFunction, FuncData)      -- | A function from the session
223   -> [AST.LibraryUnit]        -- | The library units it generates
224
225 getLibraryUnits (hsfunc, fdata) =
226   case funcEntity fdata of 
227     Nothing -> []
228     Just ent -> case ent_decl ent of
229       Nothing -> []
230       Just decl -> [AST.LUEntity decl]
231   ++
232   case funcArch fdata of
233     Nothing -> []
234     Just arch -> [AST.LUArch arch]
235
236 -- | The VHDL Bit type
237 bit_ty :: AST.TypeMark
238 bit_ty = AST.unsafeVHDLBasicId "Bit"
239
240 -- | The VHDL std_logic
241 std_logic_ty :: AST.TypeMark
242 std_logic_ty = AST.unsafeVHDLBasicId "std_logic"
243
244 -- Translate a Haskell type to a VHDL type
245 vhdl_ty :: Type.Type -> AST.TypeMark
246 vhdl_ty ty = Maybe.fromMaybe
247   (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
248   (vhdl_ty_maybe ty)
249
250 -- Translate a Haskell type to a VHDL type
251 vhdl_ty_maybe :: Type.Type -> Maybe AST.TypeMark
252 vhdl_ty_maybe ty =
253   case Type.splitTyConApp_maybe ty of
254     Just (tycon, args) ->
255       let name = TyCon.tyConName tycon in
256         -- TODO: Do something more robust than string matching
257         case Name.getOccString name of
258           "Bit"      -> Just bit_ty
259           otherwise  -> Nothing
260     otherwise -> Nothing
261
262 -- Shortcut
263 mkVHDLId :: String -> AST.VHDLId
264 mkVHDLId = AST.unsafeVHDLBasicId