Landin library reference discuss source

Library reference

Landin's library is ordinary Landin source that ships with the compiler. Its modules are in three namespaces, and the namespace says where a module is available:

Namespace Available on
core Every enabled target, firmware included.
hosted A hosted system only.
platform The narrower target scope each module declares.

Some platform modules serve the hosted POSIX systems, which are Linux, macOS and FreeBSD. None of these modules is available on firmware:

  • platform/posix serves all three systems.
  • platform/linux and platform/libc are each system's own interface beneath it.
  • platform/kqueue is the event interface of macOS and FreeBSD.

Being available does not promise that every composition fits a particular firmware image. Every memory lifetime and every handle lifetime remains an explicit obligation of the caller.

Two kinds of reference appear on this page. A number in brackets, such as [1300], is a numbered paragraph of the tour or spec.md. A name such as D503 is a decision recorded in spec.md. refine explain prints either one, as in refine explain D503.

Common tasks

Find the task in this table. Each row gives the calls to write and the module whose page describes them. The program after the table does several of the tasks together.

Task Calls Module
Get the handle every hosted call takes host := blocking.new() hosted/blocking
Print a formatted line io.write_format(host, io.out(host), "{} lines\n", [any(addr count)]) core/io
Print many lines io.buffered_over(host, io.out(host), storage) once, then io.format(out, "{} lines\n", [any(addr count)]) for each line, and io.flush(out), checked, before reporting success core/io
Get a command-line argument io.argument(host, 0), and io.arguments_length(host) core/io
Read a file line by line io.open_read(host, path), io.lines_over(host, file, buffer), then io.read_line(lines) until item.at_end, and io.close(host, file) core/io
Read a whole file into memory io.open_read(host, path), then io.read(host, file, chunk) until it gives 0, adding each piece to a builder with text.append(whole, chunk[0..<got]), and io.close(host, file). The two kinds of builder are compared after this table core/io, core/text
Write straight to standard error io.write(host, io.err(host), bytes) core/io
Turn a failure into words for a person failure.words(problem) core/failure
Turn an errno from platform/posix into words posix.words(problem) for an errno alone; system.words(problem) for a system.reason, an errno or one of the library's failures platform/posix, hosted/system
Right-align a number in a column text.over(buffer) makes a builder, text.append_u64(line, value) writes the number, text.align_right(line, start, width, u8(' ')) pads it from start, and io.put(out, text.used(line)) prints it core/text
Print a float with two decimals Scale it to whole hundredths and print the integer parts, as core/text's program shows; floats are not formattable core/text

A program that reads a whole file into memory chooses between two builders:

  • A builder that text.over(storage) makes fails with mem.out_of_memory once the file outgrows storage.
  • A builder that text.growing(any(addr heap)) makes grows from the allocator until text.release gives its storage back. It fails with mem.out_of_memory too, when the allocator refuses.

This program reads a file both ways. Its runs over a file larger than 64 bytes, a smaller one and a missing one are the compiler's own tests. The read_all function of reverse-complement is the same loop over standard input.

The next program does the common tasks of a small tool in one place. It numbers the lines of the file named on the command line, as cat -n does. When it cannot read the file, it says why on standard error:

--  Number the lines of the file named on the command line, as `cat -n`
--  does, and say in words why when it cannot be read.
import core/failure
import core/io
import core/text
import hosted/blocking

--- Write each line of the file at `path` to `out` after its number.
numbered: (inout out: io.buffered_writer(blocking.host), host: blocking.host,
           path: text.os_string) -> none ! ... =
    file := try io.open_read(host, path)
    defer io.close(host, file) else none
    mut buffer: [4096]u8 = zeroed
    mut lines := io.lines_over(host, file, buffer)
    mut number: u64 = 0
    loop do
        item := try io.read_line(lines)
        break when item.at_end
        inc number
        try io.format(out, "{}: {}\n", [any(addr number), any(addr item.bytes)])
    end loop
end numbered

public main: () -> (code: i32) =
    host := blocking.new()
    mut storage: [256]u8 = zeroed
    mut out := io.buffered_over(host, io.out(host), storage)
    defer io.flush(out) else none
    code = 1
    path := io.argument(host, 0) else begin
        io.write(host, io.err(host), "usage: number FILE\n") else none
        return
    end
    numbered(out, host, path) else (problem)
        io.write(host, io.err(host), text.os_string_bytes(path)) else none
        io.write(host, io.err(host), ": ") else none
        io.write(host, io.err(host), failure.words(problem)) else none
        io.write(host, io.err(host), "\n") else none
        return
    end
    io.flush(out) else (problem)
        io.write(host, io.err(host), "standard output: ") else none
        io.write(host, io.err(host), failure.words(problem)) else none
        io.write(host, io.err(host), "\n") else none
        return
    end
    code = 0
end main

Three points about it:

  • numbered can fail, so its signature ends in !. Writing ! ... asks the compiler to work out the set from the trys in the body. A function that is not public may do that [0960].
  • main cannot fail, so it handles each failure with else [1030]. else (problem) names the atom, and failure.words(problem) turns the atom into words for a person, such as not found.
  • The output goes through a buffered writer over a buffer that main declares. The last of the output therefore reaches standard output only when the writer is flushed. main flushes the writer before it reports success, so a write that fails at that point is reported rather than lost. On the earlier ways out, the deferred io.flush still writes what is waiting. The deferred io.close closes the file however numbered ends.

Compile the program and run it over a four-line file:

refine compile main.ldn -o number && ./number input.txt
1: first line
2: second line
3: 
4: last, without a newline

When the file it is given is not there, the program says why on standard error and exits with 1:

./number missing.conf
missing.conf: not found

Both runs are the compiler's own tests: the program and its failing run.

Reading a signature

On the site, the library reference gives each module a page that shows the full signature of every call. The signature of io.argument, for example, is (provider: type is process, host: provider, index: usize) -> (value: text.os_string from host) ! no_argument. A call writes far less: io.argument(host, 0).

This table says what each part of a signature means:

In a signature What it means
provider: type is process, first A type parameter. The compiler deduces it from the arguments, so a call usually leaves it out [1300]. A call may name it instead, and then it names every type parameter. vec.new(item: i32) must name its type parameter, because no argument has that type.
provider: type A type parameter with no requirement: any type will do.
is process The type must conform to the concept process. A concept is a named set of operations [1230] [1240].
host: provider The provider, which is the handle a call works through. Here it is the handle that blocking.new() made. An allocator is passed the same way, usually as memory: provider beside its own provider: type is mem.allocator.
evidence The table that tells generic code how a type does a concept's operations [1240] [1310]. A conformance such as u32 is formattable (...) supplies it.
world The concept core/io has for an ordinary program's provider: a reader, writer, files and process in one. The host that blocking.new() made is one. In core/io, memory is the memory world, a provider over the caller's storage.
buffered_writer(provider) A generic type applied to a type: a buffered writer over whichever provider the call deduces [1250].
public builder: type = builder_value A public name for a type whose fields are the module's own. You hold a value of the type and pass it to the module's calls. Reading a field is refused.
[]mut u8 A slice the call may write through [0570]. The call only reads a plain []u8.
[]any text.formattable A slice of values of any type that conforms to formattable [1370]. A call writes it as an array literal, [any(addr count), any(addr name)].
-> none The call returns nothing.
-> (lines: line_reader(provider) from buffer, host) A named result. from buffer, host says that the result borrows from both and must not outlive either [0790].
-> (name: []u8, value: []u8) Several named results. The caller reads them as fields of the call's result or takes them apart by name [0990].
! no_argument What the call can fail with [0940]. The caller passes the failure on with try or handles it with else.
! ... A function that is not public may let the compiler work its set out from its body [0960]. The library's public calls always write theirs.
inout The call may change the argument in place [0900].
sink The call consumes the argument [0910].

About this reference

This page is the overview. For each module it has an introduction, the main calls and an executable example. Other places hold the rest:

To find Read
Exact signatures, source links, module browsing and local search The site's module pages
The shared conventions and evidence The library guide
The language itself The tour

The module pages are generated from this page and from the public declarations in core, hosted and platform with their --- doc comments. An editor shows the same comments on hover.

Each module below opens with what it is for, then gives its main calls, then says how it behaves. The module's page lists the items and ends with a complete program that uses the module. The compiler's own tests run that program. Where the program prints, the page also gives the command and its output.

What the library does not cover yet

