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