Functions¶
Declaration¶
Parameters are name: Type. The return type follows ->. Functions that return nothing use -> none.
Every argument is passed in a register, so a function can take at most 8
parameters. self takes one of them, so a method or interface method can
take at most 7 besides self. The same limit holds for externs, function
literals and function types such as func(int64) -> int64, in a type alias
too; going past it is an error where the function, literal or type is
written (`f` takes 9 parameters, but a function can take at most 8),
not again at each call through it. When that is in another module, the
error is reported at each call through it instead. To pass more, group
them in a struct.
Calling¶
The arguments are worked out left to right, each once, before the body runs.
A small function or method whose whole body is return of an expression made
of its parameters, literals, operators and field reads, with int64, bool
or float64 parameters (a method's self may be a struct) and result, like
add above or a method func area(self) -> int64 { return self.w * self.h },
is compiled in place at each call instead of being called. So is a short
body of statements (let of a number or bool, assignments, if, for with
a condition, break, continue, return and calls, but no match,
for x in, try, is or function literal) whose parameters, none of them
mut, are numbers, bools or structs, and whose result is a number, a bool or
nothing; a struct argument must then be a local name, as self must. It
behaves the same, except that a backtrace from inside it, such as a division
by zero, names the caller.
Call labels¶
Calls use labeled arguments by default; the parameter name is the label:
Labeled arguments go in parameter order: with func move(x: int64, y: int64),
move(y: 2, x: 1) is an error
(parameter 0 of `move` expected label `x`, got `y`). A label may jump over
parameters that have defaults, which are then left out of the call.
anon removes the label requirement for that parameter:
Convention: when calling, label every parameter except 1–2 of a single shared
type (e.g. slice(arr, from: 0, to: 3) is fine; passing a label for arr
is just noise).
If a passed argument is a bare identifier with the same name as the
parameter, the label can be shortened to a leading ::
Long calls and parameter lists¶
A call may be split across lines wherever the arguments are separated, and so may a parameter list. Put each argument on its own line, with or without a trailing comma, and comments between them:
let conn = connect(
"example.com",
port: 8443, // not the default
timeout_ms: 200,
tls: true,
)
func request(
anon method: str,
anon url: str,
timeout_ms: int64 = 5000,
) -> none { ... }
This holds for every call: functions, methods, x?.method(...), struct and enum
constructors (Point(x: 1, y: 2)), and the argument lists of enum variants in a type
declaration. A line break after the callee and before the ( still ends the statement,
so f and (1) on two lines are two expressions, not a call. A call that never closes
is reported at the first token that cannot continue it, for instance
expected `)`, got `let` on the line of the next statement.
Label / binding split¶
A parameter can have two names — an external label used at call sites and an internal binding used inside the function body:
Useful for prepositions that make call sites read naturally without forcing short variable names inside the function.
Each parameter binds a name of its own, self included, so two parameters
can't share one: func f(anon a: int64, b a: str) is an error
(parameter `a` is declared twice; give one of them another name). The
same holds for methods, interface methods, externs and function literals.
Default values¶
Trailing parameters may declare a default with = expr, and a call can
leave them out:
func retry(anon n: int64, delay_ms: int64 = 100) -> int64 {
return n * delay_ms
}
retry(3) // 300
retry(3, delay_ms: 500) // 1500
The default is evaluated fresh at each call that omits it. It is
evaluated in the module that declares the function and can't see the
caller's local variables, so a name in it means the same thing at every
call site. Methods and interface methods take
defaults the same way. A default must have its parameter's type, like an
argument. A function's or method's default has its type checked where it
is declared, so func f(x: int64 = "a") is an error even if no call leaves
x out. Anything else wrong in it, such as an unknown name or variant, or
a wrong field in a constructor, is reported where a call leaves it out, and
an interface method's default is checked only at each call that leaves it
out.
A label can jump over parameters that have defaults, so that a later one can be set without writing out the ones in between:
func connect(anon host: str, port: int64 = 80, timeout_ms: int64 = 5000, tls: bool = false) -> none { ... }
connect("example.com") // all defaults
connect("example.com", timeout_ms: 200) // port and tls by default
connect("example.com", port: 8443, tls: true) // timeout_ms by default
The labels still go in parameter order, and a parameter that is jumped over must
have a default; connect(port: 1) is an error because host has none
(parameter 0 of `connect` is anon; remove label `port`). An anon
parameter with a default can be jumped over the same way, by labeling a later
argument. Unlabeled arguments fill the parameters strictly in order, so only a
label can skip.
Each default is evaluated afresh at the call, in the order of the parameters,
along with the arguments you did give: in f(a: x(), c: z()) for func f(a: int64, b: int64 = y(), c: int64 = 0),
the calls run x, then the default y, then z. It works the same for
methods, interface methods and functions of other modules.
Argument types¶
Each argument must have its parameter's type: print(5) is an error
(expected `str`, got `int64`), and so is passing a Gen[int64] where
a Gen[str] is declared, or an int64? where an int64 is. The only
implicit conversions are the ones an annotated let makes (see
Bindings and mutability):
- a
Tbecomes aT?; - a struct,
int64,strorboolbecomes an interface value; .VariantandEnum.Variant(...)are built for the parameter's enum;- an array literal or
+chain is built for an array of enums, interfaces, optionals or arrays.
An array value is never converted element by element. With
func take(anon xs: [Shape]), take([Sq(s: 1)]) is fine, but passing a
[Sq] variable is an error. The same rules apply to extern functions, to
calls through a function value, and to the arguments of a method, an
interface method and x?.method(...).
mut parameters¶
A parameter declared mut is the caller's variable: the function can assign
it, change its elements or append to it, and the caller's variable has the
new value when the call returns. The argument says so with mut, which
takes a mut local or another mut parameter of the calling function:
func count(anon s: str, mut seen: [str]) -> int64 {
seen += [s]
return len(seen)
}
mut names: [str] = []
count("a", seen: mut names) // names is ["a"]
Writing the mut at the call site is required, and only there: passing
names without it to a mut parameter is an error
(`seen` is a `mut` parameter of `count`: pass `mut names`), and so is
mut before an argument whose parameter isn't mut. The argument must be a
name the caller could assign, a mut local or a mut parameter, and one
name can't go to two mut parameters of one call. A field, an element, a
let, or a mut a function literal captures is an error; copy it into a
mut local and assign it back after the call.
Inside the function, a mut parameter is used like a local. The caller's
variable gets the parameter's value when the function returns, however it
returns, including through try. A function with a mut parameter is
called by name: it can't be used as a function value, and an interface
method can't have one. A method that changes its struct declares mut self
(see Methods).
Return values¶
A returned value must have the function's return type, with the same
conversions as an argument: func f() -> str { return 5 } is an error
(expected `str`, got `int64`), and so is returning a [Sq] variable
from a -> [Shape] function. A -> none function returns no value; it
can end with a bare return, return none, or return of a call that
itself returns none. Any function can return a call that never returns
(see below), such as return self.fail("bad") or return log.die("bad").
In a -> T or Error function, a returned T becomes a successful result.
A returned T or Error value must have the same T, so returning an
int64 or Error from a -> str or Error function is an error.
A function with a return type other than none must end every path with a
return, a throw, or a call that doesn't return, like panic(...).
One that can reach the end of its body is an error at its name, or at the
func of a function literal
(`pick` can reach its end without returning a value), and that
includes a -> T? function: write return none at the end. Only a
-> none or Error function may run off its end, which returns Ok(none).
The error isn't reported for a body that already has other errors, or in
a file that doesn't parse, since those may hide the missing return.
Whether a path can reach the end is decided from the statements alone:
return,throw,breakandcontinueend a path, and so does a call of a function or method that never returns;- an
ifends every path only if it has anelseand both branches do; - a
matchdoes if each of its arms does; - a
for trueloop does unless it canbreakout of itself; any otherforloop, includingfor … in, may finish.
Code after a statement that ends every path is never run and isn't
considered, so a break placed after a return or panic(...) doesn't
let a for true loop finish.
The builtin panic(...) never returns, and neither does a function or
method that returns none, has no return, and can't reach the end of its
body by these rules. A function of the module or one it imports named
panic, or a local function value of that name in force at the
call, hides the builtin (see Built-ins). A local named
panic that holds anything else doesn't, so panic(msg) after
let panic = 5 never returns. So a helper that ends in
panic(...) never returns, and nor does one that ends in a call of
another such helper (self.fail(msg), log.die(msg), or a function
declared further down), or in a for true loop it can't break out of.
A call that leads back to the function itself doesn't count:
func spin() -> none { spin() } is taken to return.
This holds for a call of:
- a function of the module or one it imports (
die(msg)), or a function of an imported module (log.die(msg)); - a method of a struct, whatever it's called on:
self, a parameter, any local, a field or a call's result (self.fail(msg),self.log.fail(msg),r.fail(msg),self.reps[i].fail(msg),reporter().fail(msg)), as long as that expression's type is known at the call. A local has the type of its binding in force there, whether alet, let-else, match arm,if … isorforbinds it, sor.fail(msg)never returns afterlet r = Reporter(), even whereris also a parameter of another type.
Two kinds of call are always taken to return, because what they call is chosen at run time:
- a call through a function value (a local, parameter or field of a function type);
- a method called through an interface value.
End such a path with a panic(...) or a return after the call.
A call in a value's place, as a returned value, a match arm's value or an
x? or ... default, is decided where it is written by the same rules, so
return r.fail(msg) never returns after let r = Reporter(), and nor
does return die(msg) when die ends in that call. When what it calls
ends in a call taken to return, the error names that call and its line:
return die(msg) is an error when die ends in r.fail(msg) after
let r: Failer = Reporter(), for an interface Failer
(as `die` ends in `r.fail(msg)` (line 19), or
(line 19 of lib/log.kod) when the call is in another module), and
it says to put a panic(...) after it. The can reach its end error
names that call too when the body ends in a call of such a function, and
says so when the body itself ends in a call through a function value or
a method called through an interface value. Such a call is taken to
return wherever it is written: call it as a statement and end the path
with panic(...).
main¶
Every executable must define main. It can take no arguments or receive the command-line argument list:
// no args
func main() -> int64 {
return 0
}
// with argv
func main(argv: [str]) -> int64 {
print_int(len(argv))
return 0
}
main can also return int64 or Error, directly or through an alias. A
returned value is the exit status, and an error that reaches the end of
main prints panic: <message> and exits with status 1.
Methods¶
Functions inside a struct type declaration are methods. The first parameter must be self:
type Counter = struct {
value: int64
func increment(mut self) -> none {
self.value = self.value + 1
}
func get(self) -> int64 {
return self.value
}
}
Call with dot notation:
Function values¶
Functions are values. Use func(T1, T2) -> R as a type to store,
pass, or return them. A function value is an 8-byte reference, not a C function
pointer (see Function values).
func double(x: int64) -> int64 { return x * 2 }
func triple(x: int64) -> int64 { return x * 3 }
func apply(anon f: func(int64) -> int64, anon x: int64) -> int64 {
return f(x)
}
let g: func(int64) -> int64 = double
print_int(g(21)) // 42 — indirect call through g
print_int(apply(triple, 14)) // 42 — function passed as callback
A function literal, func(anon n: int64) -> int64 { return n + 1 }, is
a value of its function type too.
A bare identifier in value position resolves to the function's address
when no local of that name is in force there. A call f(args) goes to a
struct named f first, so Pt(x: 1) constructs. Otherwise it does an indirect blr when the
innermost binding of f in force holds a function value, and a direct
bl of the module's, an imported or the builtin function named f when
no binding of f is in force or it holds anything else. A function value
declared in a block, such as an if or loop body, is called that way
only from its let to the end of the block, and after the block f(args)
calls an outer function value of that name again. Elsewhere f(args)
calls the module's or an imported function, or the builtin, named f,
and f as a value is that function; with none of those it is an error:
`f` is declared in a block that has ended after the block, and
`f` is called before its `let` (or read) before the
declaration (see Blocks and bindings
and Built-ins).
A function of an imported module is a value written through its module,
let f = vec.dot. A name the module doesn't declare is an error with a
did-you-mean hint (module `vec` has no function or constant `dott`).
An indirect call has the function type's return type wherever the
function value comes from: a local, an array element (fs[i](x)), a
struct field (h.fn(x)) or another call (get_fn()(x)). It must pass
exactly as many arguments as the function type has parameters, since a
function type carries no defaults.
Closures¶
A function literal can read the locals and parameters in force where it's
written, including self. It keeps their values, so it can outlive the function
that made it:
func adder(anon n: int64) -> func(int64) -> int64 {
return func(anon x: int64) -> int64 {
return x + n
}
}
let add5 = adder(5)
print_int(add5(1)) // 6
A literal captures the value a name has when the literal is evaluated. Each pass
of a loop makes its own closure, with that pass's for variable and pattern
bindings. Literals nest, and an inner one can capture what the outer one can see.
A variable declared mut is shared instead: the literal and the function it's
in use the same variable, so what one assigns the other sees, even after the
function has returned:
func make_counter() -> func() -> int64 {
mut n = 0
return func() -> int64 {
n += 1
return n
}
}
let next = make_counter()
next()
print_int(next()) // 2
A mut declared in a loop's body is a new variable on each pass, so each pass's
closure has one of its own. Any other name the literal captures keeps the value
it had when the literal was evaluated, and can't be assigned in it:
a function literal can't assign to `x`, which it captures. That holds for a
let, a parameter, a for variable and a pattern binding. A mut parameter
can't be captured: a function literal can't capture `p`, a `mut` parameter;
copy it into a `mut` local to share it.
A captured mut lives in a counted cell from its declaration on, and each read
and assignment of it goes through the cell, in the function too; a mut that no
literal captures stays in the frame.
Other limits:
- A literal can't see its own
let, so it can't call itself through it. Use a named function to recurse:unknown function `fact`; a function literal can't see its own `let`, so use a named function to recurse. - A literal inside a generic function, or a method of a generic type, can't
capture:
a function literal in a generic function or type can't capture `x`. Passing a closure to a generic function works, as insort.sorted_by(xs, less: ...). - A default value sees no locals, so a literal used as one captures nothing.
- A closure kept in a struct that it captures is a cycle, and a cycle is never freed (see Reclaiming memory).
Generic functions¶
Type parameters in brackets after the name make a function generic. They can be used in its parameters, its return type and its body:
func first[T](anon xs: [T]) -> T? {
if len(xs) == 0 {
return none
}
return xs[0]
}
func map_all[T, U](anon xs: [T], f: func(T) -> U) -> [U] {
mut out: [U] = []
for x in xs {
out += [f(x)]
}
return out
}
let a = first([1, 2]) // a: int64?
let b = map_all([1, 2], f: func(anon n: int64) -> str { // b: [str]
return f"#{n}"
})
Like a generic struct, a generic function is monomorphised: it's compiled once for each list of type arguments a module calls it with.
Inference¶
A call usually leaves the type arguments out, and the compiler works them out from the arguments:
- Arguments are read in parameter order. Each one is matched against its
parameter's declared type:
Ttakes the argument's whole type,[T]an array's element type,Box[T]an instance's type argument, andfunc(T) -> Ua function's parameter and return types.T?takes the inner type of an optional or else the argument's own type, soint64?andint64both makeTanint64. - The first argument to settle a type parameter decides it. Later arguments
are then converted to the parameter's type as in any call, and one that
can't be is an error at that argument. With
func pick[T](a: T, b: T),pick(a: 1, b: "x")reportsexpected `int64`, got `str`, and arguments of two structs that share an interface need the type written out, as inpick[Shape](a: sq, b: circle). - An argument with no type of its own (
none,[],.Red) settles nothing, but takes its type from the parameter once the others have settled it: withfunc add[T](xs: [T], x: T),add(xs: [], x: 1)makesTanint64. - A parameter left to its default settles nothing either.
- Only arguments count. Neither the return type nor where the result goes
matters, so a type parameter that no argument settles is an error, even in
let xs: [int64] = empty():cannot infer `T` in the call to `empty`; write the type arguments: `empty[T](...)`.
Explicit type arguments¶
Type arguments can be written after the function's name, all of them or none:
They are spelled as for a generic struct's constructor (str, [str],
int64?, Box[int64]). The wrong number is an error, and so is giving them to
a function that isn't generic.
Checking¶
There are no bounds on a type parameter: the body may do anything the type arguments allow, and is compiled for each instance. A signature is always checked. A body is checked only for the instances that are called, so the body of a generic function nothing calls isn't checked. An error in a body is reported once, for the first instance that hits it, and names that instance:
func largest[T](a: T, b: T) -> T {
if a < b { // with Color: `<` doesn't take `Color` operands; … (in `largest[Color]`)
return b
}
return a
}
A generic function may call itself and other generic functions. The chain of
instances has to end: one that keeps making a bigger type, like f[[T]] inside
f[T], is an error once it is 64 instances deep, also when the chain runs
through a generic struct's methods. A chain that
branches into new types is stopped earlier, when a module passes 4096 instances.
Parameter defaults and the body resolve names in the module that wrote them,
as for a generic struct's methods, and T means the instance's
type in both.
Limits¶
- A generic function is a value once it has its type arguments, as in
let f = first[int64]orsorted_by(xs, less: before[T]). Without them,let f = firstis an error, and they aren't inferred from where the value goes. A value's type arguments must fit on one:pair[A, B]is only read as a call, so wrap a call of it in a function literal. - Only top-level functions can be generic. A method can use its struct's type
parameters but can't declare its own, and neither can an interface method, a
function literal, an extern or
main. A module-level constant can't either. - A function literal in a generic body can't name
T, as in a generic struct's methods, because it's compiled once and not per instance. - A type parameter's name can't repeat in one list, and hides a type of the same name for the length of the function.
Extern functions¶
Declare external C functions with extern:
extern func labs(anon n: int64) -> int64 // compiled programs only
extern func putchar(anon c: int64) -> int64
A C function that takes a variable number of arguments, such as fcntl,
open or printf, ends its parameters with ...:
extern func fcntl(anon fd: int64, anon cmd: int64, ...) -> int64
extern func snprintf(anon buf: int64, anon size: int64, anon format: int64, ...) -> int64
fcntl(fd, F_SETFL, flags | O_NONBLOCK)
- Only an
externcan take..., and it comes last. - The parameters before it must be
int64orbool; pass a pointer as anint64fromunsafe. - A call gives at least those, then any number more. Each extra argument is
an
int64or abool, without a label. On arm64 macOS each goes in an 8-byte slot on the stack, where C'sva_arglooks for it. - A float can't be an extra argument, and neither can a
str; passunsafe.c_str(s)for C's%s.
A C global variable of 8 bytes, such as a pointer or a long, is an
extern let:
Each read loads the variable's value as it is then; Kod can't assign it.
The type must be int64. A name that starts with _, as most of libc's
globals do, is private to the module that declares it.
An extern func is a C symbol, resolved at link time against the C runtime and whatever the modules of the program declare (see Link inputs): labs is in libc, and a module can name a C file of its own or a library to link. A str argument reaches C as a KodStr *, not as a char *; to call a libc function that takes a C string, a buffer or a pointer to write to, pass addresses from unsafe as int64.
Recursion¶
Mutual recursion between functions is supported as long as all functions are declared in the same module.
A function that calls itself as the last thing it does, in a return f(...) or,
for a function that returns nothing, as its last statement, jumps back to its
start instead of making a call, so that recursion takes no stack however deep it
goes:
The arguments are all worked out before any parameter changes, as for a call. Some calls stay ordinary calls, each with a frame of its own:
- a call to another function, or one whose result the function still uses
(
fib(n - 1) + fib(n - 2),1 + f(n - 1)); - a call from inside a loop, or from a function with
mutparameters, captures or more than eight parameters; - a function returning a
T?, aT or Error, an interface or a union; - a call that passes a newly made string, array, map or struct
(
walk(xs[1..])), since the function's own values are let go of before the jump. Passing one of its parameters on as it is (count(xs, i: i + 1)) is fine, and numbers andbools can be anything.