There are two types of subprograms, functions and procedures. Functions are like mathematical functions and take zero or more inputs and return a single value. A procedure can have many inputs or outputs without one explicit return value. The rules for subprogram declarations are:
interface-variable : [VARIABLE] name-list ":" [mode] subtype
[":=" expression]
interface-list : interface-variable | interface-signal | interface-constant
subprogram-specification :
PROCEDURE simple-name [ "(" interface-list ")" ] |
FUNCTION simple-name [ "(" interface-list ")" ] RETURN type
subprogram-prototype : subprogram-specification ";"
subprogram-declaration-item : subprogram-prototype |
subprogram-declaration | type-declaration | subtype-declaration |
constant-declaration | variable-declaration | file-declaration |
alias-declaration | attribute-declaration |
attribute-specification
subprogram-declaration :
subprogram-specification IS
{ subprogram-declaration-item }
BEGIN
sequential-statement-list
END [simple-name] ";"
Sometimes it is necessary to refer to a subprogram that has not yet been declared. In order to do this, a subprogram prototype should appear before that reference. The prototype does not give the statement body of the subprogram, but provides the interface which is necessary to call the subprogram.
A subprogram body is the list of statements that are executed when the subprogram is called. The subprogram body is a sequential program and thus contains only sequential statements. A number of different objects can be declared in a subprogram. They are listed in the subprogram declaration item rule. If the simple name appears at the end of the declaration, then it must repeat the name of the subprogram.
An example subprogram that converts an integer to a bit_vector is
function to_bit (size: in integer; num: in integer) return bit_vector is
variable ret: bit_vector (1 to size);
variable a: integer;
begin
a:=num;
for i in size downto 1 loop
if ((a rem 2)=1) then
ret(i):='1';
else
ret(i):='0';
end if;
a:=a/2;
end loop;
return ret;
end;
There may be more than one subprogram with the same name as long as they can be distinguished by their parameter list. This feature is called subprogram overloading. For example, a function that accepts an integer input and a function that accepts a bit input can have the same name. When the function is called, the proper one is called according to the type of the actual parameter. Functions can also be used to do what is called operator overloading. A function can be declared to be designated by an operator name, overloading that operator. The syntax for an operator name is:
operator-name : """ operator """
For example,
function "+" (a,b : in bit) return bit is
begin
return a xor b;
end;
.
.
.
signal a,b,c: bit;
begin
a<=b+c;
.
.
.