Allow arguments to builtins to be applications.
[matthijs/master-project/cλash.git] / Generate.hs
1 module Generate where
2
3 -- Standard modules
4 import qualified Control.Monad as Monad
5 import qualified Data.Map as Map
6 import qualified Maybe
7 import qualified Data.Either as Either
8 import Data.Accessor
9 import Debug.Trace
10
11 -- ForSyDe
12 import qualified ForSyDe.Backend.VHDL.AST as AST
13
14 -- GHC API
15 import CoreSyn
16 import Type
17 import qualified Var
18 import qualified IdInfo
19
20 -- Local imports
21 import Constants
22 import VHDLTypes
23 import VHDLTools
24 import CoreTools
25 import Pretty
26
27 -----------------------------------------------------------------------------
28 -- Functions to generate VHDL for builtin functions
29 -----------------------------------------------------------------------------
30
31 -- | A function to wrap a builder-like function that expects its arguments to
32 -- be expressions.
33 genExprArgs ::
34   (dst -> func -> [AST.Expr] -> res)
35   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
36 genExprArgs wrap dst func args = wrap dst func args'
37   where args' = map (either (varToVHDLExpr.exprToVar) id) args
38   
39 -- | A function to wrap a builder-like function that expects its arguments to
40 -- be variables.
41 genVarArgs ::
42   (dst -> func -> [Var.Var] -> res)
43   -> (dst -> func -> [Either CoreSyn.CoreExpr AST.Expr] -> res)
44 genVarArgs wrap dst func args = wrap dst func args'
45   where
46     args' = map exprToVar exprargs
47     -- Check (rather crudely) that all arguments are CoreExprs
48     (exprargs, []) = Either.partitionEithers args
49
50 -- | A function to wrap a builder-like function that produces an expression
51 -- and expects it to be assigned to the destination.
52 genExprRes ::
53   ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession AST.Expr)
54   -> ((Either CoreSyn.CoreBndr AST.VHDLName) -> func -> [arg] -> VHDLSession [AST.ConcSm])
55 genExprRes wrap dst func args = do
56   expr <- wrap dst func args
57   return $ [mkUncondAssign dst expr]
58
59 -- | Generate a binary operator application. The first argument should be a
60 -- constructor from the AST.Expr type, e.g. AST.And.
61 genOperator2 :: (AST.Expr -> AST.Expr -> AST.Expr) -> BuiltinBuilder 
62 genOperator2 op = genExprArgs $ genExprRes (genOperator2' op)
63 genOperator2' :: (AST.Expr -> AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
64 genOperator2' op _ f [arg1, arg2] = return $ op arg1 arg2
65
66 -- | Generate a unary operator application
67 genOperator1 :: (AST.Expr -> AST.Expr) -> BuiltinBuilder 
68 genOperator1 op = genExprArgs $ genExprRes (genOperator1' op)
69 genOperator1' :: (AST.Expr -> AST.Expr) -> dst -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
70 genOperator1' op _ f [arg] = return $ op arg
71
72 -- | Generate a function call from the destination binder, function name and a
73 -- list of expressions (its arguments)
74 genFCall :: BuiltinBuilder 
75 genFCall = genExprArgs $ genExprRes genFCall'
76 genFCall' :: Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
77 genFCall' (Left res) f args = do
78   let fname = varToString f
79   let el_ty = (tfvec_elem . Var.varType) res
80   id <- vectorFunId el_ty fname
81   return $ AST.PrimFCall $ AST.FCall (AST.NSimple id)  $
82              map (\exp -> Nothing AST.:=>: AST.ADExpr exp) args
83 genFCall' (Right name) _ _ = error $ "Cannot generate builtin function call assigned to a VHDLName: " ++ show name
84
85 -- | Generate a generate statement for the builtin function "map"
86 genMap :: BuiltinBuilder
87 genMap = genVarArgs genMap'
88 genMap' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
89 genMap' (Left res) f [mapped_f, arg] =
90   let
91     -- Setup the generate scheme
92     len         = (tfvec_len . Var.varType) res
93     -- TODO: Use something better than varToString
94     label       = mkVHDLExtId ("mapVector" ++ (varToString res))
95     n_id        = mkVHDLBasicId "n"
96     n_expr      = idToVHDLExpr n_id
97     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
98     genScheme   = AST.ForGn n_id range
99
100     -- Create the content of the generate statement: Applying the mapped_f to
101     -- each of the elements in arg, storing to each element in res
102     resname     = mkIndexedName (varToVHDLName res) n_expr
103     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
104   in do
105     app_concsms <- genApplication (Right resname) mapped_f [Right argexpr]
106     -- Return the generate statement
107     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
108
109 genMap' (Right name) _ _ = error $ "Cannot generate map function call assigned to a VHDLName: " ++ show name
110     
111 genZipWith :: BuiltinBuilder
112 genZipWith = genVarArgs genZipWith'
113 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
114 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] =
115   let
116     -- Setup the generate scheme
117     len         = (tfvec_len . Var.varType) res
118     -- TODO: Use something better than varToString
119     label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
120     n_id        = mkVHDLBasicId "n"
121     n_expr      = idToVHDLExpr n_id
122     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
123     genScheme   = AST.ForGn n_id range
124
125     -- Create the content of the generate statement: Applying the zipped_f to
126     -- each of the elements in arg1 and arg2, storing to each element in res
127     resname     = mkIndexedName (varToVHDLName res) n_expr
128     argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
129     argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
130   in do
131     app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
132     -- Return the generate functions
133     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
134
135 genFoldl :: BuiltinBuilder
136 genFoldl = genVarArgs genFoldl'
137 genFoldl' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
138 -- Special case for an empty input vector, just assign start to res
139 genFoldl' (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) (varToVHDLExpr start)]
140     where len = (tfvec_len . Var.varType) vec
141 genFoldl' (Left res) f [folded_f, start, vec] = do
142   -- evec is (TFVec n), so it still needs an element type
143   let (nvec, _) = splitAppTy (Var.varType vec)
144   -- Put the type of the start value in nvec, this will be the type of our
145   -- temporary vector
146   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
147   tmp_vhdl_ty <- vhdl_ty tmp_ty
148   -- Setup the generate scheme
149   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
150   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
151   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
152   let gen_scheme   = AST.ForGn n_id gen_range
153   -- Make the intermediate vector
154   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
155   -- Create the generate statement
156   cells <- sequence [genFirstCell, genOtherCell]
157   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
158   -- Assign tmp[len-1] to res
159   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (mkIndexedName tmp_name (AST.PrimLit $ show (len-1)))
160   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
161   return [AST.CSBSm block]
162   where
163     -- The vector length
164     len         = (tfvec_len . Var.varType) vec
165     -- An id for the counter
166     n_id = mkVHDLBasicId "n"
167     n_expr = idToVHDLExpr n_id
168     -- An expression for n-1
169     n_min_expr = n_expr AST.:-: (AST.PrimLit "1")
170     -- An expression for len-1
171     len_min_expr = (AST.PrimLit $ show (len-1))
172     -- An id for the tmp result vector
173     tmp_id = mkVHDLBasicId "tmp"
174     tmp_name = AST.NSimple tmp_id
175     -- Generate parts of the fold
176     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
177     genFirstCell = do
178       let cond_label = mkVHDLExtId "firstcell"
179       -- if n == 0
180       let cond_scheme = AST.IfGn $ n_expr AST.:=: (AST.PrimLit "0")
181       -- Output to tmp[n]
182       let resname = mkIndexedName tmp_name n_expr
183       -- Input from start
184       let argexpr1 = varToVHDLExpr start
185       -- Input from vec[n]
186       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_expr
187       app_concsms <- genApplication (Right resname) folded_f [Right argexpr1, Right argexpr2]
188       -- Return the conditional generate part
189       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
190
191     genOtherCell = do
192       let cond_label = mkVHDLExtId "othercell"
193       -- if n > 0
194       let cond_scheme = AST.IfGn $ n_expr AST.:>: (AST.PrimLit "0")
195       -- Output to tmp[n]
196       let resname = mkIndexedName tmp_name n_expr
197       -- Input from tmp[n-1]
198       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_min_expr
199       -- Input from vec[n]
200       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_expr
201       app_concsms <- genApplication (Right resname) folded_f [Right argexpr1, Right argexpr2]
202       -- Return the conditional generate part
203       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
204
205 {-
206 genFoldr :: BuiltinBuilder
207 genFoldr = genVarArgs genFoldr'
208 genFoldr' resVal f [folded_f, startVal, inVec] = do
209   signatures <- getA vsSignatures
210   let entity = Maybe.fromMaybe
211         (error $ "Using function '" ++ (varToString folded_f) ++ "' without signature? This should not happen!") 
212         (Map.lookup folded_f signatures)
213   let (vec, _) = splitAppTy (Var.varType inVec)
214   let vecty = Type.mkAppTy vec (Var.varType startVal)
215   vecType <- vhdl_ty vecty
216   -- Setup the generate scheme
217   let  len        = (tfvec_len . Var.varType) inVec
218   let  genlabel   = mkVHDLExtId ("foldrVector" ++ (varToString inVec))
219   let  blockLabel = mkVHDLExtId ("foldrVector" ++ (varToString startVal))
220   let  range      = AST.DownRange (AST.PrimLit $ show (len-1)) (AST.PrimLit "0")
221   let  genScheme  = AST.ForGn (AST.unsafeVHDLBasicId "n") range
222   -- Make the intermediate vector
223   let tmpId       = mkVHDLExtId "tmp"
224   let  tmpVec     = AST.BDISD $ AST.SigDec tmpId vecType Nothing
225   -- Get the entity name and port names
226   let entity_id   = ent_id entity
227   let argports    = map (Monad.liftM fst) (ent_args entity)
228   let resport     = (Monad.liftM fst) (ent_res entity)
229   -- Generate the output assignment
230   let assign      = [mkUncondAssign (Left resVal) (AST.PrimName (AST.NIndexed (AST.IndexedName 
231                         (AST.NSimple tmpId) [AST.PrimLit "0"])))]
232   -- Return the generate functions
233   let genSm       = AST.CSGSm $ AST.GenerateSm genlabel genScheme [] 
234                       [ AST.CSGSm (genFirstCell len (entity_id, argports, resport) 
235                                     [startVal, inVec, resVal])
236                       , AST.CSGSm (genOtherCell len (entity_id, argports, resport) 
237                                     [startVal, inVec, resVal])
238                       ]
239   return $  if len > 0 then
240               [AST.CSBSm $ AST.BlockSm blockLabel [] (AST.PMapAspect []) [tmpVec] (genSm : assign)]
241             else
242               [mkUncondAssign (Left resVal) (AST.PrimName $ AST.NSimple (varToVHDLId startVal))]
243   where
244     genFirstCell len (entity_id, argports, resport) [startVal, inVec, resVal] = cellGn
245       where
246         cellLabel   = mkVHDLExtId "firstcell"
247         cellGenScheme = AST.IfGn ((AST.PrimName $ AST.NSimple nPar)  AST.:=: (AST.PrimLit $ show (len-1)))
248         tmpId       = mkVHDLExtId "tmp"
249         nPar        = AST.unsafeVHDLBasicId "n"
250         -- Assign the ports
251         inport1     = mkAssocElem (argports!!0) (varToString startVal)
252         inport2     = mkAssocElemIndexed (argports!!1) (varToVHDLId inVec) nPar 
253         outport     = mkAssocElemIndexed resport tmpId nPar
254         portassigns = Maybe.catMaybes [inport1,inport2,outport]
255         -- Generate the portmap
256         mapLabel    = "cell" ++ (AST.fromVHDLId entity_id)
257         compins     = mkComponentInst mapLabel entity_id portassigns
258         -- Return the generate functions
259         cellGn       = AST.GenerateSm cellLabel cellGenScheme [] [compins]
260     genOtherCell len (entity_id, argports, resport) [startVal, inVec, resVal] = cellGn
261       where
262         len         = (tfvec_len . Var.varType) inVec
263         cellLabel   = mkVHDLExtId "othercell"
264         cellGenScheme = AST.IfGn ((AST.PrimName $ AST.NSimple nPar)  AST.:/=: (AST.PrimLit $ show (len-1)))
265                                 -- ((AST.PrimName $ AST.NSimple nPar)  AST.:<: (AST.PrimLit $ show (len-1)))
266         tmpId       = mkVHDLExtId "tmp"
267         nPar        = AST.unsafeVHDLBasicId "n"
268         -- Assign the ports
269         inport1     = mkAssocElemIndexed (argports!!0) tmpId (AST.unsafeVHDLBasicId "n+1")
270         inport2     = mkAssocElemIndexed (argports!!1) (varToVHDLId inVec) nPar 
271         outport     = mkAssocElemIndexed resport tmpId nPar
272         portassigns = Maybe.catMaybes [inport1,inport2,outport]
273         -- Generate the portmap
274         mapLabel    = "cell" ++ (AST.fromVHDLId entity_id)
275         compins     = mkComponentInst mapLabel entity_id portassigns
276         -- Return the generate functions
277         cellGn      = AST.GenerateSm cellLabel cellGenScheme [] [compins]
278
279 -}
280
281
282 -----------------------------------------------------------------------------
283 -- Function to generate VHDL for applications
284 -----------------------------------------------------------------------------
285 genApplication ::
286   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
287   -> CoreSyn.CoreBndr -- ^ The function to apply
288   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
289   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
290 genApplication dst f args =
291   case Var.globalIdVarDetails f of
292     IdInfo.DataConWorkId dc -> case dst of
293       -- It's a datacon. Create a record from its arguments.
294       Left bndr -> do
295         -- We have the bndr, so we can get at the type
296         labels <- getFieldLabels (Var.varType bndr)
297         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
298         where
299           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
300           mkassign label arg =
301             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
302             mkUncondAssign (Right sel_name) arg
303       Right _ -> error $ "Generate.genApplication Can't generate dataconstructor application without an original binder"
304     IdInfo.VanillaGlobal -> do
305       -- It's a global value imported from elsewhere. These can be builtin
306       -- functions. Look up the function name in the name table and execute
307       -- the associated builder if there is any and the argument count matches
308       -- (this should always be the case if it typechecks, but just to be
309       -- sure...).
310       case (Map.lookup (varToString f) globalNameTable) of
311         Just (arg_count, builder) ->
312           if length args == arg_count then
313             builder dst f args
314           else
315             error $ "Generate.genApplication Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
316         Nothing -> error $ "Using function from another module that is not a known builtin: " ++ pprString f
317     IdInfo.NotGlobalId -> do
318       signatures <- getA vsSignatures
319       -- This is a local id, so it should be a function whose definition we
320       -- have and which can be turned into a component instantiation.
321       let  
322         signature = Maybe.fromMaybe 
323           (error $ "Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
324           (Map.lookup f signatures)
325         entity_id = ent_id signature
326         -- TODO: Using show here isn't really pretty, but we'll need some
327         -- unique-ish value...
328         label = "comp_ins_" ++ (either show show) dst
329         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
330         in
331           return [mkComponentInst label entity_id portmaps]
332     details -> error $ "Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
333
334 -----------------------------------------------------------------------------
335 -- Functions to generate functions dealing with vectors.
336 -----------------------------------------------------------------------------
337
338 -- Returns the VHDLId of the vector function with the given name for the given
339 -- element type. Generates -- this function if needed.
340 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
341 vectorFunId el_ty fname = do
342   elemTM <- vhdl_ty el_ty
343   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
344   -- the VHDLState or something.
345   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
346   typefuns <- getA vsTypeFuns
347   case Map.lookup (OrdType el_ty, fname) typefuns of
348     -- Function already generated, just return it
349     Just (id, _) -> return id
350     -- Function not generated yet, generate it
351     Nothing -> do
352       let functions = genUnconsVectorFuns elemTM vectorTM
353       case lookup fname functions of
354         Just body -> do
355           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, body)
356           return function_id
357         Nothing -> error $ "I don't know how to generate vector function " ++ fname
358   where
359     function_id = mkVHDLExtId fname
360
361 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
362                     -> AST.TypeMark -- ^ type of the vector
363                     -> [(String, AST.SubProgBody)]
364 genUnconsVectorFuns elemTM vectorTM  = 
365   [ (exId, AST.SubProgBody exSpec      []                  [exExpr])
366   , (replaceId, AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet])
367   , (headId, AST.SubProgBody headSpec    []                  [headExpr])
368   , (lastId, AST.SubProgBody lastSpec    []                  [lastExpr])
369   , (initId, AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet])
370   , (tailId, AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet])
371   , (takeId, AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet])
372   , (dropId, AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet])
373   , (plusgtId, AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet])
374   , (emptyId, AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr])
375   , (singletonId, AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet])
376   , (copyId, AST.SubProgBody copySpec    [AST.SPVD copyVar]      [copyExpr])
377   ]
378   where 
379     ixPar   = AST.unsafeVHDLBasicId "ix"
380     vecPar  = AST.unsafeVHDLBasicId "vec"
381     nPar    = AST.unsafeVHDLBasicId "n"
382     iId     = AST.unsafeVHDLBasicId "i"
383     iPar    = iId
384     aPar    = AST.unsafeVHDLBasicId "a"
385     resId   = AST.unsafeVHDLBasicId "res"
386     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
387                                AST.IfaceVarDec ixPar  naturalTM] elemTM
388     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
389               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
390                 AST.NSimple ixPar]))
391     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
392                                           , AST.IfaceVarDec iPar   naturalTM
393                                           , AST.IfaceVarDec aPar   elemTM
394                                           ] vectorTM 
395        -- variable res : fsvec_x (0 to vec'length-1);
396     replaceVar =
397          AST.VarDec resId 
398                 (AST.SubtypeIn vectorTM
399                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
400                    [AST.ToRange (AST.PrimLit "0")
401                             (AST.PrimName (AST.NAttribute $ 
402                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
403                                 (AST.PrimLit "1"))   ]))
404                 Nothing
405        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
406     replaceExpr = AST.NSimple resId AST.:=
407            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
408             AST.PrimName (AST.NSimple aPar) AST.:&: 
409              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
410                       ((AST.PrimName (AST.NAttribute $ 
411                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
412                                                               AST.:-: AST.PrimLit "1"))
413     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
414     vecSlice init last =  AST.PrimName (AST.NSlice 
415                                         (AST.SliceName 
416                                               (AST.NSimple vecPar) 
417                                               (AST.ToRange init last)))
418     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
419        -- return vec(0);
420     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
421                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
422     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
423        -- return vec(vec'length-1);
424     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
425                     (AST.NSimple vecPar) 
426                     [AST.PrimName (AST.NAttribute $ 
427                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
428                                                              AST.:-: AST.PrimLit "1"])))
429     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
430        -- variable res : fsvec_x (0 to vec'length-2);
431     initVar = 
432          AST.VarDec resId 
433                 (AST.SubtypeIn vectorTM
434                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
435                    [AST.ToRange (AST.PrimLit "0")
436                             (AST.PrimName (AST.NAttribute $ 
437                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
438                                 (AST.PrimLit "2"))   ]))
439                 Nothing
440        -- resAST.:= vec(0 to vec'length-2)
441     initExpr = AST.NSimple resId AST.:= (vecSlice 
442                                (AST.PrimLit "0") 
443                                (AST.PrimName (AST.NAttribute $ 
444                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
445                                                              AST.:-: AST.PrimLit "2"))
446     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
447     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
448        -- variable res : fsvec_x (0 to vec'length-2); 
449     tailVar = 
450          AST.VarDec resId 
451                 (AST.SubtypeIn vectorTM
452                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
453                    [AST.ToRange (AST.PrimLit "0")
454                             (AST.PrimName (AST.NAttribute $ 
455                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
456                                 (AST.PrimLit "2"))   ]))
457                 Nothing       
458        -- res AST.:= vec(1 to vec'length-1)
459     tailExpr = AST.NSimple resId AST.:= (vecSlice 
460                                (AST.PrimLit "1") 
461                                (AST.PrimName (AST.NAttribute $ 
462                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
463                                                              AST.:-: AST.PrimLit "1"))
464     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
465     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
466                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
467        -- variable res : fsvec_x (0 to n-1);
468     takeVar = 
469          AST.VarDec resId 
470                 (AST.SubtypeIn vectorTM
471                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
472                    [AST.ToRange (AST.PrimLit "0")
473                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
474                                 (AST.PrimLit "1"))   ]))
475                 Nothing
476        -- res AST.:= vec(0 to n-1)
477     takeExpr = AST.NSimple resId AST.:= 
478                     (vecSlice (AST.PrimLit "1") 
479                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
480     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
481     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
482                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
483        -- variable res : fsvec_x (0 to vec'length-n-1);
484     dropVar = 
485          AST.VarDec resId 
486                 (AST.SubtypeIn vectorTM
487                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
488                    [AST.ToRange (AST.PrimLit "0")
489                             (AST.PrimName (AST.NAttribute $ 
490                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
491                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
492                Nothing
493        -- res AST.:= vec(n to vec'length-1)
494     dropExpr = AST.NSimple resId AST.:= (vecSlice 
495                                (AST.PrimName $ AST.NSimple nPar) 
496                                (AST.PrimName (AST.NAttribute $ 
497                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
498                                                              AST.:-: AST.PrimLit "1"))
499     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
500     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
501                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
502     -- variable res : fsvec_x (0 to vec'length);
503     plusgtVar = 
504       AST.VarDec resId 
505              (AST.SubtypeIn vectorTM
506                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
507                 [AST.ToRange (AST.PrimLit "0")
508                         (AST.PrimName (AST.NAttribute $ 
509                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
510              Nothing
511     plusgtExpr = AST.NSimple resId AST.:= 
512                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
513                     (AST.PrimName $ AST.NSimple vecPar))
514     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
515     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
516     emptyVar = 
517           AST.ConstDec resId 
518               (AST.SubtypeIn vectorTM Nothing)
519               (Just $ AST.PrimLit "\"\"")
520     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
521     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
522                                          vectorTM
523     -- variable res : fsvec_x (0 to 0) := (others => a);
524     singletonVar = 
525       AST.VarDec resId 
526              (AST.SubtypeIn vectorTM
527                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
528                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
529              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
530                                           (AST.PrimName $ AST.NSimple aPar)])
531     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
532     copySpec = AST.Function (mkVHDLExtId copyId) [AST.IfaceVarDec nPar   naturalTM,
533                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
534     -- variable res : fsvec_x (0 to n-1) := (others => a);
535     copyVar = 
536       AST.VarDec resId 
537              (AST.SubtypeIn vectorTM
538                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
539                 [AST.ToRange (AST.PrimLit "0")
540                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
541                              (AST.PrimLit "1"))   ]))
542              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
543                                           (AST.PrimName $ AST.NSimple aPar)])
544     -- return res
545     copyExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
546
547 -----------------------------------------------------------------------------
548 -- A table of builtin functions
549 -----------------------------------------------------------------------------
550
551 -- | The builtin functions we support. Maps a name to an argument count and a
552 -- builder function.
553 globalNameTable :: NameTable
554 globalNameTable = Map.fromList
555   [ (exId             , (2, genFCall                ) )
556   , (replaceId        , (3, genFCall                ) )
557   , (headId           , (1, genFCall                ) )
558   , (lastId           , (1, genFCall                ) )
559   , (tailId           , (1, genFCall                ) )
560   , (initId           , (1, genFCall                ) )
561   , (takeId           , (2, genFCall                ) )
562   , (dropId           , (2, genFCall                ) )
563   , (plusgtId         , (2, genFCall                ) )
564   , (mapId            , (2, genMap                  ) )
565   , (zipWithId        , (3, genZipWith              ) )
566   , (foldlId          , (3, genFoldl                ) )
567   --, (foldrId          , (3, genFoldr                ) )
568   , (emptyId          , (0, genFCall                ) )
569   , (singletonId      , (1, genFCall                ) )
570   , (copyId           , (2, genFCall                ) )
571   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
572   , (hwandId          , (2, genOperator2 AST.And    ) )
573   , (hworId           , (2, genOperator2 AST.Or     ) )
574   , (hwnotId          , (1, genOperator1 AST.Not    ) )
575   ]