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