Make the arguments of the alu function curried.
[matthijs/master-project/cλash.git] / Translator.hs
1 module Main(main) where
2 import GHC
3 import CoreSyn
4 import qualified CoreUtils
5 import qualified Var
6 import qualified Type
7 import qualified TyCon
8 import qualified DataCon
9 import qualified Maybe
10 import qualified Module
11 import qualified Control.Monad.State as State
12 import Name
13 import Data.Generics
14 import NameEnv ( lookupNameEnv )
15 import HscTypes ( cm_binds, cm_types )
16 import MonadUtils ( liftIO )
17 import Outputable ( showSDoc, ppr )
18 import GHC.Paths ( libdir )
19 import DynFlags ( defaultDynFlags )
20 import List ( find )
21 import qualified List
22 import qualified Monad
23
24 -- The following modules come from the ForSyDe project. They are really
25 -- internal modules, so ForSyDe.cabal has to be modified prior to installing
26 -- ForSyDe to get access to these modules.
27 import qualified ForSyDe.Backend.VHDL.AST as AST
28 import qualified ForSyDe.Backend.VHDL.Ppr
29 import qualified ForSyDe.Backend.VHDL.FileIO
30 import qualified ForSyDe.Backend.Ppr
31 -- This is needed for rendering the pretty printed VHDL
32 import Text.PrettyPrint.HughesPJ (render)
33
34 main = 
35     do
36       defaultErrorHandler defaultDynFlags $ do
37         runGhc (Just libdir) $ do
38           dflags <- getSessionDynFlags
39           setSessionDynFlags dflags
40           --target <- guessTarget "adder.hs" Nothing
41           --liftIO (print (showSDoc (ppr (target))))
42           --liftIO $ printTarget target
43           --setTargets [target]
44           --load LoadAllTargets
45           --core <- GHC.compileToCoreSimplified "Adders.hs"
46           core <- GHC.compileToCoreSimplified "Adders.hs"
47           --liftIO $ printBinds (cm_binds core)
48           let binds = Maybe.mapMaybe (findBind (cm_binds core)) ["dff"]
49           liftIO $ printBinds binds
50           -- Turn bind into VHDL
51           let (vhdl, sess) = State.runState (mkVHDL binds) (VHDLSession 0 [])
52           liftIO $ putStr $ render $ ForSyDe.Backend.Ppr.ppr vhdl
53           liftIO $ ForSyDe.Backend.VHDL.FileIO.writeDesignFile vhdl "../vhdl/vhdl/output.vhdl"
54           liftIO $ putStr $ "\n\nFinal session:\n" ++ show sess
55           return ()
56   where
57     -- Turns the given bind into VHDL
58     mkVHDL binds = do
59       -- Add the builtin functions
60       mapM (uncurry addFunc) builtin_funcs
61       -- Create entities and architectures for them
62       units <- mapM expandBind binds
63       return $ AST.DesignFile 
64         []
65         (concat units)
66
67 printTarget (Target (TargetFile file (Just x)) obj Nothing) =
68   print $ show file
69
70 printBinds [] = putStr "done\n\n"
71 printBinds (b:bs) = do
72   printBind b
73   putStr "\n"
74   printBinds bs
75
76 printBind (NonRec b expr) = do
77   putStr "NonRec: "
78   printBind' (b, expr)
79
80 printBind (Rec binds) = do
81   putStr "Rec: \n"  
82   foldl1 (>>) (map printBind' binds)
83
84 printBind' (b, expr) = do
85   putStr $ getOccString b
86   putStr $ showSDoc $ ppr expr
87   putStr "\n"
88
89 findBind :: [CoreBind] -> String -> Maybe CoreBind
90 findBind binds lookfor =
91   -- This ignores Recs and compares the name of the bind with lookfor,
92   -- disregarding any namespaces in OccName and extra attributes in Name and
93   -- Var.
94   find (\b -> case b of 
95     Rec l -> False
96     NonRec var _ -> lookfor == (occNameString $ nameOccName $ getName var)
97   ) binds
98
99 getPortMapEntry ::
100   SignalNameMap  -- The port name to bind to
101   -> SignalNameMap 
102                             -- The signal or port to bind to it
103   -> AST.AssocElem          -- The resulting port map entry
104   
105 -- Accepts a port name and an argument to map to it.
106 -- Returns the appropriate line for in the port map
107 getPortMapEntry (Single (portname, _)) (Single (signame, _)) = 
108   (Just portname) AST.:=>: (AST.ADName (AST.NSimple signame))
109 expandExpr ::
110   [(CoreBndr, SignalNameMap)] 
111                                          -- A list of bindings in effect
112   -> CoreExpr                            -- The expression to expand
113   -> VHDLState (
114        [AST.SigDec],                     -- Needed signal declarations
115        [AST.ConcSm],                     -- Needed component instantations and
116                                          -- signal assignments.
117        [SignalNameMap],       -- The signal names corresponding to
118                                          -- the expression's arguments
119        SignalNameMap)         -- The signal names corresponding to
120                                          -- the expression's result.
121 expandExpr binds lam@(Lam b expr) = do
122   -- Generate a new signal to which we will expect this argument to be bound.
123   signal_name <- uniqueName ("arg_" ++ getOccString b)
124   -- Find the type of the binder
125   let (arg_ty, _) = Type.splitFunTy (CoreUtils.exprType lam)
126   -- Create signal names for the binder
127   -- TODO: We assume arguments are ports here
128   let arg_signal = getPortNameMapForTy signal_name arg_ty (useAsPort arg_ty)
129   -- Create the corresponding signal declarations
130   let signal_decls = mkSignalsFromMap arg_signal
131   -- Add the binder to the list of binds
132   let binds' = (b, arg_signal) : binds
133   -- Expand the rest of the expression
134   (signal_decls', statements', arg_signals', res_signal') <- expandExpr binds' expr
135   -- Properly merge the results
136   return (signal_decls ++ signal_decls',
137           statements',
138           arg_signal : arg_signals',
139           res_signal')
140
141 expandExpr binds (Var id) =
142   return ([], [], [], bind)
143   where
144     -- Lookup the id in our binds map
145     bind = Maybe.fromMaybe
146       (error $ "Argument " ++ getOccString id ++ "is unknown")
147       (lookup id binds)
148
149 expandExpr binds l@(Let (NonRec b bexpr) expr) = do
150   (signal_decls, statements, arg_signals, res_signals) <- expandExpr binds bexpr
151   let binds' = (b, res_signals) : binds
152   (signal_decls', statements', arg_signals', res_signals') <- expandExpr binds' expr
153   return (
154     signal_decls ++ signal_decls',
155     statements ++ statements',
156     arg_signals',
157     res_signals')
158
159 expandExpr binds app@(App _ _) = do
160   -- Is this a data constructor application?
161   case CoreUtils.exprIsConApp_maybe app of
162     -- Is this a tuple construction?
163     Just (dc, args) -> if DataCon.isTupleCon dc 
164       then
165         expandBuildTupleExpr binds (dataConAppArgs dc args)
166       else
167         error "Data constructors other than tuples not supported"
168     otherise ->
169       -- Normal function application, should map to a component instantiation
170       let ((Var f), args) = collectArgs app in
171       expandApplicationExpr binds (CoreUtils.exprType app) f args
172
173 expandExpr binds expr@(Case (Var v) b _ alts) =
174   case alts of
175     [alt] -> expandSingleAltCaseExpr binds v b alt
176     otherwise -> error $ "Multiple alternative case expression not supported: " ++ (showSDoc $ ppr expr)
177
178 expandExpr binds expr@(Case _ b _ _) =
179   error $ "Case expression with non-variable scrutinee not supported: " ++ (showSDoc $ ppr expr)
180
181 expandExpr binds expr = 
182   error $ "Unsupported expression: " ++ (showSDoc $ ppr $ expr)
183
184 -- Expands the construction of a tuple into VHDL
185 expandBuildTupleExpr ::
186   [(CoreBndr, SignalNameMap)] 
187                                          -- A list of bindings in effect
188   -> [CoreExpr]                          -- A list of expressions to put in the tuple
189   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
190                                          -- See expandExpr
191 expandBuildTupleExpr binds args = do
192   -- Split the tuple constructor arguments into types and actual values.
193   -- Expand each of the values in the tuple
194   (signals_declss, statementss, arg_signalss, res_signals) <-
195     (Monad.liftM List.unzip4) $ mapM (expandExpr binds) args
196   if any (not . null) arg_signalss
197     then error "Putting high order functions in tuples not supported"
198     else
199       return (
200         concat signals_declss,
201         concat statementss,
202         [],
203         Tuple res_signals)
204
205 -- Expands the most simple case expression that scrutinizes a plain variable
206 -- and has a single alternative. This simple form currently allows only for
207 -- unpacking tuple variables.
208 expandSingleAltCaseExpr ::
209   [(CoreBndr, SignalNameMap)] 
210                             -- A list of bindings in effect
211   -> Var.Var                -- The scrutinee
212   -> CoreBndr               -- The binder to bind the scrutinee to
213   -> CoreAlt                -- The single alternative
214   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
215                                          -- See expandExpr
216
217 expandSingleAltCaseExpr binds v b alt@(DataAlt datacon, bind_vars, expr) =
218   if not (DataCon.isTupleCon datacon) 
219     then
220       error $ "Dataconstructors other than tuple constructors not supported in case pattern of alternative: " ++ (showSDoc $ ppr alt)
221     else
222       let
223         -- Lookup the scrutinee (which must be a variable bound to a tuple) in
224         -- the existing bindings list and get the portname map for each of
225         -- it's elements.
226         Tuple tuple_ports = Maybe.fromMaybe 
227           (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
228           (lookup v binds)
229         -- TODO include b in the binds list
230         -- Merge our existing binds with the new binds.
231         binds' = (zip bind_vars tuple_ports) ++ binds 
232       in
233         -- Expand the expression with the new binds list
234         expandExpr binds' expr
235
236 expandSingleAltCaseExpr _ _ _ alt =
237   error $ "Case patterns other than data constructors not supported in case alternative: " ++ (showSDoc $ ppr alt)
238       
239
240 -- Expands the application of argument to a function into VHDL
241 expandApplicationExpr ::
242   [(CoreBndr, SignalNameMap)] 
243                                          -- A list of bindings in effect
244   -> Type                                -- The result type of the function call
245   -> Var.Var                             -- The function to call
246   -> [CoreExpr]                          -- A list of argumetns to apply to the function
247   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
248                                          -- See expandExpr
249 expandApplicationExpr binds ty f args = do
250   let name = getOccString f
251   -- Generate a unique name for the application
252   appname <- uniqueName ("app_" ++ name)
253   -- Lookup the hwfunction to instantiate
254   HWFunction vhdl_id inports outport <- getHWFunc (appToHsFunction f args ty)
255   -- Expand each of the args, so each of them is reduced to output signals
256   (arg_signal_decls, arg_statements, arg_res_signals) <- expandArgs binds args
257   -- Bind each of the input ports to the expanded arguments
258   let inmaps = concat $ zipWith createAssocElems inports arg_res_signals
259   -- Create signal names for our result
260   -- TODO: We assume the result is a port here
261   let res_signal = getPortNameMapForTy (appname ++ "_out") ty (useAsPort ty)
262   -- Create the corresponding signal declarations
263   let signal_decls = mkSignalsFromMap res_signal
264   -- Bind each of the output ports to our output signals
265   let outmaps = mapOutputPorts outport res_signal
266   -- Instantiate the component
267   let component = AST.CSISm $ AST.CompInsSm
268         (AST.unsafeVHDLBasicId appname)
269         (AST.IUEntity (AST.NSimple vhdl_id))
270         (AST.PMapAspect (inmaps ++ outmaps))
271   -- Merge the generated declarations
272   return (
273     signal_decls ++ arg_signal_decls,
274     component : arg_statements,
275     [], -- We don't take any extra arguments; we don't support higher order functions yet
276     res_signal)
277   
278 -- Creates a list of AssocElems (port map lines) that maps the given signals
279 -- to the given ports.
280 createAssocElems ::
281   SignalNameMap      -- The port names to bind to
282   -> SignalNameMap   -- The signals to bind to it
283   -> [AST.AssocElem]            -- The resulting port map lines
284   
285 createAssocElems (Single (port_id, _)) (Single (signal_id, _)) = 
286   [(Just port_id) AST.:=>: (AST.ADName (AST.NSimple signal_id))]
287
288 createAssocElems (Tuple ports) (Tuple signals) = 
289   concat $ zipWith createAssocElems ports signals
290
291 -- Generate a signal declaration for a signal with the given name and the
292 -- given type and no value. Also returns the id of the signal.
293 mkSignal :: String -> AST.TypeMark -> (AST.VHDLId, AST.SigDec)
294 mkSignal name ty =
295   (id, mkSignalFromId id ty)
296   where 
297     id = AST.unsafeVHDLBasicId name
298
299 mkSignalFromId :: AST.VHDLId -> AST.TypeMark -> AST.SigDec
300 mkSignalFromId id ty =
301   AST.SigDec id ty Nothing
302
303 -- Generates signal declarations for all the signals in the given map
304 mkSignalsFromMap ::
305   SignalNameMap 
306   -> [AST.SigDec]
307
308 mkSignalsFromMap (Single (id, ty)) =
309   [mkSignalFromId id ty]
310
311 mkSignalsFromMap (Tuple signals) =
312   concat $ map mkSignalsFromMap signals
313
314 expandArgs :: 
315   [(CoreBndr, SignalNameMap)] -- A list of bindings in effect
316   -> [CoreExpr]                          -- The arguments to expand
317   -> VHDLState ([AST.SigDec], [AST.ConcSm], [SignalNameMap])  
318                                          -- The resulting signal declarations,
319                                          -- component instantiations and a
320                                          -- VHDLName for each of the
321                                          -- expressions passed in.
322 expandArgs binds (e:exprs) = do
323   -- Expand the first expression
324   (signal_decls, statements, arg_signals, res_signal) <- expandExpr binds e
325   if not (null arg_signals)
326     then error $ "Passing functions as arguments not supported: " ++ (showSDoc $ ppr e)
327     else do
328       (signal_decls', statements', res_signals') <- expandArgs binds exprs
329       return (
330         signal_decls ++ signal_decls',
331         statements ++ statements',
332         res_signal : res_signals')
333
334 expandArgs _ [] = return ([], [], [])
335
336 -- Extract the arguments from a data constructor application (that is, the
337 -- normal args, leaving out the type args).
338 dataConAppArgs :: DataCon -> [CoreExpr] -> [CoreExpr]
339 dataConAppArgs dc args =
340     drop tycount args
341   where
342     tycount = length $ DataCon.dataConAllTyVars dc
343
344 mapOutputPorts ::
345   SignalNameMap      -- The output portnames of the component
346   -> SignalNameMap   -- The output portnames and/or signals to map these to
347   -> [AST.AssocElem]            -- The resulting output ports
348
349 -- Map the output port of a component to the output port of the containing
350 -- entity.
351 mapOutputPorts (Single (portname, _)) (Single (signalname, _)) =
352   [(Just portname) AST.:=>: (AST.ADName (AST.NSimple signalname))]
353
354 -- Map matching output ports in the tuple
355 mapOutputPorts (Tuple ports) (Tuple signals) =
356   concat (zipWith mapOutputPorts ports signals)
357
358 expandBind ::
359   CoreBind                        -- The binder to expand into VHDL
360   -> VHDLState [AST.LibraryUnit]  -- The resulting VHDL
361
362 expandBind (Rec _) = error "Recursive binders not supported"
363
364 expandBind bind@(NonRec var expr) = do
365   -- Create the function signature
366   let ty = CoreUtils.exprType expr
367   let hsfunc = mkHsFunction var ty
368   hwfunc <- mkHWFunction bind hsfunc
369   -- Add it to the session
370   addFunc hsfunc hwfunc 
371   arch <- getArchitecture hsfunc hwfunc expr
372   -- Give every entity a clock port
373   -- TODO: Omit this for stateless entities
374   let clk_port = AST.IfaceSigDec (mkVHDLId "clk") AST.In vhdl_bit_ty
375   let entity = getEntity hwfunc [clk_port]
376   return $ [
377     AST.LUEntity entity,
378     AST.LUArch arch ]
379
380 getArchitecture ::
381   HsFunction                -- The function interface
382   -> HWFunction             -- The function to generate an architecture for
383   -> CoreExpr               -- The expression that is bound to the function
384   -> VHDLState AST.ArchBody -- The resulting architecture
385    
386 getArchitecture hsfunc hwfunc expr = do
387   -- Unpack our hwfunc
388   let HWFunction vhdl_id inports outport = hwfunc
389   -- Expand the expression into an architecture body
390   (signal_decls, statements, arg_signals, res_signal) <- expandExpr [] expr
391   let (inport_assigns, instate_map)  = concat_elements $ unzip $ zipWith3 createSignalAssignments arg_signals inports (hsArgs hsfunc)
392   let (outport_assigns, outstate_map) = createSignalAssignments outport res_signal (hsRes hsfunc)
393   let state_procs = map AST.CSPSm $ createStateProcs (sortMap instate_map) (sortMap outstate_map)
394   return $ AST.ArchBody
395     (AST.unsafeVHDLBasicId "structural")
396     (AST.NSimple vhdl_id)
397     (map AST.BDISD signal_decls)
398     (state_procs ++ inport_assigns ++ outport_assigns ++ statements)
399
400 -- | Sorts a map modeled as a list of (key,value) pairs by key
401 sortMap :: Ord a => [(a, b)] -> [(a, b)]
402 sortMap = List.sortBy (\(a, _) (b, _) -> compare a b)
403
404 -- | Generate procs for state variables
405 createStateProcs ::
406   [(Int, AST.VHDLId)]
407                     -- ^ The sorted list of signals that should be assigned
408                     --   to each state
409   -> [(Int, AST.VHDLId)]   
410                     -- ^ The sorted list of signals that contain each new state
411   -> [AST.ProcSm]   -- ^ The resulting procs
412
413 createStateProcs ((old_num, old_id):olds) ((new_num, new_id):news) =
414   if (old_num == new_num)
415     then
416       AST.ProcSm label [clk] [statement] : createStateProcs olds news
417     else
418       error "State numbers don't match!"
419   where
420     label       = mkVHDLId $ "state_" ++ (show old_num)
421     clk         = mkVHDLId "clk"
422     rising_edge = AST.NSimple $ mkVHDLId "rising_edge"
423     wform       = AST.Wform [AST.WformElem (AST.PrimName $ AST.NSimple $ new_id) Nothing]
424     assign      = AST.SigAssign (AST.NSimple old_id) wform
425     rising_edge_clk = AST.PrimFCall $ AST.FCall rising_edge [Nothing AST.:=>: (AST.ADName $ AST.NSimple clk)]
426     statement   = AST.IfSm rising_edge_clk [assign] [] Nothing
427
428 createStateProcs [] [] = []
429
430 -- Generate a VHDL entity declaration for the given function
431 getEntity :: HWFunction -> [AST.IfaceSigDec] -> AST.EntityDec  
432 getEntity (HWFunction vhdl_id inports outport) extra_ports = 
433   AST.EntityDec vhdl_id ports
434   where
435     ports = 
436       (concat $ map (mkIfaceSigDecs AST.In) inports)
437       ++ mkIfaceSigDecs AST.Out outport
438       ++ extra_ports
439
440 mkIfaceSigDecs ::
441   AST.Mode                        -- The port's mode (In or Out)
442   -> SignalNameMap        -- The ports to generate a map for
443   -> [AST.IfaceSigDec]            -- The resulting ports
444   
445 mkIfaceSigDecs mode (Single (port_id, ty)) =
446   [AST.IfaceSigDec port_id mode ty]
447
448 mkIfaceSigDecs mode (Tuple ports) =
449   concat $ map (mkIfaceSigDecs mode) ports
450
451 -- Unused values (state) don't generate ports
452 mkIfaceSigDecs mode Unused =
453   []
454
455 -- Create concurrent assignments of one map of signals to another. The maps
456 -- should have a similar form.
457 createSignalAssignments ::
458   SignalNameMap           -- The signals to assign to
459   -> SignalNameMap        -- The signals to assign
460   -> HsUseMap             -- What function does each of the signals have?
461   -> ([AST.ConcSm],       -- The resulting assignments
462       [(Int, AST.VHDLId)]) -- The resulting state -> signal mappings
463
464 -- A simple assignment of one signal to another (greatly complicated because
465 -- signal assignments can be conditional with multiple conditions in VHDL).
466 createSignalAssignments (Single (dst, _)) (Single (src, _)) (Single Port)=
467     ([AST.CSSASm assign], [])
468   where
469     src_name  = AST.NSimple src
470     src_expr  = AST.PrimName src_name
471     src_wform = AST.Wform [AST.WformElem src_expr Nothing]
472     dst_name  = (AST.NSimple dst)
473     assign    = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
474
475 createSignalAssignments (Tuple dsts) (Tuple srcs) (Tuple uses) =
476   concat_elements $ unzip $ zipWith3 createSignalAssignments dsts srcs uses
477
478 createSignalAssignments Unused (Single (src, _)) (Single (State n)) =
479   -- Write state
480   ([], [(n, src)])
481
482 createSignalAssignments (Single (dst, _)) Unused (Single (State n)) =
483   -- Read state
484   ([], [(n, dst)])
485
486 createSignalAssignments dst src use =
487   error $ "Non matching source and destination: " ++ show dst ++ " <= " ++  show src ++ " (Used as " ++ show use ++ ")"
488
489 type SignalNameMap = HsValueMap (AST.VHDLId, AST.TypeMark)
490
491 -- | A datatype that maps each of the single values in a haskell structure to
492 -- a mapto. The map has the same structure as the haskell type mapped, ie
493 -- nested tuples etc.
494 data HsValueMap mapto =
495   Tuple [HsValueMap mapto]
496   | Single mapto
497   | Unused
498   deriving (Show, Eq)
499
500 -- | Creates a HsValueMap with the same structure as the given type, using the
501 --   given function for mapping the single types.
502 mkHsValueMap ::
503   ((Type, s) -> (HsValueMap mapto, s))
504                                 -- ^ A function to map single value Types
505                                 --   (basically anything but tuples) to a
506                                 --   HsValueMap (not limited to the Single
507                                 --   constructor) Also accepts and produces a
508                                 --   state that will be passed on between
509                                 --   each call to the function.
510   -> s                          -- ^ The initial state
511   -> Type                       -- ^ The type to map to a HsValueMap
512   -> (HsValueMap mapto, s)      -- ^ The resulting map and state
513
514 mkHsValueMap f s ty =
515   case Type.splitTyConApp_maybe ty of
516     Just (tycon, args) ->
517       if (TyCon.isTupleTyCon tycon) 
518         then
519           let (args', s') = mapTuple f s args in
520           -- Handle tuple construction especially
521           (Tuple args', s')
522         else
523           -- And let f handle the rest
524           f (ty, s)
525     -- And let f handle the rest
526     Nothing -> f (ty, s)
527   where
528     mapTuple f s (ty:tys) =
529       let (map, s') = mkHsValueMap f s ty in
530       let (maps, s'') = mapTuple f s' tys in
531       (map: maps, s'')
532     mapTuple f s [] = ([], s)
533
534 -- Generate a port name map (or multiple for tuple types) in the given direction for
535 -- each type given.
536 getPortNameMapForTys :: String -> Int -> [Type] -> [HsUseMap] -> [SignalNameMap]
537 getPortNameMapForTys prefix num [] [] = [] 
538 getPortNameMapForTys prefix num (t:ts) (u:us) =
539   (getPortNameMapForTy (prefix ++ show num) t u) : getPortNameMapForTys prefix (num + 1) ts us
540
541 getPortNameMapForTy :: String -> Type -> HsUseMap -> SignalNameMap
542 getPortNameMapForTy name _ (Single (State _)) =
543   Unused
544
545 getPortNameMapForTy name ty use =
546   if (TyCon.isTupleTyCon tycon) then
547     let (Tuple uses) = use in
548     -- Expand tuples we find
549     Tuple (getPortNameMapForTys name 0 args uses)
550   else -- Assume it's a type constructor application, ie simple data type
551     Single ((AST.unsafeVHDLBasicId name), (vhdl_ty ty))
552   where
553     (tycon, args) = Type.splitTyConApp ty 
554
555 data HWFunction = HWFunction { -- A function that is available in hardware
556   vhdlId    :: AST.VHDLId,
557   inPorts   :: [SignalNameMap],
558   outPort   :: SignalNameMap
559   --entity    :: AST.EntityDec
560 } deriving (Show)
561
562 -- Turns a CoreExpr describing a function into a description of its input and
563 -- output ports.
564 mkHWFunction ::
565   CoreBind                                   -- The core binder to generate the interface for
566   -> HsFunction                              -- The HsFunction describing the function
567   -> VHDLState HWFunction                    -- The function interface
568
569 mkHWFunction (NonRec var expr) hsfunc =
570     return $ HWFunction (mkVHDLId name) inports outport
571   where
572     name = getOccString var
573     ty = CoreUtils.exprType expr
574     (args, res) = Type.splitFunTys ty
575     inports = case args of
576       -- Handle a single port specially, to prevent an extra 0 in the name
577       [port] -> [getPortNameMapForTy "portin" port (head $ hsArgs hsfunc)]
578       ps     -> getPortNameMapForTys "portin" 0 ps (hsArgs hsfunc)
579     outport = getPortNameMapForTy "portout" res (hsRes hsfunc)
580
581 mkHWFunction (Rec _) _ =
582   error "Recursive binders not supported"
583
584 -- | How is a given (single) value in a function's type (ie, argument or
585 -- return value) used?
586 data HsValueUse = 
587   Port        -- ^ Use it as a port (input or output)
588   | State Int -- ^ Use it as state (input or output). The int is used to
589               --   match input state to output state.
590   deriving (Show, Eq)
591
592 useAsPort :: Type -> HsUseMap
593 useAsPort = fst . (mkHsValueMap (\(ty, s) -> (Single Port, s)) 0)
594 useAsState :: Type -> HsUseMap
595 useAsState = fst . (mkHsValueMap (\(ty, s) -> (Single $ State s, s + 1)) 0)
596
597 type HsUseMap = HsValueMap HsValueUse
598
599 -- | This type describes a particular use of a Haskell function and is used to
600 --   look up an appropriate hardware description.  
601 data HsFunction = HsFunction {
602   hsName :: String,                      -- ^ What was the name of the original Haskell function?
603   hsArgs :: [HsUseMap],                  -- ^ How are the arguments used?
604   hsRes  :: HsUseMap                     -- ^ How is the result value used?
605 } deriving (Show, Eq)
606
607 -- | Translate a function application to a HsFunction. i.e., which function
608 --   do you need to translate this function application.
609 appToHsFunction ::
610   Var.Var         -- ^ The function to call
611   -> [CoreExpr]   -- ^ The function arguments
612   -> Type         -- ^ The return type
613   -> HsFunction   -- ^ The needed HsFunction
614
615 appToHsFunction f args ty =
616   HsFunction hsname hsargs hsres
617   where
618     hsargs = map (useAsPort . CoreUtils.exprType) args
619     hsres  = useAsPort ty
620     hsname = getOccString f
621
622 -- | Translate a top level function declaration to a HsFunction. i.e., which
623 --   interface will be provided by this function. This function essentially
624 --   defines the "calling convention" for hardware models.
625 mkHsFunction ::
626   Var.Var         -- ^ The function defined
627   -> Type         -- ^ The function type (including arguments!)
628   -> HsFunction   -- ^ The resulting HsFunction
629
630 mkHsFunction f ty =
631   HsFunction hsname hsargs hsres
632   where
633     hsname  = getOccString f
634     (arg_tys, res_ty) = Type.splitFunTys ty
635     -- The last argument must be state
636     state_ty = last arg_tys
637     state    = useAsState state_ty
638     -- All but the last argument are inports
639     inports = map useAsPort (init arg_tys)
640     hsargs   = inports ++ [state]
641     hsres    = case splitTupleType res_ty of
642       -- Result type must be a two tuple (state, ports)
643       Just [outstate_ty, outport_ty] -> if Type.coreEqType state_ty outstate_ty
644         then
645           Tuple [state, useAsPort outport_ty]
646         else
647           error $ "Input state type of function " ++ hsname ++ ": " ++ (showSDoc $ ppr state_ty) ++ " does not match output state type: " ++ (showSDoc $ ppr outstate_ty)
648       otherwise                -> error $ "Return type of top-level function " ++ hsname ++ " must be a two-tuple containing a state and output ports."
649
650 data VHDLSession = VHDLSession {
651   nameCount :: Int,                       -- A counter that can be used to generate unique names
652   funcs     :: [(HsFunction, HWFunction)] -- All functions available
653 } deriving (Show)
654
655 type VHDLState = State.State VHDLSession
656
657 -- Add the function to the session
658 addFunc :: HsFunction -> HWFunction -> VHDLState ()
659 addFunc hsfunc hwfunc = do
660   fs <- State.gets funcs -- Get the funcs element from the session
661   State.modify (\x -> x {funcs = (hsfunc, hwfunc) : fs }) -- Prepend name and f
662
663 -- Lookup the function with the given name in the current session. Errors if
664 -- it was not found.
665 getHWFunc :: HsFunction -> VHDLState HWFunction
666 getHWFunc hsfunc = do
667   fs <- State.gets funcs -- Get the funcs element from the session
668   return $ Maybe.fromMaybe
669     (error $ "Function " ++ (hsName hsfunc) ++ "is unknown? This should not happen!")
670     (lookup hsfunc fs)
671
672 -- | Splits a tuple type into a list of element types, or Nothing if the type
673 --   is not a tuple type.
674 splitTupleType ::
675   Type              -- ^ The type to split
676   -> Maybe [Type]   -- ^ The tuples element types
677
678 splitTupleType ty =
679   case Type.splitTyConApp_maybe ty of
680     Just (tycon, args) -> if TyCon.isTupleTyCon tycon 
681       then
682         Just args
683       else
684         Nothing
685     Nothing -> Nothing
686
687 -- Makes the given name unique by appending a unique number.
688 -- This does not do any checking against existing names, so it only guarantees
689 -- uniqueness with other names generated by uniqueName.
690 uniqueName :: String -> VHDLState String
691 uniqueName name = do
692   count <- State.gets nameCount -- Get the funcs element from the session
693   State.modify (\s -> s {nameCount = count + 1})
694   return $ name ++ "_" ++ (show count)
695
696 -- Shortcut
697 mkVHDLId :: String -> AST.VHDLId
698 mkVHDLId = AST.unsafeVHDLBasicId
699
700 -- Concatenate each of the lists of lists inside the given tuple.
701 -- Since the element types in the lists might differ, we can't generalize
702 -- this (unless we pass in f twice).
703 concat_elements :: ([[a]], [[b]]) -> ([a], [b])
704 concat_elements (a, b) = (concat a, concat b)
705
706 builtin_funcs = 
707   [ 
708     (HsFunction "hwxor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwxor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
709     (HsFunction "hwand" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwand") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
710     (HsFunction "hwor" [(Single Port), (Single Port)] (Single Port), HWFunction (mkVHDLId "hwor") [Single (mkVHDLId "a", vhdl_bit_ty), Single (mkVHDLId "b", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty))),
711     (HsFunction "hwnot" [(Single Port)] (Single Port), HWFunction (mkVHDLId "hwnot") [Single (mkVHDLId "i", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty)))
712   ]
713
714 vhdl_bit_ty :: AST.TypeMark
715 vhdl_bit_ty = AST.unsafeVHDLBasicId "Bit"
716
717 -- Translate a Haskell type to a VHDL type
718 vhdl_ty :: Type -> AST.TypeMark
719 vhdl_ty ty = Maybe.fromMaybe
720   (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
721   (vhdl_ty_maybe ty)
722
723 -- Translate a Haskell type to a VHDL type
724 vhdl_ty_maybe :: Type -> Maybe AST.TypeMark
725 vhdl_ty_maybe ty =
726   case Type.splitTyConApp_maybe ty of
727     Just (tycon, args) ->
728       let name = TyCon.tyConName tycon in
729         -- TODO: Do something more robust than string matching
730         case getOccString name of
731           "Bit"      -> Just vhdl_bit_ty
732           otherwise  -> Nothing
733     otherwise -> Nothing
734
735 -- vim: set ts=8 sw=2 sts=2 expandtab: