Function Declarations
This page covers function modifiers, visibility, ABI and linkage, and forward declarations.
Function Modifiers
Modifiers appear after the parameter list and before the return type arrow. Multiple modifiers can be combined, subject to the compatibility rules below. inline and eval may also be written before fn (pub inline fn twice(x: i32) -> i32); both positions mean the same thing.
fn compute(x: i32) inline -> i32 { return x * x }
fn dangerous() unsafe -> void { /* ... */ }
fn compile_time() eval -> i32 { return 42 }
fn may_fail() panic -> i32 { /* ... */ }
fn background() async -> Data { /* ... */ }
Modifier reference
| Modifier | Free functions | Methods | Description |
|---|---|---|---|
const | fn f(...) const (after the parameters) | const self | A method does not modify self (see Variables); a free const function reads only its inputs (see Const functions) |
volatile | Yes | Yes | Prevents certain compiler optimizations; for hardware interaction |
unsafe | Yes | Yes | Separate overload namespace for alternative implementations |
eval | Yes | Yes | Must be evaluable at compile time. See Eval |
async | Yes | Yes | Asynchronous execution. See Concurrency |
panic | Yes | Yes | May panic; callers must handle. panic(E1, E2) declares the set. See Panic |
inline | Yes | Yes | Puts the body in the interface. See inline |
final | Yes | Prevents override in subclasses. See Classes |
inline
inline puts the body in the interface: importers compile it themselves. Use it for small functions on hot paths, and for functions the C++ compiler calls on your behalf (coroutine promises and awaiters).
pub inline fn twice(x: i32) -> i32 { return x * 2 }
Every module that can see the declaration gets the definition and compiles it, so the optimizer can inline the call there. In C++ terms it is an inline function: one shared definition that the linker merges across objects. It is not a request to force inlining.
- An
inlinefunction must have a body, in the same file as its declaration (an in-class declaration may be defined out of line in that file). Aninlinedeclaration with no body is an error. - Every declaration of the function must agree on
inline. - Unused
inlinebodies cost parse time only: no code is generated for one nothing calls.
Const functions
A free function marked const after its parameters, fn f(...) const, reads strictly its inputs: no global memory, nothing through a pointer. It is a function in the mathematical sense, like sin or abs, and the compiler may merge two calls with the same arguments, hoist a call out of a loop, or drop one whose result is unused. In the generated C++ it is [[gnu::const]]. A function that keeps this promise without writing const is found and treated the same way by default (function hints; -fno-infer-purity turns it off).
fn lerp(a: f64, b: f64, t: f64) const -> f64 {
return a + (b - a) * t
}
Because the optimizer acts on the promise without looking, the compiler checks it. A const function must return a value (on a function without a result the promise means nothing, and the compiler offers to remove it), must not be -> ! or @unwind, and its result type must not own memory (a string, a vector, a record holding one). In its body these are errors:
- reading or writing a global or
staticvariable (anevalconstant is a compile-time value, not memory, and is allowed); - dereferencing a pointer:
*p,p->field, or indexing a pointer withp[i]; - reading a parameter passed by reference:
@inout,@move, or aconstparameter of a class or struct type. A by-value parameter is a copy and may be read, fields included; - calling a function that is not itself const, an
eval fnor a side-effect-free compiler intrinsic (a hint such as__builtin_expect; not__builtin_trapor the memory and atomic intrinsics). A user operator is a call too, including the two you do not write as one: the@implicit op asan implicit conversion runs, and theop ==amatchpattern runs when it compares a value against a constant. A call through a function value or an interface requirement is always an error; - making a value that owns memory: a
string(a string literal or an f-string included), a vector or a map, a local of such a type, or a by-value copy of one passed to another function; - anything that can stop the program instead of returning:
assert,unwrap!, an asserting downcast,crash!(); - a
for ... inloop over anything but a range (0..n) or a fixed-size array: the iterator calls it makes are not checked; delete, inline C++,spawn,threadandawait.
panic is allowed: it returns an error value, it does not unwind.
Each error carries a note on the function's head: 'lerp' is const: it may read only its own inputs.
A const function is a free function. A method says the weaker thing, that it does not change its object, with const self; a trailing const on a method is an error. The leading spelling const fn f() is an error too, with a fix-it: const before a name reads as a binding.
class Vec2 {
var x: f64
var y: f64
fn len(const self) -> f64 { /* a const method: reads self, changes nothing */ }
// fn len2(self) const -> f64 { ... } // error: write 'fn len2(const self)'
}
A function that may read globals or pointed-to memory, but writes nothing, is @pure instead.
Modifier compatibility
Not all modifiers can be combined:
| Combination | Valid | Reason |
|---|---|---|
const + volatile | ok: | |
const + unsafe | unsafe: implies a separate overload with different invariants | |
const + eval | eval: implies compile-time evaluation const self is meaningless | |
const + async | ok: | |
unsafe + any other | ok: | unsafe: creates a separate overload the other modifiers apply to both versions as appropriate |
eval + unsafe | ok: | eval and unsafe are orthogonal modifiers |
eval + any other (except unsafe) | eval implies compile-time evaluation incompatible with runtime modifiers | |
async + const | ok: | |
async + volatile | ok: |
Visibility
A top-level function with no visibility written is priv to its file, or prot to its module when a module.k sits at or above the file. Write pub on what other modules may use.
| Keyword | Scope of a top-level function |
|---|---|
pub | Any module that imports this module |
priv | Current file only |
prot | Current file and sibling files in the same library subtree |
pub fn api() { /* ... */ }
fn helper() { /* ... */ } // priv, or prot under a module.k
priv fn internal_helper() { /* ... */ }
prot fn library_helper() { /* ... */ }
See Modules for how visibility interacts with imports. Methods follow the member rules in Classes.
ABI and Linkage
ABI modifiers control name mangling, dispatch mechanism, and symbol visibility at the object code level.
| Modifier | Description |
|---|---|
ffi "c" | C linkage no name mangling. See C/C++ Interop |
ffi "c++" | C++ linkage Itanium or MSVC mangling. See C/C++ Interop |
static | Internal linkage; no vtable dispatch. Cannot be virtual or override |
virtual | Dynamic dispatch via vtable. See Classes |
override | Overrides a virtual method from a base class; implies virtual |
static, virtual, and override are mutually exclusive with each other. ffi can be combined with any of them.
class Shape {
virtual fn area(const self) -> f64 { return 0.0 }
}
class Circle derives Shape {
var radius: f64
override fn area(const self) -> f64 {
return 3.14159 * self.radius * self.radius
}
}
class Math {
static fn sqrt(x: f64) -> f64 { /* ... */ }
}
Math::sqrt(16.0) // called without an instance
Forward Declarations
A function can be declared without a body a signature followed by no block:
fn parse_expression(tokens: [Token]) -> Expr
fn parse_statement(tokens: [Token]) -> Stmt
Within a single module, forward declarations are rarely needed. Kairo hoists all top-level declarations before type checking, so mutual recursion works without them:
fn is_even(n: u32) -> bool = if n == 0 => true else => is_odd(n - 1)
fn is_odd(n: u32) -> bool = if n == 0 => false else => is_even(n - 1)
Forward declarations are used when the definition lives elsewhere:
-
FFI imports the body is provided by a C or C++ library. See C/C++ Interop.
-
Separate translation units the declaration is visible to callers; the definition is linked in from another
.kfile. -
Out-of-line class methods declared in the class body, defined outside it using the
Class::methodqualified-name syntax:class Parser { var pos: usize fn advance(self) -> Token fn peek(const self) -> Token } fn Parser::advance(self) -> Token { var t = self.tokens[self.pos] self.pos += 1 return t } fn Parser::peek(const self) -> Token = self.tokens[self.pos]See Classes for the full rules.
Signature matching
When a definition follows a forward declaration, the two must match exactly:
- Parameter types, return type, and all function modifiers (
const,unsafe,panic,eval,async,inline,final,volatile) - Visibility (
pub,priv,prot) - ABI linkage (
ffi "c",ffi "c++",static,virtual,override) - Calling convention (
@preserve_most,@preserve_all,@preserve_none, or none); see Calling conventions
Parameter names may differ; the definition's names are used in the body. So may the names of generic parameters: fn <T impl Graph> g(x: T) -> i32 and a later fn <U impl Graph> g(x: U) -> i32 { ... } are one function. Their bounds may not: a declaration and its definition must name the same bounds for each generic parameter. (Two generic functions that both have bodies and differ only in their bounds are two overloads.) Defaults are not part of the match: each parameter's default may be written on any one declaration, and it applies to every call (see Defaults apply to the whole function).
A mismatch in any other element is a compile error.
Calling conventions
A calling convention decides which registers a call may clobber. Every function uses the platform's C convention unless it carries one of three attributes, each an LLVM calling convention:
| Attribute | LLVM | clang |
|---|---|---|
@preserve_most | preserve_mostcc | [[clang::preserve_most]] |
@preserve_all | preserve_allcc | [[clang::preserve_all]] |
@preserve_none | preserve_nonecc | [[clang::preserve_none]] |
@preserve_most and @preserve_all pass arguments and return values exactly as the C convention does; only the set of registers the callee must save changes. @preserve_none also passes arguments in more registers than C does, which only matters to code that is not Kairo (and none can call it; see below).
@preserve_most
priv fn grow_slow(v: *Buffer, need: usize) { /* rare: reallocate and copy */ }
fn push(v: *Buffer, x: u8) {
if v->len == v->cap { grow_slow(v, 1) } // the hot caller keeps its registers
v->data[v->len] = x
v->len += 1
}
Who saves what
| x86-64 | AArch64 | |
|---|---|---|
| C convention (callee saves) | rbx, rbp, r12-r15 (Windows adds rdi, rsi, xmm6-xmm15) | x19-x28, x29, x30, low 64 bits of v8-v15 |
@preserve_most | every general-purpose register except r11 and the return registers; floating-point and vector registers stay caller-saved | every general-purpose register except x0-x8 and x16-x18 (adds x9-x15 to C's set); floating-point and vector registers as in C |
@preserve_all | as @preserve_most, plus every XMM/YMM register | as @preserve_most, plus the floating-point and SIMD registers |
@preserve_none | nothing but rsp and rbp | nothing but the frame pointer, link register and sp |
When to use each
@preserve_most: a rarely taken slow path (growing a buffer, refilling a cache, reporting an error) called from hot integer code. The hot caller keeps its values in the registers they are already in instead of saving them around the call; the slow path pays for the saves instead.@preserve_all: the same, when the hot caller also keeps floating-point or SIMD values live across the call.@preserve_none: tail-call-heavy dispatch, such as an interpreter's opcode handlers, where each handler jumps to the next and nothing needs to survive a call.
None of them changes inlining: the optimizer may still inline the function, and the convention then applies only to the calls that remain.
Rules
- One per function. Two different conventions on one function is an error naming both (SC133E).
- Every declaration agrees. A forward declaration and its definition, or an in-class declaration and its out-of-line definition, carry the same convention (Signature matching). A convention alone never makes two declarations distinct overloads: the same signature with a different convention is a redeclaration error.
- Not on functions called by code Kairo does not write: a constructor, a destructor (
op finally), any operator,main, a generator, anasyncfunction, a closure or aneval fn(SC134E). - One convention per override set. A
virtualoroverridemethod may carry a convention only if every method it overrides or is overridden by carries the same one (SC135E). - Not across the C/C++ boundary. GCC has no spelling for these conventions, so a function C or C++ can see may not carry one: an
ffi "c"/ffi "c++"declaration, or any function that is notpriv, written or by default (an unmarked function isprivwhen nomodule.kis above its file; under one it isprotand is in the header). Such a function is in the module's emitted C++ header and its#include "x.k"interface. Aprivor local function is fine (SC136E). - x86-64 and AArch64 only, on any operating system. On any other target the attribute is an error, never silently ignored (SC137E).
In a function type
The convention is part of a function's type: fn(usize, usize) @preserve_most -> unsafe *u8 (the attribute after the parameter list, before the modifiers and ->). A function with a convention converts only to a fn type with the same convention, in either direction; converting to or from the default convention is a type mismatch. Because closures cannot have a convention, a value of such a type always holds a named function, and it is a plain function pointer, called directly. An interface requirement may carry a convention, and a conforming method must match it exactly.
Stability across LLVM versions
LLVM documents these conventions as not stable across releases. Every object that defines or calls a function with one records which conventions it uses and the LLVM major that compiled it in its ABI note, and kld refuses to link two such objects built by different LLVM majors:
error: '@preserve_most' is used by a.o (LLVM 22) and b.o (LLVM 23); this calling convention is not stable across LLVM versions; rebuild both
Objects that use none of the conventions are never compared.