\sekshun{Procedures}
\label{Functions}
\index{functions}
\index{functions!call site}
\index{call site}
\index{functions!formal arguments}
\index{formal arguments}
\index{functions!actual arguments}
\index{actual arguments}

A \emph{function} is a code abstraction that can be invoked by a call
expression. Throughout this specification the term ``function''
is used in this programming-languages sense, rather than
in the mathematical sense.
% TODO: the above is here until we substitute a different word for 'function'
A function has zero or more \emph{formal arguments}, or simply
\emph{formals}. Upon a function call each formal is associated
with the corresponding \emph{actual argument}, or simply
\emph{actual}. Actual arguments are provided as part of the call
expression, or at the the \emph{call site}.
% TODO - move into a footnote?
Direct and indirect recursion is supported.

\index{functions!procedure}
\index{procedure}
\index{functions!operator}
\index{functions!method}
\index{operators!procedure}
A function can be a \emph{procedure}, which completes and returns to
the call site exactly once, returning no result, a single result, or
multiple results aggregated in a tuple. A function can also be an
iterator, which can generate, or \emph{yield}, multiple results (in
sequence and/or in parallel). A function (either a procedure or an
iterator) can be a \emph{method} if it is bound to a type (often a
class). An \emph{operator} in this chapter is a procedure
with a special name, which can be invoked using infix notation,
i.e., via a unary or binary expression.
This chapter defines procedures, but most of its contents
apply to iterators and methods as well.

Functions are presented as follows:
\begin{itemize}
\item procedures (this chapter)
\item operators \rsec{Function_Definitions}, \rsec{Binary_Expressions}
\item iterators \rsec{Iterators}
\item methods (when bound to a class) \rsec{Class_Methods}
\item function calls \rsec{Function_Calls}
\item various aspects of defining a procedure
      \rsec{Function_Definitions}--\rsec{Nested_Functions}
\item calling external functions from Chapel
      \rsec{Calling_External_Functions}
\item calling Chapel functions from external functions\rsec{Calling_Chapel_Functions}
\item determining the function to invoke for a given call site:
      function and operator overloading \rsec{Function_Overloading},
      function resolution \rsec{Function_Resolution}
\end{itemize}


\section{Function Calls}
\label{Function_Calls}
\index{function calls}
\index{calls!function}

The syntax to call a non-method function is given by:
\begin{syntax}
call-expression:
  lvalue-expression ( named-expression-list )
  lvalue-expression [ named-expression-list ]
  parenthesesless-function-identifier

named-expression-list:
  named-expression
  named-expression , named-expression-list

named-expression:
  expression
  identifier = expression

parenthesesless-function-identifier:
  identifier
\end{syntax}


A \sntx{call-expression} is resolved to a particular function
according to the algorithm for function resolution described
in~\rsec{Function_Resolution}.

Functions can be called using either parentheses or brackets.

\begin{rationale}
This provides an opportunity to blur the distinction between
an array access and a function call and thereby exploit a
possible space/time tradeoff.
\end{rationale}

Functions that are defined without parentheses must be called without
parentheses as defined by scope resolution.  Functions without
parentheses are discussed in~\rsec{Functions_without_Parentheses}.

A \sntx{named-expression} is an expression that may be optionally
named.  It provides
\index{actual arguments}
\index{functions!actual arguments}
an actual argument to the function being called.
The optional \sntx{identifier} refers to a named formal
argument described in~\rsec{Named_Arguments}.

Calls to methods are defined in Section~\rsec{Class_Method_Calls}.


\section{Procedure Definitions}
\label{Function_Definitions}
\index{functions!procedure definition}
\index{procedures!definition}

\index{proc@\chpl{proc}}
Procedures are defined with the following syntax:
\begin{syntax}
procedure-declaration-statement:
  privacy-specifier[OPT] linkage-specifier[OPT] `proc' function-name argument-list[OPT] return-intent[OPT] return-type[OPT] where-clause[OPT]
    function-body

linkage-specifier:
  `inline'

function-name:
  identifier
  operator-name

operator-name: one of
  + $ $ $ $ - $ $ $ $ * $ $ $ $ / $ $ $ $ % $ $ $ $ ** $ $ $ $ ! $ $ $ $ == $ $ $ $ != $ $ $ $ <= $ $ $ $ >= $ $ $ $ < $ $ $ $ > $ $ $ $ << $ $ $ $ >> $ $ $ $ & $ $ $ $ | $ $ $ $ ^ $ $ $ $ ~
  += $ $ $ $ -= $ $ $ $ *= $ $ $ $ /= $ $ $ $ %= $ $ $ $ **= $ $ $ $ &= $ $ $ $ |= $ $ $ $ ^= $ $ $ $ <<= $ $ $ $ >>= $ $ $ $ <=> $ $ $ $ <~>

argument-list:
  ( formals[OPT] )

formals:
  formal
  formal , formals

formal:
  formal-intent[OPT] identifier formal-type[OPT] default-expression[OPT]
  formal-intent[OPT] identifier formal-type[OPT] variable-argument-expression
  formal-intent[OPT] tuple-grouped-identifier-list formal-type[OPT] default-expression[OPT]
  formal-intent[OPT] tuple-grouped-identifier-list formal-type[OPT] variable-argument-expression

formal-type:
  : type-specifier
  : ? identifier[OPT]

default-expression:
  = expression