This section first says what is covered. Then it lists what is missing, with the route to take until then.

The library covers:

  • memory, containers and text;
  • files, directories, standard input and output, process arguments and the environment;
  • running programs, clocks, sleeping, the system's entropy and a deterministic generator;
  • blocking TCP and UDP sockets over IPv4 and IPv6;
  • threads started as a group the function joins, hosted/thread;
  • the rest of the file system: opening with options, renaming, a file's status, read-only files, synchronizing, truncation, reading and writing at an offset, temporary files, the working directory's path and terminals.

platform/posix gives POSIX's own facilities in Landin types, in the same way on Linux, Darwin and FreeBSD:

  • files, directories and memory mappings;
  • poll, pipes, children and waiting;
  • clocks and random bytes;
  • sockets, Unix-domain ones among them;
  • links, permission bits, owners, file times and locks;
  • terminals and their raw mode, and pseudo-terminals;
  • the user and group databases.

platform/posix also loads shared objects with the system's own loader, wherever a C runtime started the program. That is the case on Darwin and FreeBSD, and on Linux under --link=libc.

A program that needs something neither of the two covers yet reaches the operating system itself. The route differs between Linux and the C library's systems:

Need Planned Route until then
Calendars, time zones and formatting a date the locale record in the register time.wall_now gives the wall clock's seconds since 1970. Turning them into a date is the program's work.
Resolving a host name to an address the resolver record in the register Under the C library, which means on Darwin, on FreeBSD and on Linux under --link=libc, declare getaddrinfo as extern(c). A static Linux program has none. net.parse_address reads an address that is already written as one.
Changing the working directory Not offered. The working directory is the whole process's, and beside threads a change would move every relative path at once. Use a path built from io.current_directory, or a call relative to a directory open as at in platform/posix; chdir by its number through linux.system_call on Linux, or declared extern(c) on Darwin and FreeBSD, where a program must.
Extended attributes, access control lists, file flags not yet planned On Linux, pass the call's number from platform/linux/numbers to linux.system_call. On Darwin and FreeBSD, declare the C function as extern(c).
Accounts kept outside /etc/passwd and /etc/group on Linux, those of a directory service or of the Name Service Switch (NSS) --link=libc A static Linux program reads the two files itself. In a program linked with --link=libc, platform/posix asks the C library, which asks NSS.

Every Linux system call is reachable through linux.system_call:

  • platform/linux/numbers names each call's number. The module is generated from a pinned kernel release.
  • linux.system_call makes the call with six integer arguments. It returns the kernel's result, which on a failure is the errno negated.

Nothing checks those arguments. A pointer goes as i64(usize(p)), and getting a flag or a record right for each architecture is the program's work. Prefer a typed wrapper where platform/linux has one, and prefer platform/posix where it gives the call.

Modules

core

  • core/arena A monotonic allocator over caller-supplied bytes.
  • core/atomic A cell holding one u8, u16, u32 or u64, read and written only atomically, its operations' orderings in their names.
  • core/cache Cache maintenance for memory a device reads or writes behind the CPU's caches: handing a DMA buffer between CPU and device as one concept, maintenance, over ranges of whole lines (D227).
  • core/cmp Equality, hashing and ordering evidence, apart from the containers and algorithms that consume it.
  • core/diag Bounded diagnostic storage and streaming diagnostics through a writer capability.
  • core/failure Words for a person for every failure atom a core module raises: a short English phrase each.
  • core/fault Deterministic allocation-failure injection over any allocator, with cumulative counters.
  • core/fibre Fibres: tasks a function starts as a group and waits for before it goes on.
  • core/fibre/stacks The switch between stacks, and a round of fixed turns built on it.
  • core/io Concepts for reading, writing, files and the process, and world, which composes them; beside them directories, running programs, entropy, terminals and the rest of the file system; the memory world, a formatted write, a buffered writer and a line reader. Time is core/time, the network core/net, and fakes of a system's providers core/io/fake.
  • core/io/fake Fakes of a system's providers for tests that must give the same answer every run and on every target: a file system, a network, a clock, entropy, terminals and signals, each over the caller's records.
  • core/io/signal Signals as events: the concept a provider that takes turns supplies when it delivers the system's signals to a fibre that waits for them.
  • core/iter The concept a for loop walks a value through.
  • core/line Serial line settings: a UART's rate and frame, the divisor its baud-rate generator is set to, and the refusals every driver shares.
  • core/map An insertion-ordered hash map with explicit entry walks.
  • core/mem Memory providers and typed storage: the foundation for allocation, initialized prefixes and caller-owned backing.
  • core/net The network concept, whose connections are readers and writers, and internet addresses with their text.
  • core/panic The compiler's five panic atoms and their shared panic-kind domain.
  • core/pool A reclaiming allocator over fixed-size slots and caller-supplied bookkeeping.
  • core/random A deterministic generator of pseudorandom numbers, the same sequence for a seed on every target.
  • core/region An allocator scope that records allocations through a parent and releases them together.
  • core/sort Allocation-free in-place heapsort and selection sort using ordering evidence, and heapsort by a comparison given a context.
  • core/spill A list that keeps an inline prefix and spills into allocated storage when it fills.
  • core/text Byte cursors, validated UTF-8 views, positions and searches inside them, a scalar encoder, two text builders, formatting and parsing numbers.
  • core/time Spans and instants of time counted in nanoseconds, the wall clock's time, and the monotonic and wall clock concepts.
  • core/tree An append-only store of named leaves and branches addressed by node identifiers.
  • core/vec A growable contiguous list with explicit allocation and rollback on failed growth.
  • core/zone A bump allocator that grows by taking blocks from a parent allocator.

