Print the final session after the output.
[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)) ["shalf_adder"]
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   let arg_signal = getPortNameMapForTy ("xxx") arg_ty
128   -- Create the corresponding signal declarations
129   let signal_decls = mkSignalsFromMap arg_signal
130   -- Add the binder to the list of binds
131   let binds' = (b, arg_signal) : binds
132   -- Expand the rest of the expression
133   (signal_decls', statements', arg_signals', res_signal') <- expandExpr binds' expr
134   -- Properly merge the results
135   return (signal_decls ++ signal_decls',
136           statements',
137           arg_signal : arg_signals',
138           res_signal')
139
140 expandExpr binds (Var id) =
141   return ([], [], [], bind)
142   where
143     -- Lookup the id in our binds map
144     bind = Maybe.fromMaybe
145       (error $ "Argument " ++ getOccString id ++ "is unknown")
146       (lookup id binds)
147
148 expandExpr binds l@(Let (NonRec b bexpr) expr) = do
149   (signal_decls, statements, arg_signals, res_signals) <- expandExpr binds bexpr
150   let binds' = (b, res_signals) : binds
151   (signal_decls', statements', arg_signals', res_signals') <- expandExpr binds' expr
152   return (
153     signal_decls ++ signal_decls',
154     statements ++ statements',
155     arg_signals',
156     res_signals')
157
158 expandExpr binds app@(App _ _) = do
159   -- Is this a data constructor application?
160   case CoreUtils.exprIsConApp_maybe app of
161     -- Is this a tuple construction?
162     Just (dc, args) -> if DataCon.isTupleCon dc 
163       then
164         expandBuildTupleExpr binds (dataConAppArgs dc args)
165       else
166         error "Data constructors other than tuples not supported"
167     otherise ->
168       -- Normal function application, should map to a component instantiation
169       let ((Var f), args) = collectArgs app in
170       expandApplicationExpr binds (CoreUtils.exprType app) f args
171
172 expandExpr binds expr@(Case (Var v) b _ alts) =
173   case alts of
174     [alt] -> expandSingleAltCaseExpr binds v b alt
175     otherwise -> error $ "Multiple alternative case expression not supported: " ++ (showSDoc $ ppr expr)
176
177 expandExpr binds expr@(Case _ b _ _) =
178   error $ "Case expression with non-variable scrutinee not supported: " ++ (showSDoc $ ppr expr)
179
180 expandExpr binds expr = 
181   error $ "Unsupported expression: " ++ (showSDoc $ ppr $ expr)
182
183 -- Expands the construction of a tuple into VHDL
184 expandBuildTupleExpr ::
185   [(CoreBndr, SignalNameMap)] 
186                                          -- A list of bindings in effect
187   -> [CoreExpr]                          -- A list of expressions to put in the tuple
188   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
189                                          -- See expandExpr
190 expandBuildTupleExpr binds args = do
191   -- Split the tuple constructor arguments into types and actual values.
192   -- Expand each of the values in the tuple
193   (signals_declss, statementss, arg_signalss, res_signals) <-
194     (Monad.liftM List.unzip4) $ mapM (expandExpr binds) args
195   if any (not . null) arg_signalss
196     then error "Putting high order functions in tuples not supported"
197     else
198       return (
199         concat signals_declss,
200         concat statementss,
201         [],
202         Tuple res_signals)
203
204 -- Expands the most simple case expression that scrutinizes a plain variable
205 -- and has a single alternative. This simple form currently allows only for
206 -- unpacking tuple variables.
207 expandSingleAltCaseExpr ::
208   [(CoreBndr, SignalNameMap)] 
209                             -- A list of bindings in effect
210   -> Var.Var                -- The scrutinee
211   -> CoreBndr               -- The binder to bind the scrutinee to
212   -> CoreAlt                -- The single alternative
213   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
214                                          -- See expandExpr
215
216 expandSingleAltCaseExpr binds v b alt@(DataAlt datacon, bind_vars, expr) =
217   if not (DataCon.isTupleCon datacon) 
218     then
219       error $ "Dataconstructors other than tuple constructors not supported in case pattern of alternative: " ++ (showSDoc $ ppr alt)
220     else
221       let
222         -- Lookup the scrutinee (which must be a variable bound to a tuple) in
223         -- the existing bindings list and get the portname map for each of
224         -- it's elements.
225         Tuple tuple_ports = Maybe.fromMaybe 
226           (error $ "Case expression uses unknown scrutinee " ++ getOccString v)
227           (lookup v binds)
228         -- TODO include b in the binds list
229         -- Merge our existing binds with the new binds.
230         binds' = (zip bind_vars tuple_ports) ++ binds 
231       in
232         -- Expand the expression with the new binds list
233         expandExpr binds' expr
234
235 expandSingleAltCaseExpr _ _ _ alt =
236   error $ "Case patterns other than data constructors not supported in case alternative: " ++ (showSDoc $ ppr alt)
237       
238
239 -- Expands the application of argument to a function into VHDL
240 expandApplicationExpr ::
241   [(CoreBndr, SignalNameMap)] 
242                                          -- A list of bindings in effect
243   -> Type                                -- The result type of the function call
244   -> Var.Var                             -- The function to call
245   -> [CoreExpr]                          -- A list of argumetns to apply to the function
246   -> VHDLState ( [AST.SigDec], [AST.ConcSm], [SignalNameMap], SignalNameMap)
247                                          -- See expandExpr
248 expandApplicationExpr binds ty f args = do
249   let name = getOccString f
250   -- Generate a unique name for the application
251   appname <- uniqueName ("app_" ++ name)
252   -- Lookup the hwfunction to instantiate
253   HWFunction vhdl_id inports outport <- getHWFunc (appToHsFunction f args ty)
254   -- Expand each of the args, so each of them is reduced to output signals
255   (arg_signal_decls, arg_statements, arg_res_signals) <- expandArgs binds args
256   -- Bind each of the input ports to the expanded arguments
257   let inmaps = concat $ zipWith createAssocElems inports arg_res_signals
258   -- Create signal names for our result
259   let res_signal = getPortNameMapForTy (appname ++ "_out") ty
260   -- Create the corresponding signal declarations
261   let signal_decls = mkSignalsFromMap res_signal
262   -- Bind each of the output ports to our output signals
263   let outmaps = mapOutputPorts outport res_signal
264   -- Instantiate the component
265   let component = AST.CSISm $ AST.CompInsSm
266         (AST.unsafeVHDLBasicId appname)
267         (AST.IUEntity (AST.NSimple vhdl_id))
268         (AST.PMapAspect (inmaps ++ outmaps))
269   -- Merge the generated declarations
270   return (
271     signal_decls ++ arg_signal_decls,
272     component : arg_statements,
273     [], -- We don't take any extra arguments; we don't support higher order functions yet
274     res_signal)
275   
276 -- Creates a list of AssocElems (port map lines) that maps the given signals
277 -- to the given ports.
278 createAssocElems ::
279   SignalNameMap      -- The port names to bind to
280   -> SignalNameMap   -- The signals to bind to it
281   -> [AST.AssocElem]            -- The resulting port map lines
282   
283 createAssocElems (Single (port_id, _)) (Single (signal_id, _)) = 
284   [(Just port_id) AST.:=>: (AST.ADName (AST.NSimple signal_id))]
285
286 createAssocElems (Tuple ports) (Tuple signals) = 
287   concat $ zipWith createAssocElems ports signals
288
289 -- Generate a signal declaration for a signal with the given name and the
290 -- given type and no value. Also returns the id of the signal.
291 mkSignal :: String -> AST.TypeMark -> (AST.VHDLId, AST.SigDec)
292 mkSignal name ty =
293   (id, mkSignalFromId id ty)
294   where 
295     id = AST.unsafeVHDLBasicId name
296
297 mkSignalFromId :: AST.VHDLId -> AST.TypeMark -> AST.SigDec
298 mkSignalFromId id ty =
299   AST.SigDec id ty Nothing
300
301 -- Generates signal declarations for all the signals in the given map
302 mkSignalsFromMap ::
303   SignalNameMap 
304   -> [AST.SigDec]
305
306 mkSignalsFromMap (Single (id, ty)) =
307   [mkSignalFromId id ty]
308
309 mkSignalsFromMap (Tuple signals) =
310   concat $ map mkSignalsFromMap signals
311
312 expandArgs :: 
313   [(CoreBndr, SignalNameMap)] -- A list of bindings in effect
314   -> [CoreExpr]                          -- The arguments to expand
315   -> VHDLState ([AST.SigDec], [AST.ConcSm], [SignalNameMap])  
316                                          -- The resulting signal declarations,
317                                          -- component instantiations and a
318                                          -- VHDLName for each of the
319                                          -- expressions passed in.
320 expandArgs binds (e:exprs) = do
321   -- Expand the first expression
322   (signal_decls, statements, arg_signals, res_signal) <- expandExpr binds e
323   if not (null arg_signals)
324     then error $ "Passing functions as arguments not supported: " ++ (showSDoc $ ppr e)
325     else do
326       (signal_decls', statements', res_signals') <- expandArgs binds exprs
327       return (
328         signal_decls ++ signal_decls',
329         statements ++ statements',
330         res_signal : res_signals')
331
332 expandArgs _ [] = return ([], [], [])
333
334 -- Extract the arguments from a data constructor application (that is, the
335 -- normal args, leaving out the type args).
336 dataConAppArgs :: DataCon -> [CoreExpr] -> [CoreExpr]
337 dataConAppArgs dc args =
338     drop tycount args
339   where
340     tycount = length $ DataCon.dataConAllTyVars dc
341
342 mapOutputPorts ::
343   SignalNameMap      -- The output portnames of the component
344   -> SignalNameMap   -- The output portnames and/or signals to map these to
345   -> [AST.AssocElem]            -- The resulting output ports
346
347 -- Map the output port of a component to the output port of the containing
348 -- entity.
349 mapOutputPorts (Single (portname, _)) (Single (signalname, _)) =
350   [(Just portname) AST.:=>: (AST.ADName (AST.NSimple signalname))]
351
352 -- Map matching output ports in the tuple
353 mapOutputPorts (Tuple ports) (Tuple signals) =
354   concat (zipWith mapOutputPorts ports signals)
355
356 expandBind ::
357   CoreBind                        -- The binder to expand into VHDL
358   -> VHDLState [AST.LibraryUnit]  -- The resulting VHDL
359
360 expandBind (Rec _) = error "Recursive binders not supported"
361
362 expandBind bind@(NonRec var expr) = do
363   -- Create the function signature
364   hwfunc <- mkHWFunction bind
365   let ty = CoreUtils.exprType expr
366   let hsfunc = mkHsFunction var ty
367   -- Add it to the session
368   addFunc hsfunc hwfunc 
369   arch <- getArchitecture hwfunc expr
370   let entity = getEntity hwfunc
371   return $ [
372     AST.LUEntity entity,
373     AST.LUArch arch ]
374
375 getArchitecture ::
376   HWFunction                -- The function to generate an architecture for
377   -> CoreExpr               -- The expression that is bound to the function
378   -> VHDLState AST.ArchBody -- The resulting architecture
379    
380 getArchitecture hwfunc expr = do
381   -- Unpack our hwfunc
382   let HWFunction vhdl_id inports outport = hwfunc
383   -- Expand the expression into an architecture body
384   (signal_decls, statements, arg_signals, res_signal) <- expandExpr [] expr
385   let inport_assigns = concat $ zipWith createSignalAssignments arg_signals inports
386   let outport_assigns = createSignalAssignments outport res_signal
387   return $ AST.ArchBody
388     (AST.unsafeVHDLBasicId "structural")
389     (AST.NSimple vhdl_id)
390     (map AST.BDISD signal_decls)
391     (inport_assigns ++ outport_assigns ++ statements)
392
393 -- Generate a VHDL entity declaration for the given function
394 getEntity :: HWFunction -> AST.EntityDec  
395 getEntity (HWFunction vhdl_id inports outport) = 
396   AST.EntityDec vhdl_id ports
397   where
398     ports = 
399       (concat $ map (mkIfaceSigDecs AST.In) inports)
400       ++ mkIfaceSigDecs AST.Out outport
401
402 mkIfaceSigDecs ::
403   AST.Mode                        -- The port's mode (In or Out)
404   -> SignalNameMap        -- The ports to generate a map for
405   -> [AST.IfaceSigDec]            -- The resulting ports
406   
407 mkIfaceSigDecs mode (Single (port_id, ty)) =
408   [AST.IfaceSigDec port_id mode ty]
409
410 mkIfaceSigDecs mode (Tuple ports) =
411   concat $ map (mkIfaceSigDecs mode) ports
412
413 -- Create concurrent assignments of one map of signals to another. The maps
414 -- should have a similar form.
415 createSignalAssignments ::
416   SignalNameMap         -- The signals to assign to
417   -> SignalNameMap      -- The signals to assign
418   -> [AST.ConcSm]                  -- The resulting assignments
419
420 -- A simple assignment of one signal to another (greatly complicated because
421 -- signal assignments can be conditional with multiple conditions in VHDL).
422 createSignalAssignments (Single (dst, _)) (Single (src, _)) =
423     [AST.CSSASm assign]
424   where
425     src_name  = AST.NSimple src
426     src_expr  = AST.PrimName src_name
427     src_wform = AST.Wform [AST.WformElem src_expr Nothing]
428     dst_name  = (AST.NSimple dst)
429     assign    = dst_name AST.:<==: (AST.ConWforms [] src_wform Nothing)
430
431 createSignalAssignments (Tuple dsts) (Tuple srcs) =
432   concat $ zipWith createSignalAssignments dsts srcs
433
434 createSignalAssignments dst src =
435   error $ "Non matching source and destination: " ++ show dst ++ "\nand\n" ++  show src
436
437 type SignalNameMap = HsValueMap (AST.VHDLId, AST.TypeMark)
438
439 -- | A datatype that maps each of the single values in a haskell structure to
440 -- a mapto. The map has the same structure as the haskell type mapped, ie
441 -- nested tuples etc.
442 data HsValueMap mapto =
443   Tuple [HsValueMap mapto]
444   | Single mapto
445   deriving (Show, Eq)
446
447 -- | Creates a HsValueMap with the same structure as the given type, using the
448 --   given function for mapping the single types.
449 mkHsValueMap ::
450   (Type -> HsValueMap mapto)    -- ^ A function to map single value Types
451                                 --   (basically anything but tuples) to a
452                                 --   HsValueMap (not limited to the Single
453                                 --   constructor)
454   -> Type                       -- ^ The type to map to a HsValueMap
455   -> HsValueMap mapto           -- ^ The resulting map
456
457 mkHsValueMap f ty =
458   case Type.splitTyConApp_maybe ty of
459     Just (tycon, args) ->
460       if (TyCon.isTupleTyCon tycon) 
461         then
462           -- Handle tuple construction especially
463           Tuple (map (mkHsValueMap f) args)
464         else
465           -- And let f handle the rest
466           f ty
467     -- And let f handle the rest
468     Nothing -> f ty
469
470 -- Generate a port name map (or multiple for tuple types) in the given direction for
471 -- each type given.
472 getPortNameMapForTys :: String -> Int -> [Type] -> [SignalNameMap]
473 getPortNameMapForTys prefix num [] = [] 
474 getPortNameMapForTys prefix num (t:ts) =
475   (getPortNameMapForTy (prefix ++ show num) t) : getPortNameMapForTys prefix (num + 1) ts
476
477 getPortNameMapForTy :: String -> Type -> SignalNameMap
478 getPortNameMapForTy name ty =
479   if (TyCon.isTupleTyCon tycon) then
480     -- Expand tuples we find
481     Tuple (getPortNameMapForTys name 0 args)
482   else -- Assume it's a type constructor application, ie simple data type
483     Single ((AST.unsafeVHDLBasicId name), (vhdl_ty ty))
484   where
485     (tycon, args) = Type.splitTyConApp ty 
486
487 data HWFunction = HWFunction { -- A function that is available in hardware
488   vhdlId    :: AST.VHDLId,
489   inPorts   :: [SignalNameMap],
490   outPort   :: SignalNameMap
491   --entity    :: AST.EntityDec
492 } deriving (Show)
493
494 -- Turns a CoreExpr describing a function into a description of its input and
495 -- output ports.
496 mkHWFunction ::
497   CoreBind                                   -- The core binder to generate the interface for
498   -> VHDLState HWFunction                    -- The function interface
499
500 mkHWFunction (NonRec var expr) =
501     return $ HWFunction (mkVHDLId name) inports outport
502   where
503     name = getOccString var
504     ty = CoreUtils.exprType expr
505     (fargs, res) = Type.splitFunTys ty
506     args = if length fargs == 1 then fargs else (init fargs)
507     --state = if length fargs == 1 then () else (last fargs)
508     inports = case args of
509       -- Handle a single port specially, to prevent an extra 0 in the name
510       [port] -> [getPortNameMapForTy "portin" port]
511       ps     -> getPortNameMapForTys "portin" 0 ps
512     outport = getPortNameMapForTy "portout" res
513
514 mkHWFunction (Rec _) =
515   error "Recursive binders not supported"
516
517 -- | How is a given (single) value in a function's type (ie, argument or
518 -- return value) used?
519 data HsValueUse = 
520   Port -- ^ Use it as a port (input or output)
521   | State --- ^ Use it as state (input or output)
522   deriving (Show, Eq)
523
524 -- | This type describes a particular use of a Haskell function and is used to
525 --   look up an appropriate hardware description.  
526 data HsFunction = HsFunction {
527   hsName :: String,                      -- ^ What was the name of the original Haskell function?
528   hsArgs :: [HsValueMap HsValueUse],     -- ^ How are the arguments used?
529   hsRes  :: HsValueMap HsValueUse        -- ^ How is the result value used?
530 } deriving (Show, Eq)
531
532 -- | Translate a function application to a HsFunction. i.e., which function
533 --   do you need to translate this function application.
534 appToHsFunction ::
535   Var.Var         -- ^ The function to call
536   -> [CoreExpr]   -- ^ The function arguments
537   -> Type         -- ^ The return type
538   -> HsFunction   -- ^ The needed HsFunction
539
540 appToHsFunction f args ty =
541   HsFunction hsname hsargs hsres
542   where
543     mkPort = \x -> Single Port
544     hsargs = map (mkHsValueMap mkPort . CoreUtils.exprType) args
545     hsres  = mkHsValueMap mkPort ty
546     hsname = getOccString f
547
548 -- | Translate a top level function declaration to a HsFunction. i.e., which
549 --   interface will be provided by this function. This function essentially
550 --   defines the "calling convention" for hardware models.
551 mkHsFunction ::
552   Var.Var         -- ^ The function defined
553   -> Type         -- ^ The function type (including arguments!)
554   -> HsFunction   -- ^ The resulting HsFunction
555
556 mkHsFunction f ty =
557   HsFunction hsname hsargs hsres
558   where
559     mkPort = mkHsValueMap (\x -> Single Port)
560     mkState = mkHsValueMap (\x -> Single State)
561     hsname  = getOccString f
562     (arg_tys, res_ty) = Type.splitFunTys ty
563     -- The last argument must be state
564     state_ty = last arg_tys
565     state    = mkState state_ty
566     -- All but the last argument are inports
567     inports = map mkPort (init arg_tys)
568     hsargs   = inports ++ [state]
569     hsres    = case splitTupleType res_ty of
570       -- Result type must be a two tuple (state, ports)
571       Just [outstate_ty, outport_ty] -> if Type.coreEqType state_ty outstate_ty
572         then
573           Tuple [state, mkPort outport_ty]
574         else
575           error $ "Input state type of function " ++ hsname ++ ": " ++ (showSDoc $ ppr state_ty) ++ " does not match output state type: " ++ (showSDoc $ ppr outstate_ty)
576       otherwise                -> error $ "Return type of top-level function " ++ hsname ++ " must be a two-tuple containing a state and output ports."
577
578 data VHDLSession = VHDLSession {
579   nameCount :: Int,                       -- A counter that can be used to generate unique names
580   funcs     :: [(HsFunction, HWFunction)] -- All functions available
581 } deriving (Show)
582
583 type VHDLState = State.State VHDLSession
584
585 -- Add the function to the session
586 addFunc :: HsFunction -> HWFunction -> VHDLState ()
587 addFunc hsfunc hwfunc = do
588   fs <- State.gets funcs -- Get the funcs element from the session
589   State.modify (\x -> x {funcs = (hsfunc, hwfunc) : fs }) -- Prepend name and f
590
591 -- Lookup the function with the given name in the current session. Errors if
592 -- it was not found.
593 getHWFunc :: HsFunction -> VHDLState HWFunction
594 getHWFunc hsfunc = do
595   fs <- State.gets funcs -- Get the funcs element from the session
596   return $ Maybe.fromMaybe
597     (error $ "Function " ++ (hsName hsfunc) ++ "is unknown? This should not happen!")
598     (lookup hsfunc fs)
599
600 -- | Splits a tuple type into a list of element types, or Nothing if the type
601 --   is not a tuple type.
602 splitTupleType ::
603   Type              -- ^ The type to split
604   -> Maybe [Type]   -- ^ The tuples element types
605
606 splitTupleType ty =
607   case Type.splitTyConApp_maybe ty of
608     Just (tycon, args) -> if TyCon.isTupleTyCon tycon 
609       then
610         Just args
611       else
612         Nothing
613     Nothing -> Nothing
614
615 -- Makes the given name unique by appending a unique number.
616 -- This does not do any checking against existing names, so it only guarantees
617 -- uniqueness with other names generated by uniqueName.
618 uniqueName :: String -> VHDLState String
619 uniqueName name = do
620   count <- State.gets nameCount -- Get the funcs element from the session
621   State.modify (\s -> s {nameCount = count + 1})
622   return $ name ++ "_" ++ (show count)
623
624 -- Shortcut
625 mkVHDLId :: String -> AST.VHDLId
626 mkVHDLId = AST.unsafeVHDLBasicId
627
628 builtin_funcs = 
629   [ 
630     (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))),
631     (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))),
632     (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))),
633     (HsFunction "hwnot" [(Single Port)] (Single Port), HWFunction (mkVHDLId "hwnot") [Single (mkVHDLId "i", vhdl_bit_ty)] (Single (mkVHDLId "o", vhdl_bit_ty)))
634   ]
635
636 vhdl_bit_ty :: AST.TypeMark
637 vhdl_bit_ty = AST.unsafeVHDLBasicId "Bit"
638
639 -- Translate a Haskell type to a VHDL type
640 vhdl_ty :: Type -> AST.TypeMark
641 vhdl_ty ty = Maybe.fromMaybe
642   (error $ "Unsupported Haskell type: " ++ (showSDoc $ ppr ty))
643   (vhdl_ty_maybe ty)
644
645 -- Translate a Haskell type to a VHDL type
646 vhdl_ty_maybe :: Type -> Maybe AST.TypeMark
647 vhdl_ty_maybe ty =
648   case Type.splitTyConApp_maybe ty of
649     Just (tycon, args) ->
650       let name = TyCon.tyConName tycon in
651         -- TODO: Do something more robust than string matching
652         case getOccString name of
653           "Bit"      -> Just vhdl_bit_ty
654           otherwise  -> Nothing
655     otherwise -> Nothing
656
657 -- vim: set ts=8 sw=2 sts=2 expandtab: