Functions¶
A function declaration defines a callable symbol, its parameter interface, an optional return type, and an executable body.
::clamp FUNCTION(@value I32, @minimum I32, @maximum I32): I32
{
IF (value < minimum)
{
RETURN minimum;
}
IF (value > maximum)
{
RETURN maximum;
}
RETURN value;
}
An ordinary function declaration always has a body. Signature-only functions
occur in interfaces and generic surfaces, while external declarations use
EXTERN_PROCEDURE.
Definitions¶
Function: A function is a section of code declared with the FUNCTION keyword.
Functum: A functum is a collection of 1 or more functions defined in same symbol. For example, two separate ::squareroot functions declared for F32 and F64 inputs comprise a single unified functum.
Functanoid: The concrete instantiation of a function applied to specific argument types. Functions can have formal parameters with so-called temploidic types, such as AUTO, in which case a single function can have multiple associated functanoids.
Procedure: A unit of generated machine code which is executable. It's possible for a single functanoid to have multiple associated procedures, such as with and without AVX512.
Calls in coroutines¶
The controller's optional
CO_FUNCTUM_CALL(@FUNCTUM binding, @ARGUMENTS arguments) hook intercepts ordinary
call expressions before overload resolution. The hook takes precedence over
CO_FUNCTION_CALL and CO_COROUTINE_CALL. It receives the complete callable
binding and the evaluated argument pack. The binding retains a bound receiver
and its virtual dispatch behavior. A receiver supplied separately from the
callable binding appears as RECEIVER in the pack. An explicitly specialized
callable retains its specialization.
The hook can inspect and select overloads, change arguments, select a child
controller, or replace the invocation. The original arguments do not need to
match an overload. The hook supplies any implicit controller argument required
by its selected target.
Coroutine invocations that otherwise use CO_COROUTINE_CALL, including
overloaded operator invocations, also use this hook.
CO_FUNCTUM_CALL executes as a synchronous FUNCTION and returns an awaitable.
The coroutine implicitly awaits that result through CO_AWAIT. The awaiter's
result determines the call expression's value and reference category. Each
explicit argument expression executes once, and argument temporaries and borrowed
operands survive the await. An inherited hook participates in interception. A
present hook with an incompatible or inaccessible signature is a compilation error.
Lifecycle operations, synchronous compiler-generated operations, BIND_CALL,
RUN, GO, and synchronous hook bodies use their respective invocation protocols.
When CO_FUNCTUM_CALL is absent, the following rules apply.
An ordinary function call expression in a coroutine can be intercepted by the
controller's optional CO_FUNCTION_CALL(@FUNCTION descriptor, @ARGUMENTS arguments)
hook. Overload resolution selects the function before interception. The hook
receives the selected descriptor and the evaluated argument pack, returns an
awaitable, and executes as a synchronous FUNCTION. The coroutine implicitly
awaits that result through CO_AWAIT. The awaiter's result determines the call
expression's value and reference category.
Each explicit argument expression executes once. The descriptor retains a bound receiver, including its virtual dispatch behavior. Parameter conversions and default argument evaluation occur when the hook invokes or captures the descriptor. The hook can defer the invocation or replace its result. Argument temporaries and borrowed operands remain alive through the await.
A controller without CO_FUNCTION_CALL executes ordinary function calls directly.
A present hook with an incompatible signature is a compilation error. Compiler
protocol calls and lifecycle operations retain their own invocation rules.
Bindings containing coroutine overloads use CO_COROUTINE_CALL; RUN and GO
use CO_RUN and CO_GO respectively.
Exception contract¶
Ordinary functions may propagate exceptions. The NOEXCEPT modifier requires
exception handling to complete before control leaves the callable:
::fallback_value FUNCTION() NOEXCEPT: I32
{
TRY
{
THROW I32(@OTHER 17);
}
CATCH error CONST& I32
{
RETURN error;
}
RETURN 0;
}
An escaping exception terminates execution at this boundary; an outer caller cannot catch it. See Exception Handling for local handling, cleanup, and constexpr behavior.
NOEXCEPT_IF(condition) applies the same exception boundary when condition
evaluates to TRUE. A FALSE condition permits exception propagation. The
condition must be a constant expression accepted as BOOL and is evaluated in
the selected function's context, including template arguments and deduced
parameter types.
::exchange FUNCTION(@left MUT& AUTO(t), @right MUT& AUTO(t))
NOEXCEPT_IF(IS_NOEXCEPT_SWAPPABLE(t))
{
left <-> right;
}
The exception specification follows the parameter list and precedes ENABLE_IF,
the return type, constructor delegates, and the body. A declaration accepts one
exception specification. Duplicate specifications and combinations of NOEXCEPT
and NOEXCEPT_IF are invalid. The evaluated specification determines the
NOEXCEPT qualification of a procedure pointer formed from the function.
An invalid condition is a compilation error. Destructors are implicitly
non-throwing; an explicit NOEXCEPT_IF(FALSE) disables that implicit contract.
Named parameters¶
@api_name Type declares a named parameter. The API name is written explicitly
at multi-argument call sites and is also the default local name:
::divide FUNCTION(@numerator I32, @denominator I32): I32
{
RETURN numerator / denominator;
}
VAR result I32 := divide(@numerator 20, @denominator 4);
@api_name:local_name gives the body a different local spelling without
changing the call interface:
@ARG is the conventional name for a one-argument interface. A call with one
bare argument binds it to @ARG:
The bare form is limited to exactly one argument. Other calls write every named
argument as @name expression.
Positional parameters¶
%local_name Type declares a positional parameter:
::sum_pair FUNCTION(%left I32, %right I32): I32
{
RETURN left + right;
}
ASSERT(sum_pair(% [4, 5]) == 9);
%IGNORED Type consumes one positional argument without introducing a local
name. Positional arguments are passed in % [...] groups. A signature may mix
named and positional parameters; argument mapping uses the named API names and
the source order of positional formals independently.
Variadic positional parameters¶
%...name Type consumes the remaining positional values as a pack.
%...IGNORED Type accepts the pack without naming it.
Only one positional pack is permitted, and no ordinary positional parameter may follow it. Pack element types are checked or deduced as described in Variadic Packs.
Keyword argument capture¶
A final @KWARGS ... parameter captures unmatched named arguments in a
pack. @KWARGS:options ... names the local pack options. An empty capture
is valid, and the fields preserve supplied argument types. Pack inspection,
FUSE, and FISSION operate on the capture. FORWARD PACK(options) TO callable
consumes the capture and supplies its fields as call arguments. The spelling
@... is not accepted. See Packs for the complete capture rules.
Named pack parameters such as @funcs ... and @args ... each accept one
explicitly supplied pack. Multiple named pack parameters can appear in the
same declaration. Their arguments bind before unmatched arguments enter
KWARGS:
::apply FUNCTION(@funcs ..., @args ..., @KWARGS ...): I32
{
VAR callback EMIT FIELD("callback") FROM (funcs);
RETURN FORWARD PACK(args) TO callback;
}
The reserved arguments THIS, RETURN, and CONTROLLER cannot be captured by
a named argument pack. A CONTROLLER argument requires an explicit parameter
in the selected declaration.
Parameter types and access¶
Value parameters initialize a local parameter object. Reference types express access to the caller's object:
CONST& Tpermits reads;MUT& Tpermits reads and writes;WRITE& Tis a pure output destination that the callee must initialize before reading;TEMP& Tbinds the temporary-value category;AUTO& AUTOdeduces a reference and its qualifier.
Pointer and procedure types are ordinary parameter types. AUTO, AUTO(name),
and composite patterns make the function deduced for the concrete call; see
Type Queries and Deduction and
Overload Resolution.
Default arguments¶
DEFAULT(expression) follows the parameter type:
Omitted parameters with defaults are initialized at the call. Missing required parameters make the function non-viable. Full declaration-context and overload rules are on Default Arguments.
Return type¶
The return type follows : after the parameter list and any ENABLE_IF:
Omitting : Type declares a VOID function. AUTO and other type patterns can
deduce the result from value-returning paths. Every reachable exit must satisfy
the selected result contract. See RETURN Statements.
An ordinary function can return a static type or callable binding. The binding's identity forms part of the return type. The function executes normally, including its side effects, while a binding without a runtime value requires no runtime return storage. Return paths must agree on the binding's identity.
Overloads and ENABLE_IF¶
Several declarations may share a name when their callable signatures differ:
Parameter binding, type adaptation, template deduction, candidate priorities,
and ENABLE_IF determine the selected declaration. ENABLE_IF(condition) is
written after the parameter list and before the return type:
::small_width FUNCTION(@ARG AUTO(value_type))
ENABLE_IF(BITS(value_type) < 32 AS I32): I32
{
RETURN BITS(value_type) AS I32;
}
Its condition is evaluated for the concrete candidate instantiation. See Overload Resolution for the complete ranking rules.
Member and nested functions¶
Within a structure, . declares an instance member and :: declares a nested
function that receives no object:
::counter STRUCT
{
.value VAR I32;
.read FUNCTION() CONST: I32
{
RETURN .value;
}
.set FUNCTION(@ARG I32) MUT
{
.value := ARG;
}
::zero FUNCTION(): counter
{
RETURN counter();
}
}
The suffix MUT, CONST, WRITE, or TEMP declares the receiver qualifier
and is equivalent to an explicit @THIS <qualifier>& THISTYPE parameter.
THIS names the current object; .member is shorthand for its member.
Receiver and field rules are detailed on Structures.
Calls and function values¶
Named and positional call arguments are evaluated in source order before the selected function body begins. Calls may target a function symbol, member, procedure pointer, or callable function value. See Call Arguments and Procedure Pointers and Function Values.
Initialization parameters¶
NVALUE[T] declares an initialization parameter whose argument identifies
uninitialized destination storage for T. Ordinary functions, lambdas, and
callable objects may declare these parameters. Forwarding an initialization
parameter passes the original destination storage through ordinary overload
resolution.
::construct_number FUNCTION(@INITVAL NVALUE[I32])
{
INIT := 42;
}
::forward_number FUNCTION(@INITVAL NVALUE[I32])
{
construct_number(@INITVAL INITVAL);
RETURN;
}
INIT selects the constructor of the current function's named @INITVAL
parameter. Its accepted forms are:
INIT;
INIT := expression;
INIT FROM expression;
INIT FROM CHECKED expression;
INIT :(@argument expression);
INIT :[expression, expression];
FROM accepts the same conversion modes as NEW. Constructor selection and
argument adaptation follow ordinary construction rules. INIT does not return;
subsequent statements and exit cleanup execute normally. A VOID function may
fall through after successful initialization.
Every normal function exit requires every initialization parameter to contain a
completed object. Branches, loops, and lexical scopes preserve and validate this
state. Reading an uninitialized destination, initializing a completed destination,
forwarding a destination twice, or consuming a completed output before return is
ill-formed. Uninitialized destinations cannot escape through lambda captures or
stored aliases. NVALUE[T] is a parameter type. It cannot be a variable or field
type, a function return type, an array element, a pointer or reference target, or
a type admitted by typed storage.
Normal return transfers the completed output to the caller. Exceptional exit destroys completed outputs and partially constructed subobjects through ordinary cleanup. The caller treats an output as completed only after its call returns normally. This rule applies through forwarding chains.