hosted

  • hosted/blocking The hosted provider whose waiting operations block the thread: what an ordinary hosted program imports.
  • hosted/events The hosted provider whose waiting operations switch fibres: what a program that serves several things at once, or waits for a signal, mints instead of blocking.new().
  • hosted/heap An explicit allocator over the host runtime heap.
  • hosted/system What a hosted program needs that does not wait, the same under either waiting provider.
  • hosted/thread/lock A lock that threads share state behind, and the record that a thread has started.
  • hosted/thread Threads: tasks a function starts as a group and waits for before it goes on, each on a thread of its own, written over platform/posix and, on Windows, over platform/windows.

platform

  • platform/c C scalar spellings for the target's C ABI, on every target whose C ABI is enabled: the four LP64 ones and Cortex-M's ILP32 AAPCS32.
  • platform/cortex_m M-profile interrupt masking, waiting and memory barriers.
  • platform/cortex_m/l1 The Cortex-M7's level 1 caches as core/cache's provider, on a cached profile.
  • platform/kqueue kqueue, the event interface Darwin and FreeBSD share, through their C libraries, raw: a failure is -1 with the reason in libc.errno_cell.
  • platform/libc The C library's declarations, as ordinary extern(c) imports, raw.
  • platform/linux Linux's system calls with no C library beneath them, and the process entry of a static Linux executable, raw.
  • platform/linux/numbers Every Linux system call's number on x86-64, arm64 and RV64, generated from a pinned kernel release.
  • platform/linux/vdso The vDSO, the small shared object Linux maps into every process, and the functions found in it, raw.
  • platform/posix POSIX's facilities in Landin types, on Linux, Darwin and FreeBSD alike.
  • platform/riscv/hazard3 Hazard3's external interrupt controller, the RP2350's RISC-V cores'.
  • platform/riscv RV32 machine-mode interrupt masking, the core's own interrupt lines, waiting and memory barriers, declared on rv32 alone.
  • platform/windows Windows' own interface under the Windows x64 C convention, raw: a call that fails returns the system's failure value and leaves the reason for last_error. It is what the hosted providers are written over on Windows, as they are over platform/posix elsewhere.
  • platform/windows/sockets Windows Sockets, ws2_32's calls, and iphlpapi's interface names, raw, under the Windows x64 C convention: making, binding, connecting and closing sockets, sending and receiving, their options, select, and the overlapped calls WSARecv, WSASend, WSARecvFrom and WSASendTo, with ConnectEx and AcceptEx reached through WSAIoctl. A call that fails returns socket_error or invalid_socket and leaves the reason for socket_last_error; started makes the one WSAStartup call a process needs before its first socket.
  • platform/xtensa Windowed Xtensa interrupt masking, enabled and pending CPU lines, the cycle counter, waiting and memory barriers, declared on xtensa alone.