Functions

Functions are declared with def, take typed parameters and declare their return type. They can return two values, be inlined by the precompiler, take a variable number of arguments, receive parameters by reference, and be stored in function pointers.

Defining and calling

#include <libstd/stdio>

def add(a: int, b: int) -> int:
    return a + b

def greet(name: str) -> None:
    print("Hello, ", name, "\n")

greet("world")
print(add(2, 3), "\n")
Hello, world
5

Multi-line signatures

The parameter list is the only construct that may span several lines, one parameter per line:

def sub(
    a: int,
    b: int
) -> int:
    return a - b

Returning two values

A function can return a pair with -> (t1, t2); the caller receives it with a comma-separated assignment. The whole assignment must be a plain a, b = f(...) statement, not part of a larger expression. A target can also be a field or an element (req.size, req.body = read_request(fd)); they are assigned left to right, as in Python.

def divmod(a: int, b: int) -> (int, int):
    return a / b, a % b

q, r = divmod(17, 5)          // q = 3, r = 2

off, piece = split_next("a,b,c", ",", 0)   // libstd/string uses this a lot

Both values are promoted exactly like a single return value, so a pair of freshly built strings is safe to use in the caller. See The arena.

Recursion

def fact(n: long) -> long:
    if n <= 1 as long:
        return 1 as long
    return n * fact(n - 1 as long)

Each call opens an arena scope, so a recursion deeper than SCOPE_CKPT_DEPTH (16384) stops with a fatal error instead of corrupting memory.

inline def

An inline def is expanded by the precompiler: its body is copied at every call site, with the arguments substituted textually and locals renamed, so no call is generated. Use it for small helpers on hot paths. Two inline functions that call each other are detected and compiled as normal functions instead.

inline def double(n: int) -> int:
    return n * 2

x = double(21)        // becomes: x = 21 * 2 (after renaming)

--dbi shows the expanded code. An inline def whose body contains a loop with an early return is rewritten with a flag variable (see Control flow).

Variadic functions

A last parameter written *name accepts any number of extra arguments of mixed type (str, int, long, char, float, or a class/array). The callee receives them as a List of Vararg objects; a Vararg has a tag (which type the argument had), a payload (an integer, widened to 64 bits), an fpayload for floats and an rpayload (a ref) for a string, an object or an array. print in libstd/stdio is written this way.

#include <libstd/stdio>

class Punto:
    x int
    y int

def describe(label: str, *args) -> None:
    print(label, ": ")
    n = list_length(args)
    i = 0 as long
    while i < n:
        v = list_get(args, i) as Vararg
        if v.tag == typeid(Punto):
            p = v.rpayload as Punto
            print("Punto(", p.x, ",", p.y, ")")
        elif v.tag == 0:
            print(v.rpayload as str)      // tag 0 = str
        elif v.tag == 4:
            print(ftoa(v.fpayload))       // tag 4 = float
        else:
            print(itoa(v.payload))        // int/long/char
        i = i + 1 as long
    print("\n")

p = new Punto
p.x = 3
p.y = 4
describe("data", 3.5, p, 99)
data: 3.500000Punto(3,4)99

typeid(ClassName) gives the id the compiler assigned to a class in this compilation, which is what tag holds for class arguments. The fixed tags for the scalar types are constants of the runtime and should be compared through the same constants print uses rather than hard-coded.

Parameters by reference

A parameter typed &T expects the address of a variable of type T; the caller passes &variable. This is how C functions that write through an out-pointer are declared (sqlite3_open(path, &db)) and how sys_setsockopt(fd, level, opt, &flag) receives its option value.

def write_to(dest: &int) -> int:
    return 0

x = 5
write_to(&x)

Function pointers

The bare name of a function is its address. A variable holding one must be declared with the full signature, and can be reassigned to any function with the same signature; it is called exactly like a function.

def somma(a: int, b: int) -> int:
    return a + b

def sottrai(a: int, b: int) -> int:
    return a - b

op: &(int, int) -> int = somma
print(op(3, 4), "\n")     // 7
op = sottrai
print(op(3, 4), "\n")     // -1

A class can name functions as methods: libstd/re declares class CompiledPattern with search &pattern_search, and pat.search(text) is a direct call to pattern_search(pat, text). A function pointer stored in each object is a callback field, name &(t1, t2) -> ret (see Classes). A bare function name passed where a str is expected (a C callback, thread_spawn(worker, ...)) is coerced to the address automatically; the reverse direction is an explicit cast, boxed as &(str, int) -> str.

extern functions

A function implemented in a C shared library is declared with extern def after a libextern line; see Inline asm & FFI.

What a function returns, and memory

Returning a str, an array or an object allocated inside the function is the normal case and needs nothing special: the compiler promotes the returned value so that the function's scope does not free it. The rules and their limits (interior pointers, values hidden in long fields) are in The arena.