variable-argument-expression:
  ... expression
  ... ? identifier[OPT]
  ...

formal-intent:
  `const'
  `const in'
  `const ref'
  `in'
  `out'
  `inout'
  `ref'
  `param'
  `type'

return-intent:
  `const'
  `const ref'
  `ref'
  `param'
  `type'

return-type:
  : type-specifier

where-clause:
  `where' expression

function-body:
  block-statement
  return-statement
\end{syntax}

%% This should be in the order that the sections appear in this
%% chapter (if they appear in this chapter).

Functions do not require parentheses if they have no arguments.  Such
functions are described in~\rsec{Functions_without_Parentheses}.

Formal arguments can be grouped together using a tuple notation as
described in~\rsec{Formal_Argument_Declarations_in_a_Tuple}.

Default expressions allow for the omission of actual arguments at the
call site, resulting in the implicit passing of a default value.
Default values are discussed in~\rsec{Default_Values}.

The intents \chpl{const}, \chpl{const in}, \chpl{const
ref}, \chpl{in}, \chpl{out}, \chpl{inout} and \chpl{ref} are discussed
in~\rsec{Argument_Intents}.  The intents \chpl{param} and \chpl{type} make a
function generic and are discussed in~\rsec{Generic_Functions}.  If
the formal argument's type is omitted, generic, or prefixed with a
question mark, the function is also generic and is discussed
in~\rsec{Generic_Functions}.

Functions can take a variable number of arguments.  Such functions are
discussed in~\rsec{Variable_Length_Argument_Lists}.

The \sntx{return-intent} can be used to indicate how the value is returned from
a function.  \sntx{return-intent} is described further in \rsec{Return_Intent}.
% TODO: define lvalue and rvalue

\begin{openissue}
Parameter and type procedures are supported. Parameter and type
iterators are currently not supported.
\end{openissue}

The \sntx{return-type} is optional and is discussed in~\rsec{Return_Types}.
A type function may not specify a return type.

The optional \sntx{where-clause} is only applicable if the function is
generic.  It is discussed in~\rsec{Where_Expressions}.

Function and operator overloading is supported in Chapel and is
discussed in~\rsec{Function_Overloading}.
Operator overloading is supported on the operators listed
above (see \sntx{operator-name}).

The optional \sntx{privacy-specifier} keywords indicate the visibility
of module level procedures to outside modules.  By default, procedures are
publicly visible.  More details on visibility can be found in
~\rsec{Visibility_Of_Symbols}.

The linkage specifier \chpl{inline} indicates that the function body must be inlined at
every call site.

See the chapter on interoperability (\rsec{Interoperability})
for details on exported and imported functions.

\section{Functions without Parentheses}
\label{Functions_without_Parentheses}
\index{functions!without parentheses}

Functions do not require parentheses if they have empty argument
lists.  Functions declared without parentheses around empty argument
lists must be called without parentheses.

\begin{chapelexample}{function-no-parens.chpl}
Given the definitions
\begin{chapel}
proc foo { writeln("In foo"); }
proc bar() { writeln("In bar"); }
\end{chapel}
\begin{chapelpost}
foo;
bar();
\end{chapelpost}
\begin{chapeloutput}
In foo
In bar
\end{chapeloutput}
the procedure \chpl{foo} can be called by writing \chpl{foo} and the
procedure \chpl{bar} can be called by writing \chpl{bar()}.  It is an
error to use parentheses when calling \chpl{foo} or omit them
when calling \chpl{bar}.
\end{chapelexample}


\section{Formal Arguments}
\label{Formal_Arguments}
\index{formal arguments}
\index{functions!formal arguments}
\index{functions!arguments!formal}

A formal argument's intent~(\rsec{Argument_Intents}) specifies how the
actual argument is passed to the function.  If no intent is specified,
the default intent~(\rsec{The_Default_Intent}) is applied, resulting in
type-dependent behavior.

\subsection{Named Arguments}
\label{Named_Arguments}
\index{named arguments}
\index{functions!named arguments}
\index{functions!arguments!named}
\index{formal arguments!naming}

A formal argument can be named at the call site to explicitly map an
actual argument to a formal argument.

\begin{chapelexample}{named-args.chpl}
Running the code
\begin{chapel}
proc foo(x: int, y: int) { writeln(x); writeln(y); }

foo(x=2, y=3);
foo(y=3, x=2);
\end{chapel}
will produce the output
\begin{chapelprintoutput}{}
2
3
2
3
\end{chapelprintoutput}
named argument passing is used to map the actual arguments to the
formal arguments.  The two function calls are equivalent.
\end{chapelexample}

Named arguments are sometimes necessary to disambiguate calls or
ignore arguments with default values.  For a function that has many
arguments, it is sometimes good practice to name the arguments at the
call site for compiler-checked documentation.

\subsection{Default Values}
\label{Default_Values}
\index{default values}
\index{functions!default argument values}
\index{functions!arguments!defaults}
\index{formal arguments!defaults}

Default values can be specified for a formal argument by appending the
assignment operator and a default expression to the declaration of the
formal argument.  If the actual argument is omitted from the function
call, the default expression is evaluated when the function call is
made and the evaluated result is passed to the formal argument as if
it were passed from the call site.

\begin{chapelexample}{default-values.chpl}
The code
\begin{chapel}
proc foo(x: int = 5, y: int = 7) { writeln(x); writeln(y); }

foo();
foo(7);
foo(y=5);
\end{chapel}
writes out
\begin{chapelprintoutput}{}
5
7
7
7
5
5
\end{chapelprintoutput}
Default values are specified for the formal arguments \chpl{x}
and \chpl{y}.  The three calls to \chpl{foo} are equivalent to the
following three calls where the actual arguments are
explicit: \chpl{foo(5, 7)}, \chpl{foo(7, 7)}, and \chpl{foo(5, 5)}.
The example \chpl{foo(y=5)} shows how to use a named argument
for \chpl{y} in order to use the default value for \chpl{x} in the
case when \chpl{x} appears earlier than \chpl{y} in the formal
argument list.
\end{chapelexample}


\section{Argument Intents}
\label{Argument_Intents}
\index{intents}
\index{argument!intents}
\index{functions!arguments!intents}

Argument intents specify how an actual argument is passed to a
function where it is represented by the corresponding formal argument.

Argument intents are categorized as being either \emph{concrete}
or \emph{abstract}.  Concrete intents are those in which the semantics
of the intent keyword are independent of the argument's type.
Abstract intents are those in which the keyword (or lack thereof)
expresses a general intention that will ultimately be implemented via
one of the concrete intents.  The specific choice of concrete intent
depends on the argument's type and may be implementation-defined.
Abstract intents are provided to support productivity and code reuse.

\subsection{Concrete Intents}
\label{Concrete Intents}
\index{intents!concrete}

The concrete intents are \chpl{in}, \chpl{out}, \chpl{inout},
\chpl{ref}, \chpl{const in}, and \chpl{const ref}.

\subsubsection{The In Intent}
\label{The_In_Intent}
\index{in (intent)@\chpl{in} (intent)}
\index{intents!in@\chpl{in}}

When \chpl{in} is specified as the intent, the actual argument is
copied into the formal argument when the function is called.
An implicit conversion occurs from the actual argument
to the type of the formal.  The
formal can be modified within the function, but such changes are local
to the function and not reflected back to the call site.


\subsubsection{The Out Intent}
\label{The_Out_Intent}
\index{out (intent)@\chpl{out} (intent)}
\index{intents!out@\chpl{out}}

When \chpl{out} is specified as the intent, the actual argument is
ignored when the call is made, but when the function returns, the
formal argument is copied back to the actual argument.
An implicit conversion occurs from the type of the formal
to the type of the actual.  The actual argument
must be a valid lvalue.  The formal
argument is initialized to its default value if one is supplied, or to
its type's default value otherwise.  The formal argument can be
modified within the function.


\subsubsection{The Inout Intent}
\label{The_Inout_Intent}
\index{inout (intent)@\chpl{inout} (intent)}
\index{intents!inout@\chpl{inout}}

When \chpl{inout} is specified as the intent, the actual argument is
copied into the formal argument as with the \chpl{in} intent and then
copied back out as with the \chpl{out} intent.  The actual argument
must be a valid lvalue.  The formal argument can be modified within
the function.
The type of the actual argument must be the same
as the type of the formal.


\subsubsection{The Ref Intent}
\label{The_Ref_Intent}
\index{ref (intent)@\chpl{ref} (intent)}
\index{intents!ref@\chpl{ref}}

When \chpl{ref} is specified as the intent, the actual argument is
passed by reference.  Any reads of, or modifications to, the formal
argument are performed directly on the corresponding actual argument
at the call site.  The actual argument must be a valid lvalue.
The type of the actual argument must be the same
as the type of the formal.

The \chpl{ref} intent differs from the \chpl{inout} intent in that
the \chpl{inout} intent requires copying from/to the actual argument on
the way in/out of the function, while \chpl{ref} allows direct
access to the actual argument through the formal argument without
copies.  Note that concurrent modifications to the \chpl{ref} actual argument by
other tasks may be visible within the function, subject to the memory
consistency model.


\subsubsection{The Const In Intent}
\label{The_Const_In_Intent}
\index{const in (intent)@\chpl{const in} (intent)}
\index{intents!const in@\chpl{const in}}

The \chpl{const in} intent is identical to the \chpl{in} intent,
except that modifications to the formal argument are prohibited within
the function.


\subsubsection{The Const Ref Intent}
\label{The_Const_Ref_Intent}
\index{const ref (intent)@\chpl{const ref} (intent)}
\index{intents!const ref@\chpl{const ref}}

The \chpl{const ref} intent is identical to the \chpl{ref} intent,
except that modifications to the formal argument are prohibited within
the dynamic scope of the function.  Note that concurrent tasks may
modify the actual argument while the function is executing and that
these modifications may be visible to reads of the formal argument
within the function's dynamic scope (subject to the memory consistency
model).

\subsubsection{Summary of Concrete Intents}
\label{Summary_of_Concrete_Intents}

The following table summarizes the differences between the concrete
intents:

\begin{center}
\begin{tabular}[c]{|l|c|c|c|c|c|c|}
\hline
                                       & \chpl{in} & \chpl{out} & \chpl{inout} & \chpl{ref} & \chpl{const in} & \chpl{const ref} \\
\hline
\hline
copied in on function call?      & yes & no  & yes & no  & yes & no  \\
copied out on function return?   & no  & yes & yes & no  & no  & no  \\
refers to actual argument?       & no  & no  & no  & yes & no  & yes \\
formal can be read?              & yes & yes & yes & yes & yes & yes \\
formal can be modified?          & yes & yes & yes & yes & no  & no  \\
local changes affect the actual? & no  & on return & on return & immediately & N/A & N/A \\
\hline
\end{tabular}
\end{center}


\subsection{Abstract Intents}
\label{Abstract Intents}
\index{intents!abstract}

The abstract intents are \chpl{const} and the \emph{default intent}
(when no intent is specified).

\subsubsection{The Const Intent}
\label{The_Const_Intent}
\index{intents!const@\chpl{const}}

The \chpl{const} intent specifies the intention that the function will
not and cannot modify the formal argument within its dynamic scope,
yet leaves unspecified whether the actual argument will be passed
by \chpl{const in} or \chpl{const ref} intent.  In general, small
values, such as scalar types, will be passed by \chpl{const in}; while
larger values, such as domains and arrays, will be passed
by \chpl{const ref} intent.  At present, the decision between the two
mechanisms is implementation-defined.  If a user's function is
sensitive to which mechanism is used, they should use the desired
concrete intent to guarantee portability.

\begin{openissue}
It remains an open issue whether the choice between \chpl{const in}
and \chpl{const ref} should be defined by the language, either for
certain types or for all of them.  One area of active debate is
whether the implementation can choose between \chpl{const in}
and \chpl{const ref} for records based on size.  Another open issue is
how tuples should be handled with respect to \chpl{const} intents.
\end{openissue}

\begin{craychapel}
The current implementation uses the following mapping:

\begin{center}
\begin{tabular}[c]{|l|c|}
\hline
     & meaning \\
type & of \chpl{const} \\
\hline
\hline
\chpl{bool}    & \chpl{const in}  \\
\chpl{int}     & \chpl{const in}  \\
\chpl{uint}    & \chpl{const in}  \\
\chpl{real}    & \chpl{const in}  \\
\chpl{imag}    & \chpl{const in}  \\
\chpl{complex} & \chpl{const in}  \\
\chpl{string}  & \chpl{const ref} \\
\chpl{sync}    & \chpl{const ref} \\
\chpl{single}  & \chpl{const ref} \\
\chpl{atomic}  & \chpl{const in}  \\
\chpl{record}  & \chpl{const ref} \\
\chpl{class}   & \chpl{const in}  \\
\chpl{union}   & \chpl{const in}  \\
\chpl{dmap}    & \chpl{const ref} \\
\chpl{domain}  & \chpl{const ref} \\
array          & \chpl{const ref} \\
\hline
\end{tabular}
\end{center}

\end{craychapel}



\subsubsection{The Default Intent}
\label{The_Default_Intent}
\index{intents!default}

When no intent is specified for a formal argument, the \emph{default
intent} is applied.  It is designed to take the most natural/least
surprising action for the argument, based on its type.  The following
table shows how default intents are interpreted based on the argument's
type:

\begin{center}
\begin{tabular}[c]{|l|c|}
\hline
     & meaning of \\
type & default intent \\
\hline
\hline
\chpl{bool}    & \chpl{const} \\
\chpl{int}     & \chpl{const} \\
\chpl{uint}    & \chpl{const} \\
\chpl{real}    & \chpl{const} \\
\chpl{imag}    & \chpl{const} \\
\chpl{complex} & \chpl{const} \\
\chpl{string}  & \chpl{const} \\
\chpl{sync}    & \chpl{ref}   \\
\chpl{single}  & \chpl{ref}   \\
\chpl{atomic}  & \chpl{ref}   \\
\chpl{record}  & \chpl{const} \\
\chpl{class}   & \chpl{const} \\
\chpl{union}   & \chpl{const} \\
\chpl{dmap}    & \chpl{const} \\
\chpl{domain}  & \chpl{const} \\
array          & \chpl{ref}   \\
\hline
\end{tabular}
\end{center}

\begin{openissue}
How tuples should be handled under default intents is an open issue;
particularly for heterogeneous tuples whose components would fall into
separate categories in the table above.  One proposed approach is to
apply the default intent to each component of the tuple independently.

Another open issue arises if the meaning of the \chpl{const} intent is
not defined by the language completely. If so, should the meaning of
the default intent have that same flexibility? In particular, should the
default intent for records mean \chpl{const} or \chpl{const in}?
\end{openissue}


\section{Variable Number of Arguments}
\label{Variable_Length_Argument_Lists}
\index{functions!variable number of arguments}
\index{functions!varargs}

Functions can be defined to take a variable number of arguments where
those arguments can have any intent or can be types.  A variable
number of parameters is not supported.  This allows the call site to
pass a different number of actual arguments.  There must be at least
one actual argument.

If the variable argument expression contains an identifier prepended by a
question mark, the number of actual arguments can vary, and the identifier
will be bound to an integer parameter value indicating the number of
arguments at a given call site.
If the variable argument expression contains an expression without
a question mark, that expression must evaluate to an integer parameter value
requiring the call site to pass that number of arguments to the
function.

Within the function, the formal argument that is marked with a
variable argument expression is a tuple of the actual
arguments.

\begin{chapelexample}{varargs.chpl}
The code
\begin{chapel}
proc mywriteln(x ...?k) {
  for param i in 1..k do
    writeln(x(i));
}
\end{chapel}
\begin{chapelpost}
mywriteln("hi", "there");
mywriteln(1, 2.0, 3, 4.0);
\end{chapelpost}
\begin{chapeloutput}
hi
there
1
2.0
3
4.0
\end{chapeloutput}
defines a generic procedure called \chpl{mywriteln} that takes a
variable number of arguments of any type and then writes them out on
separate lines.  The parameter for-loop~(\rsec{Parameter_For_Loops})
is unrolled by the compiler so that \chpl{i} is a parameter, rather
than a variable.  This needs to be a parameter for-loop because the
expression \chpl{x(i)} will have a different type on each iteration.
The type of \chpl{x} can be specified in the formal argument list to
ensure that the actuals all have the same type.
\end{chapelexample}

\begin{chapelexample}{varargs-with-type.chpl}
Either or both the number of variable arguments and their types can be
specified.  For example, a basic procedure to sum the values of three
integers can be written as
\begin{chapel}
proc sum(x: int...3) return x(1) + x(2) + x(3);
\end{chapel}
\begin{chapelpost}
writeln(sum(1, 2, 3));
writeln(sum(-1, -2, -3));
\end{chapelpost}
\begin{chapeloutput}
6
-6
\end{chapeloutput}
Specifying the type is useful if it is important that each argument
have the same type.  Specifying the number is useful in, for example,
defining a method on a class that is instantiated over a rank
parameter.
\end{chapelexample}

\begin{chapelexample}{varargs-returns-tuples.chpl}
The code
\begin{chapel}
proc tuple(x ...) return x;
\end{chapel}
\begin{chapelpost}
writeln(tuple(1));
writeln(tuple("hi", "there"));
writeln(tuple(tuple(1, 2), tuple(3, 4)));
\end{chapelpost}
\begin{chapeloutput}
(1)
(hi, there)
((1, 2), (3, 4))
\end{chapeloutput}
defines a generic procedure that is equivalent to building a tuple.
Therefore the expressions \chpl{tuple(1, 2)} and \chpl{(1,2)} are equivalent,
as are the expressions \chpl{tuple(1)} and \chpl{(1,)}.
\end{chapelexample}


\section{Return Intents}
\label{Return_Intent}
\index{functions!return intent}

The \sntx{return-intent} specifies how the value is returned from a function,
and in what contexts that function is allowed to be used.  By default, or if
the \sntx{return-intent} is \chpl{const}, the function returns a value that
cannot be used as an lvalue.

% TODO: it's a little jarring that the above talks about returning
% a value when e.g. a type function does not return a value at all
% (since it returns a type).
% It would probably be better to consider type and param return
% functions "type functions" or "param functions" and leave this
% section to only discuss const/ref/const ref return intents.

\subsection{The Ref Return Intent}
\label{Ref_Return_Intent}
\index{functions!ref keyword and@\chpl{ref} keyword and}
\index{ref (return intent)@\chpl{ref} (return intent)}
\index{intents!ref return@\chpl{ref} return}
\index{functions!lvalues}

When using a \chpl{ref} return intent, the function call is an lvalue
(specifically, a call expression for a procedure and an iterator variable for
an iterator).

The \chpl{ref} return intent is specified by following the argument list with
the \chpl{ref} keyword.  The function must return or yield an lvalue.

\begin{chapelexample}{ref-return-intent.chpl}
The following code defines a procedure that can be interpreted as a
simple two-element array where the elements are actually module
level variables:
\begin{chapel}
var x, y = 0;

proc A(i: int) ref {
  if i < 0 || i > 1 then
    halt("array access out of bounds");
  if i == 0 then
    return x;
  else
    return y;
}
\end{chapel}
Calls to this procedure can be assigned to in order to write to the ``elements''
of the array as in
\begin{chapel}
A(0) = 1;
A(1) = 2;
\end{chapel}
It can be called as an expression to access the ``elements'' as in
\begin{chapel}
writeln(A(0) + A(1));
\end{chapel}
This code outputs the number \chpl{3}.

\begin{chapeloutput}
3
\end{chapeloutput}
\end{chapelexample}


\subsection{The Const Ref Return Intent}
\label{Const_Ref_Return_Intent}
\index{functions!const ref keyword and@\chpl{const ref} keyword and}
\index{const ref (return intent)@\chpl{const ref} (return intent)}
\index{intents!const ref return@\chpl{const ref} return}

The \chpl{const ref} return intent is also available. It is a restricted
form of the \chpl{ref} return intent. Calls to functions marked with
the \chpl{const ref} return intent are not lvalue expressions.

\subsection{Choosing a Ref Return Intent Function Based on Calling Context}
\label{Ref_Pair}
\index{functions!ref-pair}

In some situations, it is useful to distinguish between calls that are
used in an lvalue setting and those that are not. In particular, suppose
that there are two functions that have the same formal arguments and
differ only in their return intent. Normally, such a situation will cause
an error since it is ambiguous which function is called. However, the
Chapel language includes a special rule for determining which function to
call when one of the calls is an lvalue and the other is not.  This rule
enables data structures such as sparse arrays.

This special rule is called the ref-pair rule. If, when resolving a call,
there are two candidate functions where:

\begin{itemize}
\item
 one of them uses the \chpl{ref} return intent and the other uses
 \chpl{const}, \chpl{const ref}, or blank return intent
\item
 either both use promotion or neither do
\end{itemize}

then this pair of candidate functions is called a ref-pair.

When such a call appears on the left-hand side of an assignment
statement, is returned in a function with \chpl{ref} return intent, or
appears in a call and corresponds to a formal argument with \chpl{out},
\chpl{inout}, or \chpl{ref} intent, the candidate with the \chpl{ref}
return intent is used. Otherwise, the other candidate is used.

% TODO - this section, or a significant portion of it,
% should move to the function resolution section.

\begin{chapelexample}{ref-return-intent-pair.chpl}

\index{functions!ref-pair}
A ref-pair can be used to ensure, for
example, that the second element in the pseudo-array is only assigned
a value if the first argument is positive.  The following is an
example:
\begin{chapel}
var x, y = 0;

proc doA(param setter, i: int) ref {
  if i < 0 || i > 1 then
    halt("array access out of bounds");

  if setter && i == 1 && x <= 0 then
    halt("cannot assign value to A(1) if A(0) <= 0");

  if i == 0 then
    return x;
  else
    return y;
}
proc A(i: int) ref {
  return doA(true, i);
}
proc A(i: int) {
  return doA(false, i);
}

A(0) = 0;
A(1) = 1;

\end{chapel}
\begin{chapeloutput}
ref-return-intent-pair.chpl:8: error: halt reached - cannot assign value to A(1) if A(0) <= 0
\end{chapeloutput}
\end{chapelexample}


\subsection{The Param Return Intent}
\label{Param_Return_Intent}
\index{functions!as parameters}
\index{functions!parameter function}
\index{parameter function}

A \emph{parameter function}, or a \emph{param function}, is a function that
returns a parameter expression.  It is specified by following the function's
argument list by the keyword \chpl{param}.  It is often, but not necessarily,
generic.

It is a compile-time error if a parameter function does not return a
parameter expression.  The result of a parameter function is computed
during compilation and substituted for the call expression.

\begin{chapelexample}{param-functions.chpl}
In the code
\begin{chapel}
proc sumOfSquares(param a: int, param b: int) param
  return a**2 + b**2;

var x: sumOfSquares(2, 3)*int;
\end{chapel}
\begin{chapelpost}
writeln(x);
\end{chapelpost}
\begin{chapeloutput}
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
\end{chapeloutput}
\chpl{sumOfSquares} is a parameter procedure that takes
two parameters as arguments.  Calls to this procedure can be used in
places where a parameter expression is required.  In this example, the
call is used in the declaration of a homogeneous tuple and so is
required to be a parameter.
\end{chapelexample}

Parameter functions may not contain control flow that is not resolved
at compile-time.  This includes loops other than the parameter for
loop~\rsec{Parameter_For_Loops} and conditionals with a conditional
expressions that is not a parameter.


\subsection{The Type Return Intent}
\label{Type_Return_Intent}
\index{functions!as types}
\index{functions!type functions}

A \emph{type function} is a function that returns a type, not a value.  It is
specified by following the function's argument list by the keyword \chpl{type},
without the subsequent return type.  It is often, but not necessarily, generic.

It is a compile-time error if a type function does not return a type.
The result of a type function is computed during compilation.

As with parameter functions, type functions may not contain control
flow that is not resolved at compile-time.  This includes loops other
than the parameter for loop~\rsec{Parameter_For_Loops} and
conditionals with a conditional expression that is not a parameter.

\begin{chapelexample}{type-functions.chpl}
In the code
\begin{chapel}
proc myType(x) type {
  if numBits(x.type) <= 32 then return int(32);
  else return int(64);
}
\end{chapel}
\begin{chapelpost}
var a = 4: int(32),
    b = 4.0;
var at: myType(a),
    bt: myType(b);
writeln((numBits(at.type), numBits(bt.type)));
\end{chapelpost}
\begin{chapeloutput}
(32, 64)
\end{chapeloutput}
\chpl{myType} is a type procedure that takes a single
argument \chpl{x} and returns \chpl{int(32)} if the number of bits used to
represent \chpl{x} is less than or equal to 32, otherwise it
returns \chpl{int(64)}.  \chpl{numBits} is a param
procedure defined in the standard Types module.
\end{chapelexample}


\section{The Return Statement}
\label{The_Return_Statement}
\index{return@\chpl{return}}
\index{statements!return}

The return statement can only appear in a function.  It causes control
to exit that function, returning it to the point at which that function
was called.

A procedure can return a value by executing a return statement
that includes an expression. If it does, that expression's value
becomes the value of the invoking call expression.

A return statement in a procedure of a non-\chpl{void} return type
(\rsec{Return_Types}) must include an expression.
A return statement in a procedure of a \chpl{void} return type
or in an iterator must not include an expression.
A return statement of a variable procedure must contain an lvalue expression.

% TODO: currently our implementation does not require that a user return
% statement be executed for a procedure of a non-void return type.
% If execution falls through to the end, the default value of the
% return type is returned.
% Do we want to formalize that or to disallow that?

The syntax of the return statement is given by
\begin{syntax}
return-statement:
  `return' expression[OPT] ;
\end{syntax}

\begin{chapelexample}{return.chpl}
The following code defines a procedure that returns the sum of three
integers:
\begin{chapel}
proc sum(i1: int, i2: int, i3: int)
  return i1 + i2 + i3;
\end{chapel}
\begin{chapelpost}
writeln(sum(1, 2, 3));
\end{chapelpost}
\begin{chapeloutput}
6
\end{chapeloutput}
\end{chapelexample}


\section{Return Types}
\label{Return_Types}
\index{return@\chpl{return}!types}
\index{functions!return types}

Every procedure has a return type. The return type is either
specified explicitly via \sntx{return-type} in the procedure
declaration, or is inferred implicitly.

% TODO: both subsections below state that the return type
% must match the type of each returned expression for variable procedures
% and that an implicit conversion occurs for non-variable procedures.
% Factor that out up here.

\subsection{Explicit Return Types}
\label{Explicit_Return_Types}
\index{explicit return type}
\index{functions!return types!explicit}

If a return type is specified and is not \chpl{void},
each return statement of the procedure must include an expression.
For a non-\chpl{ref} return intent, an implicit conversion occurs
from each return expression to the specified return type.
For a \chpl{ref} return intent~(\rsec{Ref_Return_Intent}), the return
type must match the type returned in all of the return statements
exactly, when checked after generic instantiation and parameter folding
(if applicable).

\subsection{Implicit Return Types}
\label{Implicit_Return_Types}
\index{type inference!of return types}
\index{implicit return type}
\index{functions!return types!implicit}

If a return type is not specified, it is inferred from the return statements.
It is illegal for a procedure to have a return statement with an expression
and a return statement without an expression.
For procedures without any return statements, or when none of the
return statements include an expression, the return type is \chpl{void}.

Otherwise, the types of the expressions in all of the procedure's
return statements are considered.
If a function has a \chpl{ref} return intent (\rsec{Ref_Return_Intent}), they
all must be the same exact type, which becomes the inferred return type.
Otherwise, there must exist exactly one type such that an implicit conversion
is allowed between every other type and that type, and that type becomes the
inferred return type.
If the above requirements are not satisfied, it is an error.

\section{Nested Functions}
\label{Nested_Functions}
\index{functions!nested}
\index{nested function}

A function defined in another function is called a nested function.
Nesting of functions may be done to arbitrary degrees, i.e., a
function can be nested in a nested function.

Nested functions are only visible to function calls within the lexical scope
in which they are defined.

Nested functions may refer to variables defined in the function(s) in
which they are nested.


\section{Function and Operator Overloading}
\label{Function_Overloading}
\index{overloading}
\index{overloading functions (see also functions, overloading)}
\index{overloading operators (see also operators, overloading)}
\index{functions!overloading}
\index{operators!overloading}

Functions that have the same name but different argument lists are
called overloaded functions.  Function calls to overloaded functions
are resolved according to the function resolution algorithm in~\rsec{Function_Resolution}.

Operator overloading is achieved by defining a function with a name
specified by that operator.  The operators that may be overloaded are
listed in the following table:

\begin{center}
\begin{tabular}{|l|l|}
\hline
{\bf arity} & {\bf operators} \\
\hline
unary & \verb@+ - ! ~@ \\
binary & \verb@+ - * / % ** == <= >= < > << >> & | ^ by@ \\
& \verb@+= -= *= /= %= **= &= |= ^= <<= >>= <=> <~>@ \\
\hline
\end{tabular}
\end{center}

The arity and precedence of the operator must be maintained when it is
overloaded.  Operator resolution follows the same algorithm as
function resolution.


\section{Function Resolution}
\label{Function_Resolution}
\index{functions!resolution}

\emph{Function resolution} is the algorithm that determines
which function to invoke for a given call expression.
Function resolution is defined as follows.
\begin{itemize}
\item
Identify the set of visible functions for the function call.  A
\emph{visible function} is any function that satisfies the criteria
in~\rsec{Determining_Visible_Functions}.  If no visible function can
be found, the compiler will issue an error stating that the call
cannot be resolved.
\item
From the set of visible functions for the function call, determine the
set of candidate functions for the function call.  A \emph{candidate
function} is any function that satisfies the criteria
in~\rsec{Determining_Candidate_Functions}.  If no candidate function
can be found, the compiler will issue an error stating that the call
cannot be resolved.  If exactly one candidate function is found, this
is determined to be the function.
\item
From the set of candidate functions, the most specific function is
determined.  The most specific function is a candidate function that
is \emph{more specific} than every other candidate function as defined
in~\rsec{Determining_More_Specific_Functions}.  If there is no
function that is more specific than every other candidate function,
the compiler will issue an error stating that the call is ambiguous.
\end{itemize}

\subsection{Determining Visible Functions}
\label{Determining_Visible_Functions}
\index{functions!visible}

Given a function call, a function is determined to be a \emph{visible
function} if the name of the function is the same as the name of the
function call and the function is defined in the same scope as the
function call or a lexical outer scope of the function call, or if the
function is publicly declared in a module that is used from the same
scope as the function call or a lexical outer scope of the function
call.  Function visibility in generic functions is discussed
in~\rsec{Function_Visibility_in_Generic_Functions}.

\subsection{Determining Candidate Functions}
\label{Determining_Candidate_Functions}
\index{functions!candidates}

Given a function call, a function is determined to be
a \emph{candidate function} if there is a \emph{valid mapping} from
the function call to the function and each actual argument is mapped
to a formal argument that is a \emph{legal argument mapping}.

\subsubsection{Valid Mapping}
\label{Valid_Mapping}
\index{functions!resolution!valid mapping}

The following algorithm determines a valid mapping from a function
call to a function if one exists:
\begin{itemize}
\item
Each actual argument that is passed by name is matched to the formal
argument with that name.  If there is no formal argument with that
name, there is no valid mapping.
\item
The remaining actual arguments are mapped in order to the remaining
formal arguments in order.  If there are more actual arguments then
formal arguments, there is no valid mapping.  If any formal argument
that is not mapped to by an actual argument does not have a default
value, there is no valid mapping.
\item
The valid mapping is the mapping of actual arguments to formal
arguments plus default values to formal arguments that are not mapped
to by actual arguments.
\end{itemize}

\subsubsection{Legal Argument Mapping}
\label{Legal_Argument_Mapping}
\index{functions!resolution!legal argument mapping}

An actual argument of type $T_A$ can be mapped to a formal argument of
type $T_F$ if any of the following conditions hold:
\begin{itemize}
\item $T_A$ and $T_F$ are the same type.
\item There is an implicit conversion from $T_A$ to $T_F$.
\item $T_A$ is derived from $T_F$.
\item $T_A$ is scalar promotable to $T_F$.
\end{itemize}

\subsection{Determining More Specific Functions}
\label{Determining_More_Specific_Functions}
\index{functions!most specific}
\index{functions!resolution!most specific}

Given two functions $F_1$ and $F_2$, the more specific function is
determined by the following steps:
\begin{itemize}
\item If $F_1$ does not require promotion and $F_2$ does require promotion, then $F_1$ is more specific.
\item If $F_2$ does not require promotion and $F_1$ does require promotion, then $F_2$ is more specific.
\item
If at least one of the legal argument mappings to $F_1$ is a {\em more
specific argument mapping} than the corresponding legal argument
mapping to $F_2$ and none of the legal argument mappings to $F_2$ is a
more specific argument mapping than the corresponding legal argument
mapping to $F_1$, then $F_1$ is more specific.
\item
If at least one of the legal argument mappings to $F_2$ is a {\em more
specific argument mapping} than the corresponding legal argument
mapping to $F_1$ and none of the legal argument mappings to $F_1$ is a
more specific argument mapping than the corresponding legal argument
mapping to $F_2$, then $F_2$ is more specific.
\item If $F_1$ shadows $F_2$, then $F_1$ is more specific.
\item If $F_2$ shadows $F_1$, then $F_2$ is more specific.
\item If all \chpl{param} arguments prefer $F_1$ over $F_2$, then $F_1$ is more specific.  In order of preference, a \chpl{param} argument prefers to be passed to (a) a \chpl{param} formal of matching type; (b) a \chpl{param} formal large enough to store the \chpl{param} value; (c) a non-\chpl{param} formal of matching type.
\item If all \chpl{param} arguments prefer $F_2$ over $F_1$, then $F_2$ is more specific.
\item If $F_1$ has a where clause and $F_2$ does not have a where clause, then $F_1$ is more specific.
\item If $F_2$ has a where clause and $F_1$ does not have a where clause, then $F_2$ is more specific.
\item Otherwise neither function is more specific.
\end{itemize}

Given an argument mapping, $M_1$, from an actual argument, $A$, of
type $T_A$ to a formal argument, $F1$, of type $T_{F1}$ and an
argument mapping, $M_2$, from the same actual argument to a formal
argument, $F2$, of type $T_{F2}$, the more specific argument mapping
is determined by the following steps:
\begin{itemize}
\item
 If $T_{F1}$ and $T_{F2}$ are the same type, $F1$ is an instantiated
 parameter, and $F2$ is not an instantiated parameter, $M_1$ is more
 specific.
\item
 If $T_{F1}$ and $T_{F2}$ are the same type, $F2$ is an instantiated
 parameter, and $F1$ is not an instantiated parameter, $M_2$ is more
 specific.
\item
 If $M_1$ does not require scalar promotion and $M_2$ requires scalar
 promotion, $M_1$ is more specific.
\item
 If $M_1$ requires scalar promotion and $M_2$ does not require scalar
 promotion, $M_2$ is more specific.
\item
 If $T_{F1}$ and $T_{F2}$ are the same type, $F1$ is generic, and $F2$
 is not generic, $M_1$ is more specific.
\item
 If $T_{F1}$ and $T_{F2}$ are the same type, $F2$ is generic, and $F1$
 is not generic, $M_2$ is more specific.
\item
 If $F1$ is not generic over all types and $F2$ is generic over all
 types, $M_1$ is more specific.
\item
 If $F1$ is generic over all types and $F2$ is not generic over all
 types, $M_2$ is more specific.
\item
 If $T_A$ and $T_{F1}$ are the same type and $T_A$ and $T_{F2}$ are
 not the same type, $M_1$ is more specific.
\item
 If $T_A$ and $T_{F1}$ are not the same type and $T_A$ and $T_{F2}$
 are the same type, $M_2$ is more specific.
\item
 If $T_{F1}$ is derived from $T_{F2}$, then $M_1$ is more specific.
\item
 If $T_{F2}$ is derived from $T_{F1}$, then $M_2$ is more specific.
\item
 If there is an implicit conversion from $T_{F1}$ to $T_{F2}$, then
 $M_1$ is more specific.
\item
 If there is an implicit conversion from $T_{F2}$ to $T_{F1}$, then
 $M_2$ is more specific.
\item
 If $T_{F1}$ is any \chpl{int} type and $T_{F2}$ is any \chpl{uint}
 type, $M_1$ is more specific.
\item
 If $T_{F2}$ is any \chpl{int} type and $T_{F1}$ is any \chpl{uint}
 type, $M_2$ is more specific.
\item
 Otherwise neither mapping is more specific.
\end{itemize}
