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