Keys for typemap can now deal with vector lengths based on type operators
[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 :: Bool -> BuiltinBuilder 
75 genFCall switch = genExprArgs $ genExprRes (genFCall' switch)
76 genFCall' :: Bool -> Either CoreSyn.CoreBndr AST.VHDLName -> CoreSyn.CoreBndr -> [AST.Expr] -> VHDLSession AST.Expr
77 genFCall' switch (Left res) f args = do
78   let fname = varToString f
79   let el_ty = if switch then (Var.varType res) else ((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 $ "\nGenerate.genFCall': 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 (Left res) f [Left mapped_f, Left (Var arg)] =
88   -- mapped_f must be a CoreExpr (since we can't represent functions as VHDL
89   -- expressions). arg must be a CoreExpr (and should be a CoreSyn.Var), since
90   -- we must index it (which we couldn't if it was a VHDL Expr, since only
91   -- VHDLNames can be indexed).
92   let
93     -- Setup the generate scheme
94     len         = (tfvec_len . Var.varType) res
95     -- TODO: Use something better than varToString
96     label       = mkVHDLExtId ("mapVector" ++ (varToString res))
97     n_id        = mkVHDLBasicId "n"
98     n_expr      = idToVHDLExpr n_id
99     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
100     genScheme   = AST.ForGn n_id range
101
102     -- Create the content of the generate statement: Applying the mapped_f to
103     -- each of the elements in arg, storing to each element in res
104     resname     = mkIndexedName (varToVHDLName res) n_expr
105     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
106   in do
107     let (CoreSyn.Var real_f, already_mapped_args) = CoreSyn.collectArgs mapped_f
108     let valargs = get_val_args (Var.varType real_f) already_mapped_args
109     app_concsms <- genApplication (Right resname) real_f (map Left valargs ++ [Right argexpr])
110     -- Return the generate statement
111     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
112
113 genMap' (Right name) _ _ = error $ "\nGenerate.genMap': Cannot generate map function call assigned to a VHDLName: " ++ show name
114     
115 genZipWith :: BuiltinBuilder
116 genZipWith = genVarArgs genZipWith'
117 genZipWith' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
118 genZipWith' (Left res) f args@[zipped_f, arg1, arg2] =
119   let
120     -- Setup the generate scheme
121     len         = (tfvec_len . Var.varType) res
122     -- TODO: Use something better than varToString
123     label       = mkVHDLExtId ("zipWithVector" ++ (varToString res))
124     n_id        = mkVHDLBasicId "n"
125     n_expr      = idToVHDLExpr n_id
126     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
127     genScheme   = AST.ForGn n_id range
128
129     -- Create the content of the generate statement: Applying the zipped_f to
130     -- each of the elements in arg1 and arg2, storing to each element in res
131     resname     = mkIndexedName (varToVHDLName res) n_expr
132     argexpr1    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
133     argexpr2    = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
134   in do
135     app_concsms <- genApplication (Right resname) zipped_f [Right argexpr1, Right argexpr2]
136     -- Return the generate functions
137     return [AST.CSGSm $ AST.GenerateSm label genScheme [] app_concsms]
138
139 genFoldl :: BuiltinBuilder
140 genFoldl = genFold True
141
142 genFoldr :: BuiltinBuilder
143 genFoldr = genFold False
144
145 genFold :: Bool -> BuiltinBuilder
146 genFold left = genVarArgs (genFold' left)
147 genFold' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
148 -- Special case for an empty input vector, just assign start to res
149 genFold' left (Left res) _ [_, start, vec] | len == 0 = return [mkUncondAssign (Left res) (varToVHDLExpr start)]
150     where len = (tfvec_len . Var.varType) vec
151 genFold' left (Left res) f [folded_f, start, vec] = do
152   -- evec is (TFVec n), so it still needs an element type
153   let (nvec, _) = splitAppTy (Var.varType vec)
154   -- Put the type of the start value in nvec, this will be the type of our
155   -- temporary vector
156   let tmp_ty = Type.mkAppTy nvec (Var.varType start)
157   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
158   tmp_vhdl_ty <- vhdl_ty error_msg tmp_ty
159   -- Setup the generate scheme
160   let gen_label = mkVHDLExtId ("foldlVector" ++ (varToString vec))
161   let block_label = mkVHDLExtId ("foldlVector" ++ (varToString start))
162   let gen_range = if left then AST.ToRange (AST.PrimLit "0") len_min_expr
163                   else AST.DownRange len_min_expr (AST.PrimLit "0")
164   let gen_scheme   = AST.ForGn n_id gen_range
165   -- Make the intermediate vector
166   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
167   -- Create the generate statement
168   cells <- sequence [genFirstCell, genOtherCell]
169   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
170   -- Assign tmp[len-1] or tmp[0] to res
171   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr (if left then
172                     (mkIndexedName tmp_name (AST.PrimLit $ show (len-1))) else
173                     (mkIndexedName tmp_name (AST.PrimLit "0")))      
174   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
175   return [AST.CSBSm block]
176   where
177     -- The vector length
178     len         = (tfvec_len . Var.varType) vec
179     -- An id for the counter
180     n_id = mkVHDLBasicId "n"
181     n_cur = idToVHDLExpr n_id
182     -- An expression for previous n
183     n_prev = if left then (n_cur AST.:-: (AST.PrimLit "1"))
184                      else (n_cur AST.:+: (AST.PrimLit "1"))
185     -- An expression for len-1
186     len_min_expr = (AST.PrimLit $ show (len-1))
187     -- An id for the tmp result vector
188     tmp_id = mkVHDLBasicId "tmp"
189     tmp_name = AST.NSimple tmp_id
190     -- Generate parts of the fold
191     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
192     genFirstCell = do
193       let cond_label = mkVHDLExtId "firstcell"
194       -- if n == 0 or n == len-1
195       let cond_scheme = AST.IfGn $ n_cur AST.:=: (if left then (AST.PrimLit "0")
196                                                   else (AST.PrimLit $ show (len-1)))
197       -- Output to tmp[current n]
198       let resname = mkIndexedName tmp_name n_cur
199       -- Input from start
200       let argexpr1 = varToVHDLExpr start
201       -- Input from vec[current n]
202       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
203       app_concsms <- genApplication (Right resname) folded_f  ( if left then
204                                                                   [Right argexpr1, Right argexpr2]
205                                                                 else
206                                                                   [Right argexpr2, Right argexpr1]
207                                                               )
208       -- Return the conditional generate part
209       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
210
211     genOtherCell = do
212       let cond_label = mkVHDLExtId "othercell"
213       -- if n > 0 or n < len-1
214       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (if left then (AST.PrimLit "0")
215                                                    else (AST.PrimLit $ show (len-1)))
216       -- Output to tmp[current n]
217       let resname = mkIndexedName tmp_name n_cur
218       -- Input from tmp[previous n]
219       let argexpr1 = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
220       -- Input from vec[current n]
221       let argexpr2 = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName vec) n_cur
222       app_concsms <- genApplication (Right resname) folded_f  ( if left then
223                                                                   [Right argexpr1, Right argexpr2]
224                                                                 else
225                                                                   [Right argexpr2, Right argexpr1]
226                                                               )
227       -- Return the conditional generate part
228       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
229
230 -- | Generate a generate statement for the builtin function "zip"
231 genZip :: BuiltinBuilder
232 genZip = genVarArgs genZip'
233 genZip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
234 genZip' (Left res) f args@[arg1, arg2] =
235   let
236     -- Setup the generate scheme
237     len             = (tfvec_len . Var.varType) res
238     -- TODO: Use something better than varToString
239     label           = mkVHDLExtId ("zipVector" ++ (varToString res))
240     n_id            = mkVHDLBasicId "n"
241     n_expr          = idToVHDLExpr n_id
242     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
243     genScheme       = AST.ForGn n_id range
244     resname'        = mkIndexedName (varToVHDLName res) n_expr
245     argexpr1        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg1) n_expr
246     argexpr2        = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg2) n_expr
247   in do
248     labels <- getFieldLabels (tfvec_elem (Var.varType res))
249     let resnameA    = mkSelectedName resname' (labels!!0)
250     let resnameB    = mkSelectedName resname' (labels!!1)
251     let resA_assign = mkUncondAssign (Right resnameA) argexpr1
252     let resB_assign = mkUncondAssign (Right resnameB) argexpr2
253     -- Return the generate functions
254     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
255     
256 -- | Generate a generate statement for the builtin function "unzip"
257 genUnzip :: BuiltinBuilder
258 genUnzip = genVarArgs genUnzip'
259 genUnzip' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
260 genUnzip' (Left res) f args@[arg] =
261   let
262     -- Setup the generate scheme
263     len             = (tfvec_len . Var.varType) arg
264     -- TODO: Use something better than varToString
265     label           = mkVHDLExtId ("unzipVector" ++ (varToString res))
266     n_id            = mkVHDLBasicId "n"
267     n_expr          = idToVHDLExpr n_id
268     range           = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len-1))
269     genScheme       = AST.ForGn n_id range
270     resname'        = varToVHDLName res
271     argexpr'        = mkIndexedName (varToVHDLName arg) n_expr
272   in do
273     reslabels <- getFieldLabels (Var.varType res)
274     arglabels <- getFieldLabels (tfvec_elem (Var.varType arg))
275     let resnameA    = mkIndexedName (mkSelectedName resname' (reslabels!!0)) n_expr
276     let resnameB    = mkIndexedName (mkSelectedName resname' (reslabels!!1)) n_expr
277     let argexprA    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!0)
278     let argexprB    = vhdlNameToVHDLExpr $ mkSelectedName argexpr' (arglabels!!1)
279     let resA_assign = mkUncondAssign (Right resnameA) argexprA
280     let resB_assign = mkUncondAssign (Right resnameB) argexprB
281     -- Return the generate functions
282     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [resA_assign,resB_assign]]
283
284 genCopy :: BuiltinBuilder 
285 genCopy = genVarArgs genCopy'
286 genCopy' :: (Either CoreSyn.CoreBndr AST.VHDLName ) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
287 genCopy' (Left res) f args@[arg] =
288   let
289     resExpr = AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
290                 (AST.PrimName $ (varToVHDLName arg))]
291     out_assign = mkUncondAssign (Left res) resExpr
292   in 
293     return [out_assign]
294     
295 genConcat :: BuiltinBuilder
296 genConcat = genVarArgs genConcat'
297 genConcat' :: (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
298 genConcat' (Left res) f args@[arg] =
299   let
300     -- Setup the generate scheme
301     len1        = (tfvec_len . Var.varType) arg
302     (_, nvec)   = splitAppTy (Var.varType arg)
303     len2        = tfvec_len nvec
304     -- TODO: Use something better than varToString
305     label       = mkVHDLExtId ("concatVector" ++ (varToString res))
306     n_id        = mkVHDLBasicId "n"
307     n_expr      = idToVHDLExpr n_id
308     fromRange   = n_expr AST.:*: (AST.PrimLit $ show len2)
309     genScheme   = AST.ForGn n_id range
310     -- Create the content of the generate statement: Applying the mapped_f to
311     -- each of the elements in arg, storing to each element in res
312     toRange     = (n_expr AST.:*: (AST.PrimLit $ show len2)) AST.:+: (AST.PrimLit $ show (len2-1))
313     range       = AST.ToRange (AST.PrimLit "0") (AST.PrimLit $ show (len1-1))
314     resname     = vecSlice fromRange toRange
315     argexpr     = vhdlNameToVHDLExpr $ mkIndexedName (varToVHDLName arg) n_expr
316     out_assign  = mkUncondAssign (Right resname) argexpr
317   in
318     -- Return the generate statement
319     return [AST.CSGSm $ AST.GenerateSm label genScheme [] [out_assign]]
320   where
321     vecSlice init last =  AST.NSlice (AST.SliceName (varToVHDLName res) 
322                             (AST.ToRange init last))
323
324 genIteraten :: BuiltinBuilder
325 genIteraten dst f args = genIterate dst f (tail args)
326
327 genIterate :: BuiltinBuilder
328 genIterate = genIterateOrGenerate True
329
330 genGeneraten :: BuiltinBuilder
331 genGeneraten dst f args = genGenerate dst f (tail args)
332
333 genGenerate :: BuiltinBuilder
334 genGenerate = genIterateOrGenerate False
335
336 genIterateOrGenerate :: Bool -> BuiltinBuilder
337 genIterateOrGenerate iter = genVarArgs (genIterateOrGenerate' iter)
338 genIterateOrGenerate' :: Bool -> (Either CoreSyn.CoreBndr AST.VHDLName) -> CoreSyn.CoreBndr -> [Var.Var] -> VHDLSession [AST.ConcSm]
339 -- Special case for an empty input vector, just assign start to res
340 genIterateOrGenerate' iter (Left res) _ [app_f, start] | len == 0 = return [mkUncondAssign (Left res) (AST.PrimLit "\"\"")]
341     where len = (tfvec_len . Var.varType) res
342 genIterateOrGenerate' iter (Left res) f [app_f, start] = do
343   -- -- evec is (TFVec n), so it still needs an element type
344   -- let (nvec, _) = splitAppTy (Var.varType vec)
345   -- -- Put the type of the start value in nvec, this will be the type of our
346   -- -- temporary vector
347   let tmp_ty = Var.varType res
348   let error_msg = "\nGenerate.genFold': Can not construct temp vector for element type: " ++ pprString tmp_ty 
349   tmp_vhdl_ty <- vhdl_ty error_msg tmp_ty
350   -- Setup the generate scheme
351   let gen_label = mkVHDLExtId ("iterateVector" ++ (varToString start))
352   let block_label = mkVHDLExtId ("iterateVector" ++ (varToString res))
353   let gen_range = AST.ToRange (AST.PrimLit "0") len_min_expr
354   let gen_scheme   = AST.ForGn n_id gen_range
355   -- Make the intermediate vector
356   let  tmp_dec     = AST.BDISD $ AST.SigDec tmp_id tmp_vhdl_ty Nothing
357   -- Create the generate statement
358   cells <- sequence [genFirstCell, genOtherCell]
359   let gen_sm = AST.GenerateSm gen_label gen_scheme [] (map AST.CSGSm cells)
360   -- Assign tmp[len-1] or tmp[0] to res
361   let out_assign = mkUncondAssign (Left res) $ vhdlNameToVHDLExpr tmp_name    
362   let block = AST.BlockSm block_label [] (AST.PMapAspect []) [tmp_dec] [AST.CSGSm gen_sm, out_assign]
363   return [AST.CSBSm block]
364   where
365     -- The vector length
366     len = (tfvec_len . Var.varType) res
367     -- An id for the counter
368     n_id = mkVHDLBasicId "n"
369     n_cur = idToVHDLExpr n_id
370     -- An expression for previous n
371     n_prev = n_cur AST.:-: (AST.PrimLit "1")
372     -- An expression for len-1
373     len_min_expr = (AST.PrimLit $ show (len-1))
374     -- An id for the tmp result vector
375     tmp_id = mkVHDLBasicId "tmp"
376     tmp_name = AST.NSimple tmp_id
377     -- Generate parts of the fold
378     genFirstCell, genOtherCell :: VHDLSession AST.GenerateSm
379     genFirstCell = do
380       let cond_label = mkVHDLExtId "firstcell"
381       -- if n == 0 or n == len-1
382       let cond_scheme = AST.IfGn $ n_cur AST.:=: (AST.PrimLit "0")
383       -- Output to tmp[current n]
384       let resname = mkIndexedName tmp_name n_cur
385       -- Input from start
386       let argexpr = varToVHDLExpr start
387       let startassign = mkUncondAssign (Right resname) argexpr
388       app_concsms <- genApplication (Right resname) app_f  [Right argexpr]
389       -- Return the conditional generate part
390       return $ AST.GenerateSm cond_label cond_scheme [] (if iter then 
391                                                           [startassign]
392                                                          else 
393                                                           app_concsms
394                                                         )
395
396     genOtherCell = do
397       let cond_label = mkVHDLExtId "othercell"
398       -- if n > 0 or n < len-1
399       let cond_scheme = AST.IfGn $ n_cur AST.:/=: (AST.PrimLit "0")
400       -- Output to tmp[current n]
401       let resname = mkIndexedName tmp_name n_cur
402       -- Input from tmp[previous n]
403       let argexpr = vhdlNameToVHDLExpr $ mkIndexedName tmp_name n_prev
404       app_concsms <- genApplication (Right resname) app_f [Right argexpr]
405       -- Return the conditional generate part
406       return $ AST.GenerateSm cond_label cond_scheme [] app_concsms
407
408
409 -----------------------------------------------------------------------------
410 -- Function to generate VHDL for applications
411 -----------------------------------------------------------------------------
412 genApplication ::
413   (Either CoreSyn.CoreBndr AST.VHDLName) -- ^ Where to store the result?
414   -> CoreSyn.CoreBndr -- ^ The function to apply
415   -> [Either CoreSyn.CoreExpr AST.Expr] -- ^ The arguments to apply
416   -> VHDLSession [AST.ConcSm] -- ^ The resulting concurrent statements
417 genApplication dst f args =
418   case Var.globalIdVarDetails f of
419     IdInfo.DataConWorkId dc -> case dst of
420       -- It's a datacon. Create a record from its arguments.
421       Left bndr -> do
422         -- We have the bndr, so we can get at the type
423         labels <- getFieldLabels (Var.varType bndr)
424         return $ zipWith mkassign labels $ map (either exprToVHDLExpr id) args
425         where
426           mkassign :: AST.VHDLId -> AST.Expr -> AST.ConcSm
427           mkassign label arg =
428             let sel_name = mkSelectedName ((either varToVHDLName id) dst) label in
429             mkUncondAssign (Right sel_name) arg
430       Right _ -> error $ "\nGenerate.genApplication: Can't generate dataconstructor application without an original binder"
431     IdInfo.VanillaGlobal -> do
432       -- It's a global value imported from elsewhere. These can be builtin
433       -- functions. Look up the function name in the name table and execute
434       -- the associated builder if there is any and the argument count matches
435       -- (this should always be the case if it typechecks, but just to be
436       -- sure...).
437       case (Map.lookup (varToString f) globalNameTable) of
438         Just (arg_count, builder) ->
439           if length args == arg_count then
440             builder dst f args
441           else
442             error $ "\nGenerate.genApplication: Incorrect number of arguments to builtin function: " ++ pprString f ++ " Args: " ++ show args
443         Nothing -> error $ "\nGenerate.genApplication: Using function from another module that is not a known builtin: " ++ pprString f
444     IdInfo.NotGlobalId -> do
445       signatures <- getA vsSignatures
446       -- This is a local id, so it should be a function whose definition we
447       -- have and which can be turned into a component instantiation.
448       let  
449         signature = Maybe.fromMaybe 
450           (error $ "\nGenerate.genApplication: Using function '" ++ (varToString f) ++ "' without signature? This should not happen!") 
451           (Map.lookup f signatures)
452         entity_id = ent_id signature
453         -- TODO: Using show here isn't really pretty, but we'll need some
454         -- unique-ish value...
455         label = "comp_ins_" ++ (either show prettyShow) dst
456         portmaps = mkAssocElems (map (either exprToVHDLExpr id) args) ((either varToVHDLName id) dst) signature
457         in
458           return [mkComponentInst label entity_id portmaps]
459     details -> error $ "\nGenerate.genApplication: Calling unsupported function " ++ pprString f ++ " with GlobalIdDetails " ++ pprString details
460
461 -----------------------------------------------------------------------------
462 -- Functions to generate functions dealing with vectors.
463 -----------------------------------------------------------------------------
464
465 -- Returns the VHDLId of the vector function with the given name for the given
466 -- element type. Generates -- this function if needed.
467 vectorFunId :: Type.Type -> String -> VHDLSession AST.VHDLId
468 vectorFunId el_ty fname = do
469   let error_msg = "\nGenerate.vectorFunId: Can not construct vector function for element: " ++ pprString el_ty
470   elemTM <- vhdl_ty error_msg el_ty
471   -- TODO: This should not be duplicated from mk_vector_ty. Probably but it in
472   -- the VHDLState or something.
473   let vectorTM = mkVHDLExtId $ "vector_" ++ (AST.fromVHDLId elemTM)
474   typefuns <- getA vsTypeFuns
475   case Map.lookup (OrdType el_ty, fname) typefuns of
476     -- Function already generated, just return it
477     Just (id, _) -> return id
478     -- Function not generated yet, generate it
479     Nothing -> do
480       let functions = genUnconsVectorFuns elemTM vectorTM
481       case lookup fname functions of
482         Just body -> do
483           modA vsTypeFuns $ Map.insert (OrdType el_ty, fname) (function_id, (fst body))
484           mapM_ (vectorFunId el_ty) (snd body)
485           return function_id
486         Nothing -> error $ "\nGenerate.vectorFunId: I don't know how to generate vector function " ++ fname
487   where
488     function_id = mkVHDLExtId fname
489
490 genUnconsVectorFuns :: AST.TypeMark -- ^ type of the vector elements
491                     -> AST.TypeMark -- ^ type of the vector
492                     -> [(String, (AST.SubProgBody, [String]))]
493 genUnconsVectorFuns elemTM vectorTM  = 
494   [ (exId, (AST.SubProgBody exSpec      []                  [exExpr],[]))
495   , (replaceId, (AST.SubProgBody replaceSpec [AST.SPVD replaceVar] [replaceExpr,replaceRet],[]))
496   , (headId, (AST.SubProgBody headSpec    []                  [headExpr],[]))
497   , (lastId, (AST.SubProgBody lastSpec    []                  [lastExpr],[]))
498   , (initId, (AST.SubProgBody initSpec    [AST.SPVD initVar]  [initExpr, initRet],[]))
499   , (tailId, (AST.SubProgBody tailSpec    [AST.SPVD tailVar]  [tailExpr, tailRet],[]))
500   , (takeId, (AST.SubProgBody takeSpec    [AST.SPVD takeVar]  [takeExpr, takeRet],[]))
501   , (dropId, (AST.SubProgBody dropSpec    [AST.SPVD dropVar]  [dropExpr, dropRet],[]))
502   , (plusgtId, (AST.SubProgBody plusgtSpec  [AST.SPVD plusgtVar] [plusgtExpr, plusgtRet],[]))
503   , (emptyId, (AST.SubProgBody emptySpec   [AST.SPCD emptyVar] [emptyExpr],[]))
504   , (singletonId, (AST.SubProgBody singletonSpec [AST.SPVD singletonVar] [singletonRet],[]))
505   , (copynId, (AST.SubProgBody copynSpec    [AST.SPVD copynVar]      [copynExpr],[]))
506   , (selId, (AST.SubProgBody selSpec  [AST.SPVD selVar] [selFor, selRet],[]))
507   , (ltplusId, (AST.SubProgBody ltplusSpec [AST.SPVD ltplusVar] [ltplusExpr, ltplusRet],[]))  
508   , (plusplusId, (AST.SubProgBody plusplusSpec [AST.SPVD plusplusVar] [plusplusExpr, plusplusRet],[]))
509   , (lengthTId, (AST.SubProgBody lengthTSpec [] [lengthTExpr],[]))
510   , (shiftlId, (AST.SubProgBody shiftlSpec [AST.SPVD shiftlVar] [shiftlExpr, shiftlRet], [initId]))
511   , (shiftrId, (AST.SubProgBody shiftrSpec [AST.SPVD shiftrVar] [shiftrExpr, shiftrRet], [tailId]))
512   , (nullId, (AST.SubProgBody nullSpec [] [nullExpr], []))
513   , (rotlId, (AST.SubProgBody rotlSpec [AST.SPVD rotlVar] [rotlExpr, rotlRet], [nullId, lastId, initId]))
514   , (rotrId, (AST.SubProgBody rotrSpec [AST.SPVD rotrVar] [rotrExpr, rotrRet], [nullId, tailId, headId]))
515   , (reverseId, (AST.SubProgBody reverseSpec [AST.SPVD reverseVar] [reverseFor, reverseRet], []))
516   ]
517   where 
518     ixPar   = AST.unsafeVHDLBasicId "ix"
519     vecPar  = AST.unsafeVHDLBasicId "vec"
520     vec1Par = AST.unsafeVHDLBasicId "vec1"
521     vec2Par = AST.unsafeVHDLBasicId "vec2"
522     nPar    = AST.unsafeVHDLBasicId "n"
523     iId     = AST.unsafeVHDLBasicId "i"
524     iPar    = iId
525     aPar    = AST.unsafeVHDLBasicId "a"
526     fPar = AST.unsafeVHDLBasicId "f"
527     sPar = AST.unsafeVHDLBasicId "s"
528     resId   = AST.unsafeVHDLBasicId "res"
529     exSpec = AST.Function (mkVHDLExtId exId) [AST.IfaceVarDec vecPar vectorTM,
530                                AST.IfaceVarDec ixPar  naturalTM] elemTM
531     exExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NIndexed 
532               (AST.IndexedName (AST.NSimple vecPar) [AST.PrimName $ 
533                 AST.NSimple ixPar]))
534     replaceSpec = AST.Function (mkVHDLExtId replaceId)  [ AST.IfaceVarDec vecPar vectorTM
535                                           , AST.IfaceVarDec iPar   naturalTM
536                                           , AST.IfaceVarDec aPar   elemTM
537                                           ] vectorTM 
538        -- variable res : fsvec_x (0 to vec'length-1);
539     replaceVar =
540          AST.VarDec resId 
541                 (AST.SubtypeIn vectorTM
542                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
543                    [AST.ToRange (AST.PrimLit "0")
544                             (AST.PrimName (AST.NAttribute $ 
545                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
546                                 (AST.PrimLit "1"))   ]))
547                 Nothing
548        --  res AST.:= vec(0 to i-1) & a & vec(i+1 to length'vec-1)
549     replaceExpr = AST.NSimple resId AST.:=
550            (vecSlice (AST.PrimLit "0") (AST.PrimName (AST.NSimple iPar) AST.:-: AST.PrimLit "1") AST.:&:
551             AST.PrimName (AST.NSimple aPar) AST.:&: 
552              vecSlice (AST.PrimName (AST.NSimple iPar) AST.:+: AST.PrimLit "1")
553                       ((AST.PrimName (AST.NAttribute $ 
554                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing)) 
555                                                               AST.:-: AST.PrimLit "1"))
556     replaceRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
557     vecSlice init last =  AST.PrimName (AST.NSlice 
558                                         (AST.SliceName 
559                                               (AST.NSimple vecPar) 
560                                               (AST.ToRange init last)))
561     headSpec = AST.Function (mkVHDLExtId headId) [AST.IfaceVarDec vecPar vectorTM] elemTM
562        -- return vec(0);
563     headExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
564                     (AST.NSimple vecPar) [AST.PrimLit "0"])))
565     lastSpec = AST.Function (mkVHDLExtId lastId) [AST.IfaceVarDec vecPar vectorTM] elemTM
566        -- return vec(vec'length-1);
567     lastExpr = AST.ReturnSm (Just $ (AST.PrimName $ AST.NIndexed (AST.IndexedName 
568                     (AST.NSimple vecPar) 
569                     [AST.PrimName (AST.NAttribute $ 
570                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
571                                                              AST.:-: AST.PrimLit "1"])))
572     initSpec = AST.Function (mkVHDLExtId initId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
573        -- variable res : fsvec_x (0 to vec'length-2);
574     initVar = 
575          AST.VarDec resId 
576                 (AST.SubtypeIn vectorTM
577                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
578                    [AST.ToRange (AST.PrimLit "0")
579                             (AST.PrimName (AST.NAttribute $ 
580                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
581                                 (AST.PrimLit "2"))   ]))
582                 Nothing
583        -- resAST.:= vec(0 to vec'length-2)
584     initExpr = AST.NSimple resId AST.:= (vecSlice 
585                                (AST.PrimLit "0") 
586                                (AST.PrimName (AST.NAttribute $ 
587                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
588                                                              AST.:-: AST.PrimLit "2"))
589     initRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
590     tailSpec = AST.Function (mkVHDLExtId tailId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
591        -- variable res : fsvec_x (0 to vec'length-2); 
592     tailVar = 
593          AST.VarDec resId 
594                 (AST.SubtypeIn vectorTM
595                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
596                    [AST.ToRange (AST.PrimLit "0")
597                             (AST.PrimName (AST.NAttribute $ 
598                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
599                                 (AST.PrimLit "2"))   ]))
600                 Nothing       
601        -- res AST.:= vec(1 to vec'length-1)
602     tailExpr = AST.NSimple resId AST.:= (vecSlice 
603                                (AST.PrimLit "1") 
604                                (AST.PrimName (AST.NAttribute $ 
605                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
606                                                              AST.:-: AST.PrimLit "1"))
607     tailRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
608     takeSpec = AST.Function (mkVHDLExtId takeId) [AST.IfaceVarDec nPar   naturalTM,
609                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM
610        -- variable res : fsvec_x (0 to n-1);
611     takeVar = 
612          AST.VarDec resId 
613                 (AST.SubtypeIn vectorTM
614                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
615                    [AST.ToRange (AST.PrimLit "0")
616                                ((AST.PrimName (AST.NSimple nPar)) AST.:-:
617                                 (AST.PrimLit "1"))   ]))
618                 Nothing
619        -- res AST.:= vec(0 to n-1)
620     takeExpr = AST.NSimple resId AST.:= 
621                     (vecSlice (AST.PrimLit "1") 
622                               (AST.PrimName (AST.NSimple $ nPar) AST.:-: AST.PrimLit "1"))
623     takeRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
624     dropSpec = AST.Function (mkVHDLExtId dropId) [AST.IfaceVarDec nPar   naturalTM,
625                                    AST.IfaceVarDec vecPar vectorTM ] vectorTM 
626        -- variable res : fsvec_x (0 to vec'length-n-1);
627     dropVar = 
628          AST.VarDec resId 
629                 (AST.SubtypeIn vectorTM
630                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
631                    [AST.ToRange (AST.PrimLit "0")
632                             (AST.PrimName (AST.NAttribute $ 
633                               AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
634                                (AST.PrimName $ AST.NSimple nPar)AST.:-: (AST.PrimLit "1")) ]))
635                Nothing
636        -- res AST.:= vec(n to vec'length-1)
637     dropExpr = AST.NSimple resId AST.:= (vecSlice 
638                                (AST.PrimName $ AST.NSimple nPar) 
639                                (AST.PrimName (AST.NAttribute $ 
640                                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) 
641                                                              AST.:-: AST.PrimLit "1"))
642     dropRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
643     plusgtSpec = AST.Function (mkVHDLExtId plusgtId) [AST.IfaceVarDec aPar   elemTM,
644                                        AST.IfaceVarDec vecPar vectorTM] vectorTM 
645     -- variable res : fsvec_x (0 to vec'length);
646     plusgtVar = 
647       AST.VarDec resId 
648              (AST.SubtypeIn vectorTM
649                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
650                 [AST.ToRange (AST.PrimLit "0")
651                         (AST.PrimName (AST.NAttribute $ 
652                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
653              Nothing
654     plusgtExpr = AST.NSimple resId AST.:= 
655                    ((AST.PrimName $ AST.NSimple aPar) AST.:&: 
656                     (AST.PrimName $ AST.NSimple vecPar))
657     plusgtRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
658     emptySpec = AST.Function (mkVHDLExtId emptyId) [] vectorTM
659     emptyVar = 
660           AST.ConstDec resId 
661               (AST.SubtypeIn vectorTM Nothing)
662               (Just $ AST.PrimLit "\"\"")
663     emptyExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
664     singletonSpec = AST.Function (mkVHDLExtId singletonId) [AST.IfaceVarDec aPar elemTM ] 
665                                          vectorTM
666     -- variable res : fsvec_x (0 to 0) := (others => a);
667     singletonVar = 
668       AST.VarDec resId 
669              (AST.SubtypeIn vectorTM
670                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
671                 [AST.ToRange (AST.PrimLit "0") (AST.PrimLit "0")]))
672              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
673                                           (AST.PrimName $ AST.NSimple aPar)])
674     singletonRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
675     copynSpec = AST.Function (mkVHDLExtId copynId) [AST.IfaceVarDec nPar   naturalTM,
676                                    AST.IfaceVarDec aPar   elemTM   ] vectorTM 
677     -- variable res : fsvec_x (0 to n-1) := (others => a);
678     copynVar = 
679       AST.VarDec resId 
680              (AST.SubtypeIn vectorTM
681                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
682                 [AST.ToRange (AST.PrimLit "0")
683                             ((AST.PrimName (AST.NSimple nPar)) AST.:-:
684                              (AST.PrimLit "1"))   ]))
685              (Just $ AST.Aggregate [AST.ElemAssoc (Just AST.Others) 
686                                           (AST.PrimName $ AST.NSimple aPar)])
687     -- return res
688     copynExpr = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
689     selSpec = AST.Function (mkVHDLExtId selId) [AST.IfaceVarDec fPar   naturalTM,
690                                AST.IfaceVarDec sPar   naturalTM,
691                                AST.IfaceVarDec nPar   naturalTM,
692                                AST.IfaceVarDec vecPar vectorTM ] vectorTM
693     -- variable res : fsvec_x (0 to n-1);
694     selVar = 
695       AST.VarDec resId 
696                 (AST.SubtypeIn vectorTM
697                   (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
698                     [AST.ToRange (AST.PrimLit "0")
699                       ((AST.PrimName (AST.NSimple nPar)) AST.:-:
700                       (AST.PrimLit "1"))   ])
701                 )
702                 Nothing
703     -- for i res'range loop
704     --   res(i) := vec(f+i*s);
705     -- end loop;
706     selFor = AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [selAssign]
707     -- res(i) := vec(f+i*s);
708     selAssign = let origExp = AST.PrimName (AST.NSimple fPar) AST.:+: 
709                                 (AST.PrimName (AST.NSimple iId) AST.:*: 
710                                   AST.PrimName (AST.NSimple sPar)) in
711                                   AST.NIndexed (AST.IndexedName (AST.NSimple resId) [AST.PrimName (AST.NSimple iId)]) AST.:=
712                                     (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) [origExp]))
713     -- return res;
714     selRet =  AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
715     ltplusSpec = AST.Function (mkVHDLExtId ltplusId) [AST.IfaceVarDec vecPar vectorTM,
716                                         AST.IfaceVarDec aPar   elemTM] vectorTM 
717      -- variable res : fsvec_x (0 to vec'length);
718     ltplusVar = 
719       AST.VarDec resId 
720         (AST.SubtypeIn vectorTM
721           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
722             [AST.ToRange (AST.PrimLit "0")
723               (AST.PrimName (AST.NAttribute $ 
724                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))]))
725         Nothing
726     ltplusExpr = AST.NSimple resId AST.:= 
727                      ((AST.PrimName $ AST.NSimple vecPar) AST.:&: 
728                       (AST.PrimName $ AST.NSimple aPar))
729     ltplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
730     plusplusSpec = AST.Function (mkVHDLExtId plusplusId) [AST.IfaceVarDec vec1Par vectorTM,
731                                              AST.IfaceVarDec vec2Par vectorTM] 
732                                              vectorTM 
733     -- variable res : fsvec_x (0 to vec1'length + vec2'length -1);
734     plusplusVar = 
735       AST.VarDec resId 
736         (AST.SubtypeIn vectorTM
737           (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
738             [AST.ToRange (AST.PrimLit "0")
739               (AST.PrimName (AST.NAttribute $ 
740                 AST.AttribName (AST.NSimple vec1Par) (mkVHDLBasicId lengthId) Nothing) AST.:+:
741                   AST.PrimName (AST.NAttribute $ 
742                 AST.AttribName (AST.NSimple vec2Par) (mkVHDLBasicId lengthId) Nothing) AST.:-:
743                   AST.PrimLit "1")]))
744        Nothing
745     plusplusExpr = AST.NSimple resId AST.:= 
746                      ((AST.PrimName $ AST.NSimple vec1Par) AST.:&: 
747                       (AST.PrimName $ AST.NSimple vec2Par))
748     plusplusRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
749     lengthTSpec = AST.Function (mkVHDLExtId lengthTId) [AST.IfaceVarDec vecPar vectorTM] naturalTM
750     lengthTExpr = AST.ReturnSm (Just $ AST.PrimName (AST.NAttribute $ 
751                                 AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing))
752     shiftlSpec = AST.Function (mkVHDLExtId shiftlId) [AST.IfaceVarDec vecPar vectorTM,
753                                    AST.IfaceVarDec aPar   elemTM  ] vectorTM 
754     -- variable res : fsvec_x (0 to vec'length-1);
755     shiftlVar = 
756      AST.VarDec resId 
757             (AST.SubtypeIn vectorTM
758               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
759                [AST.ToRange (AST.PrimLit "0")
760                         (AST.PrimName (AST.NAttribute $ 
761                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
762                            (AST.PrimLit "1")) ]))
763             Nothing
764     -- res := a & init(vec)
765     shiftlExpr = AST.NSimple resId AST.:=
766                     (AST.PrimName (AST.NSimple aPar) AST.:&:
767                      (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
768                        [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
769     shiftlRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
770     shiftrSpec = AST.Function (mkVHDLExtId shiftrId) [AST.IfaceVarDec vecPar vectorTM,
771                                        AST.IfaceVarDec aPar   elemTM  ] vectorTM 
772     -- variable res : fsvec_x (0 to vec'length-1);
773     shiftrVar = 
774      AST.VarDec resId 
775             (AST.SubtypeIn vectorTM
776               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
777                [AST.ToRange (AST.PrimLit "0")
778                         (AST.PrimName (AST.NAttribute $ 
779                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
780                            (AST.PrimLit "1")) ]))
781             Nothing
782     -- res := tail(vec) & a
783     shiftrExpr = AST.NSimple resId AST.:=
784                   ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
785                     [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
786                   (AST.PrimName (AST.NSimple aPar)))
787                 
788     shiftrRet = AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)      
789     nullSpec = AST.Function (mkVHDLExtId nullId) [AST.IfaceVarDec vecPar vectorTM] booleanTM
790     -- return vec'length = 0
791     nullExpr = AST.ReturnSm (Just $ 
792                 AST.PrimName (AST.NAttribute $ 
793                   AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:=:
794                     AST.PrimLit "0")
795     rotlSpec = AST.Function (mkVHDLExtId rotlId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
796     -- variable res : fsvec_x (0 to vec'length-1);
797     rotlVar = 
798      AST.VarDec resId 
799             (AST.SubtypeIn vectorTM
800               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
801                [AST.ToRange (AST.PrimLit "0")
802                         (AST.PrimName (AST.NAttribute $ 
803                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
804                            (AST.PrimLit "1")) ]))
805             Nothing
806     -- if null(vec) then res := vec else res := last(vec) & init(vec)
807     rotlExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
808                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
809                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
810                         []
811                         (Just $ AST.Else [rotlExprRet])
812       where rotlExprRet = 
813                 AST.NSimple resId AST.:= 
814                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId lastId))  
815                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
816                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId initId))  
817                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
818     rotlRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)       
819     rotrSpec = AST.Function (mkVHDLExtId rotrId) [AST.IfaceVarDec vecPar vectorTM] vectorTM 
820     -- variable res : fsvec_x (0 to vec'length-1);
821     rotrVar = 
822      AST.VarDec resId 
823             (AST.SubtypeIn vectorTM
824               (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
825                [AST.ToRange (AST.PrimLit "0")
826                         (AST.PrimName (AST.NAttribute $ 
827                           AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
828                            (AST.PrimLit "1")) ]))
829             Nothing
830     -- if null(vec) then res := vec else res := tail(vec) & head(vec)
831     rotrExpr = AST.IfSm (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId nullId))  
832                           [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)])
833                         [AST.NSimple resId AST.:= (AST.PrimName $ AST.NSimple vecPar)]
834                         []
835                         (Just $ AST.Else [rotrExprRet])
836       where rotrExprRet = 
837                 AST.NSimple resId AST.:= 
838                       ((AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId tailId))  
839                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]) AST.:&:
840                       (AST.PrimFCall $ AST.FCall (AST.NSimple (mkVHDLExtId headId))  
841                         [Nothing AST.:=>: AST.ADExpr (AST.PrimName $ AST.NSimple vecPar)]))
842     rotrRet =  AST.ReturnSm (Just $ AST.PrimName $ AST.NSimple resId)
843     reverseSpec = AST.Function (mkVHDLExtId reverseId) [AST.IfaceVarDec vecPar vectorTM] vectorTM
844     reverseVar = 
845       AST.VarDec resId 
846              (AST.SubtypeIn vectorTM
847                (Just $ AST.ConstraintIndex $ AST.IndexConstraint 
848                 [AST.ToRange (AST.PrimLit "0")
849                          (AST.PrimName (AST.NAttribute $ 
850                            AST.AttribName (AST.NSimple vecPar) (mkVHDLBasicId lengthId) Nothing) AST.:-:
851                             (AST.PrimLit "1")) ]))
852              Nothing
853     -- for i in 0 to res'range loop
854     --   res(vec'length-i-1) := vec(i);
855     -- end loop;
856     reverseFor = 
857        AST.ForSM iId (AST.AttribRange $ AST.AttribName (AST.NSimple resId) rangeId Nothing) [reverseAssign]
858     -- res(vec'length-i-1) := vec(i);
859     reverseAssign = AST.NIndexed (AST.IndexedName (AST.NSimple resId) [destExp]) AST.:=
860       (AST.PrimName $ AST.NIndexed (AST.IndexedName (AST.NSimple vecPar) 
861                            [AST.PrimName $ AST.NSimple iId]))
862         where destExp = AST.PrimName (AST.NAttribute $ AST.AttribName (AST.NSimple vecPar) 
863                                    (mkVHDLBasicId lengthId) Nothing) AST.:-: 
864                         AST.PrimName (AST.NSimple iId) AST.:-: 
865                         (AST.PrimLit "1") 
866     -- return res;
867     reverseRet = AST.ReturnSm (Just $ AST.PrimName (AST.NSimple resId))
868     
869 -----------------------------------------------------------------------------
870 -- A table of builtin functions
871 -----------------------------------------------------------------------------
872
873 -- | The builtin functions we support. Maps a name to an argument count and a
874 -- builder function.
875 globalNameTable :: NameTable
876 globalNameTable = Map.fromList
877   [ (exId             , (2, genFCall False          ) )
878   , (replaceId        , (3, genFCall False          ) )
879   , (headId           , (1, genFCall True           ) )
880   , (lastId           , (1, genFCall True           ) )
881   , (tailId           , (1, genFCall False          ) )
882   , (initId           , (1, genFCall False          ) )
883   , (takeId           , (2, genFCall False          ) )
884   , (dropId           , (2, genFCall False          ) )
885   , (selId            , (4, genFCall False          ) )
886   , (plusgtId         , (2, genFCall False          ) )
887   , (ltplusId         , (2, genFCall False          ) )
888   , (plusplusId       , (2, genFCall False          ) )
889   , (mapId            , (2, genMap                  ) )
890   , (zipWithId        , (3, genZipWith              ) )
891   , (foldlId          , (3, genFoldl                ) )
892   , (foldrId          , (3, genFoldr                ) )
893   , (zipId            , (2, genZip                  ) )
894   , (unzipId          , (1, genUnzip                ) )
895   , (shiftlId         , (2, genFCall False          ) )
896   , (shiftrId         , (2, genFCall False          ) )
897   , (rotlId           , (1, genFCall False          ) )
898   , (rotrId           , (1, genFCall False          ) )
899   , (concatId         , (1, genConcat               ) )
900   , (reverseId        , (1, genFCall False          ) )
901   , (iteratenId       , (3, genIteraten             ) )
902   , (iterateId        , (2, genIterate              ) )
903   , (generatenId      , (3, genGeneraten            ) )
904   , (generateId       , (2, genGenerate             ) )
905   , (emptyId          , (0, genFCall False          ) )
906   , (singletonId      , (1, genFCall False          ) )
907   , (copynId          , (2, genFCall False          ) )
908   , (copyId           , (1, genCopy                 ) )
909   , (lengthTId        , (1, genFCall False          ) )
910   , (nullId           , (1, genFCall False          ) )
911   , (hwxorId          , (2, genOperator2 AST.Xor    ) )
912   , (hwandId          , (2, genOperator2 AST.And    ) )
913   , (hworId           , (2, genOperator2 AST.Or     ) )
914   , (hwnotId          , (1, genOperator1 AST.Not    ) )
915   ]