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