Functions
Function rules are shared across execution backends; support for a particular native or foreign signature can still vary. See Native for ABI boundaries.
Contents
Bindings and declarations
def declares an immutable binding; mut permits reassignment. An optional type annotation precedes the binding name. del clears a mutable binding; it does not free an object.
Declaration forms:
def name = expression
mut name = expression
def Type name = expression
mut Type name = expression
fn name(parameters) { body }
fn name(parameters) Type { body }
fn name(parameters) Type = expression
A function's final expression is its result when no explicit return exits first. A string literal at the start of a function body is its docstring.
Rules
defbindings cannot be reassigned;mutbindings can.delclears a mutable binding but does not release or free the referenced object.- Arguments are evaluated left to right. Omitted defaults are evaluated at the call site in declaration order, and
...restreceives extra positional arguments. - A function returns its final expression unless an explicit
returnexits first. Calls do not implicitly copy managed containers. - An attribute has only the guarantees implemented by its checker or selected backend. Check the support boundary before relying on a partial contract.
Parameters and calls
Parameters may be inferred or explicitly typed. A parameter can have a default; ...rest collects additional positional arguments. Arguments are evaluated left to right. Omitted defaults are evaluated at the call site in declaration order.
Note: These lines describe parameter and call forms;
...restis validonly in a function parameter list.
name
Type name
name = default
Type name = default
...rest
function(positional)
function(name = value)
A lambda body may be a block or one brace-free expression:
fn(parameters) { body }
fn(parameters) expression
A brace-free body parses exactly one expression and returns its value implicitly. Blocks retain their existing scope and return behavior. Function values and lambdas can capture bindings from their enclosing scope. Their parameter and return types may be inferred when the call site provides enough information. For explicit callable shapes, use fnptr where required by an API.
Partial application
A nonempty positional prefix of a fixed-arity Nytrix callable produces a residual callable when required parameters remain unsupplied. For fn add(int a, int b) int, add(5) binds a and returns a callable accepting b; both add(5)(3) and add(5, 3) return 8. The same rule applies to inferred lambda values and to successive residual applications.
The callable and bound argument expressions are evaluated once, in source order, at construction. The body is deferred until the required arguments are available. Captures retain the ordinary closure representation and ownership rules; managed values are not implicitly copied. A fully applied call is not required to materialize intermediate closures.
Defaults take precedence over automatic partial application: if the omitted arguments all have defaults, the existing default-argument call runs instead. A default may be omitted only when every later parameter is also defaulted. If a default precedes a required residual parameter, the default is evaluated inside the residual body and the required parameter remains positional. Trailing optional parameters stay overridable on the residual callable.
Residual signatures retain dependent value indices. Partially applying pick(int n, Fin<n> index, list<int> values) to n = 3 leaves a callable whose index argument is still Fin<3>, so an out-of-range index is rejected at the residual call. Bounds and defaults that reference a captured earlier parameter are substituted from the bound prefix.
A callable value held in a name can be partially applied as well; the residual closure captures that binding without erasing its call signature or effect row. Creating a partial allocates an escaping closure when it is not immediately saturated, so it is not an allocation-free operation inside a hot loop.
Zero-argument calls, variadic functions, and foreign declarations retain their existing call rules. A variadic function still requires its fixed parameters and is not automatically curried. A foreign declaration has a fixed ABI and an incomplete foreign call is rejected with an arity diagnostic. Excess arguments report the declared limit and the supplied count. An underscore is not a partial-application placeholder. Nytrix declarations continue to use type-first parameters and a return type after ), not the retired name: Type or -> spellings.
See the currying guide for complete examples and the explicit binary core.functional.curry / uncurry adapters. The regression etc/labs/tests/lang/execution/currying.nshape exercises escaped and repeated partials, grouping, evaluation order, scalar ABI boundaries, and recursion. Additional fixtures cover residual defaults, dependent indices, capture reuse, consuming-parameter rejection, variadic and foreign boundaries, fnptr conversion, higher-order callbacks, and ny-desugar parity.
Return and container behavior
return expression exits the current function. Without an explicit return, the last expression supplies the result. A function call does not implicitly copy or deep-clone a managed container; use the owning collection API or clone when a detached value is required. See Values for collection mutation and alias behavior, and Ownership for resource contracts.
Attributes
Attributes attach compiler metadata to a function. They are contracts only to the extent the checker or selected backend implements them; see Implementation status before relying on a partial rule.
| Goal | Form | Meaning |
| Declare effects | @effects(...), @pure | Restrict the effects accepted by the effect checker. @pure means no declared effects. |
| Describe ownership | @borrows(x), @returns_borrow(x), @returns_owned, @consumes(x), @mutates(x), @releases(x), @forgets(x) | State argument and return ownership facts for supported ownership checks. |
| Bound use counts | @allowance(x, [lo, hi]) | State a supported path-sensitive usage interval. |
| Require compile-time evaluation | @consteval | Mark a function for compile-time-safe evaluation. |
| Lower eligible IO calls as tasks | @async_effects | Request stackless task lowering for supported direct calls. |
| Run work on a thread | @thread | Statement-position calls detach; value-position calls join on supported routes. |
| Set a per-function optimization level | @optimize(0), @optimize(1), @optimize(2), @optimize(3) | Override NYIR optimization level for that function. |
| Guide call handling | @inline, @noinline, @tailcall, @flatten | Request supported inlining, tail-call, or flattening behavior. |
| Mark frequency or timing intent | @hot, @cold, @constant_time | Provide compiler policy metadata; target support varies. |
| Request accelerator code | @accel, @accel(spirv) | Request a validated accelerator path or receive an unsupported-target error. |
| Require target-specific code | @naked, asm(...), intrinsic(...) | Use only on a backend that supports the requested form. |
| Restrict memory access | @readnone, @readonly, @writeonly, @argmemonly | Contract on what memory the body may touch: @readnone reads nothing, @readonly only reads, @writeonly only writes, and @argmemonly touches only memory reached through arguments. |
| Promise termination behavior | @nounwind, @mustprogress | @nounwind never unwinds through panic; @mustprogress eventually returns or performs an observable effect. |
Use semantic contracts for portable behavior. Optimization hints do not replace measurement or change source-level operator precedence.
The attribute namespace is open: any @name parses, and reflection keeps the parsed attributes queryable, so generated declarations can carry template-defined markers. Behavior attaches only to the recognized forms above. @pure and @consteval imply the full contract set (@readnone, @nounwind, @willreturn, @mustprogress); the backend lowers the contracts it models into optimizer facts on each route. The fixtures etc/labs/tests/lang/types/inference/attr.nshape (memory and termination contracts preserve program behavior), etc/labs/tests/lang/comptime/comptime.nshape (template expansion preserves attributes), and etc/labs/tests/lang/comptime/reflection/reflect-metadata.nshape (reflection sees @trace and @memoize(3) as parsed attribute names) verify the contract and reflection halves.
Effect rows
An effect row records labels and, for an open row, a row variable. Calling a function contributes its latent effects; creating a closure does not execute its body. Effects describe work, not permission to access a resource, and do not replace ownership or synchronization rules.
The type layer implements open-row unification and serialized rows. Direct calls through a user helper's fnptr parameter can propagate known callback rows through supported positional and named arguments, aliases, inline lambdas, and returned callbacks. Some local aliases retain or join rows across branches, loops, and matches. Imported rows are identified by qualified function name and arity.
This is bounded callback analysis, not general callback provenance. Unknown or escaping callbacks, unsupported control-flow joins, re-export identity, and arbitrary captured callback flows remain conservative. Built-in effects still enter analysis through fixed masks. The declared mask contract remains the user-facing boundary; effect handlers and higher-rank row polymorphism are not provided by this mechanism.
Preconditions and termination measures
requires(expression) states a condition that each call must satisfy. decreases(expression) supplies a measure for supported recursive @total checks. The solver is bounded: false and unknown obligations are rejected, and decreases alone is not a termination proof. See Proofs for examples and Types for the accepted proof boundary.
Example
use core
fn clamp(int value, int lower, int upper) int {
if value < lower { return lower }
if value > upper { return upper }
value
}
#main {
assert_eq(clamp(12, 0, 10), 10, "upper bound")
}
Related
- Types for parameter and return types.
- Control Flow for exits and cleanup.
- Programs for scripts, modules, and entry points.
- Ownership for resource and borrow contracts.