Pointers

TryC has two kinds of pointer. ref is an opaque, arena-tracked pointer to any allocation: the way an object travels through a container or a generic field, checked when it comes back. ptr T is a raw address for the parts of a program that talk to hardware, syscalls and C libraries: typed, cheap to cast, unchecked, and confined to unsafe: blocks.

ref: an opaque pointer

A ref is an 8-byte address of which the static type knows nothing more. Any pointer (a str, an array, an object, a function) becomes a ref with as ref, or implicitly wherever a ref is expected: an argument, a field, an array element, a return from a function declared -> ref, a value in a dict literal. It comes back with a cast to its real type.

#include <libstd/stdio>
#include <libstd/list>

class Token:
    text str
    kind int

def make_token(t: str, k: int) -> Token:
    tok = new Token()
    tok.text = t
    tok.kind = k
    return tok

toks = list_new()
list_push(toks, make_token("if", 1))        // Token -> ref, implicitly
list_push(toks, "just a string")            // str -> ref

t = list_get(toks, 0 as long) as Token      // checked: the object really is a Token
s = list_get(toks, 1 as long) as str
print(t.text, " ", s, "\n")
if just a string

What a ref can do is deliberately small:

A ref made from a str, an array or an object is the same pointer with a new label: a field, an element, a global or a container that holds it keeps a counted reference, as for the original type, and the value is freed when the last one goes (see The arena). Only a ref made from something the compiler cannot follow, an integer inside unsafe: or a ptr T, pins the allocation for the rest of the program. Either way, whatever a ref points to stays alive while the ref is reachable.

ref replaces the older idiom of carrying a pointer in a long (list_push(l, obj as long), obj.raw = p as long, long as ClassName), which is no longer accepted outside unsafe:: an integer can hold any bit pattern, so the compiler could neither promote it nor check it.

Null

There is no null keyword. Any pointer-typed value (str, ref, an object, an array, ptr T) compares with the literal 0: p == 0 and p != 0 test the address against null, even for a str, whose == against another string compares content. A null value is written 0 as ptr Node, 0 as Node, 0 as ref or 0 as str: the literal 0 is the one integer that may become a pointer anywhere. Dereferencing null crashes with the SIGSEGV report. Used bare as a condition, a pointer is true when it is not null (if node.next:), except a str, which is true when it is not empty (see Control flow).

node.next = 0 as ptr Node
if node.next != 0:
    walk(node.next)

Address of a variable

#include <libstd/stdio>

x = 5
p = &x                 // type int*, an 8-byte address
unsafe:
    y = p as long      // the same bits as an integer
    z = p as ptr int   // the same address, indexable as int
print(z[0], "\n")      // 5, read through the pointer
z[0] = 6               // x is now 6

&name takes the address of a variable (a global or a local; the address of a local is valid only while its function runs). The type of &x is int*; the type you name explicitly after as is written ptr int. The two are the same thing. Turning the address into a number, or into a ptr T, needs unsafe:; indexing the resulting ptr int does not.

ptr T

ptr T is a pointer to elements of type T (int, long, char, a class...). It is indexed like an array, without bounds checks: there is no length anywhere. A ptr T comes from an extern def, from &variable, or from a cast inside unsafe:.

unsafe:
    buf = rt_alloc(80 as long) as ptr long  // 80 bytes from the arena, zeroed
    p = buf as ptr int                      // reinterpret the same bytes as ints
buf[0] = 1 as long
buf[9] = 7 as long
print(p[0], "\n")                           // 1: low half of buf[0]

unsafe:

An unsafe: block is a plain statement list (no scope of its own, nestable) in which two things are allowed that are refused elsewhere:

Inside the block the arena rules still hold: p as long pins the allocation for the rest of the program, because a pointer hidden in an integer can never be freed safely. Outside, the same casts are compile errors: 'str as long' solo dentro 'unsafe:'. libstd keeps its unsafe: blocks around syscall buffers, the peek/poke helpers and the Vulkan bindings; the self-hosted compiler has exactly one, the argv it builds for LLVM. --legacy-casts switches the rule off for a source not yet migrated to ref.

Reading and writing raw memory

Besides indexing a ptr T, libstd offers peek/poke helpers for code that already holds a str address: dict_peek64/dict_poke64, dict_peek32/dict_poke32 in libstd/dict and peek_int/poke_int in libstd/sync. Atomic operations on memory shared between threads are atomic_add32 and atomic_cas32.

Pointer arithmetic on strings

s + n on a str is pointer arithmetic: it yields a str pointing n bytes further into the same buffer (an interior pointer). libstd uses it to walk a text without copying (lstrip returns stringa + start; sys_read(fd, buf + total, ...) appends to a buffer). The arena resolves an interior pointer to its allocation when it promotes it, so a slice can be stored and returned like any string; nothing checks that n is inside the buffer, and the slice has no length header of its own (strlen scans it).

Memory outside the arena

Everything allocated with new, rt_alloc or string operations is tracked by the arena and freed with its scope. Two functions give memory the arena never touches, for the cases where a block must be shared between threads or must not move when a scope ends:

FunctionDoes
raw_alloc(size)an mmap of its own, never tracked, never freed automatically
raw_free(ptr)munmaps it
raw_realloc(ptr, new_size)allocate + copy

They are used by libstd/thread for thread stacks and by libstd/vulkan for structures whose lifetime the driver controls. They are refused under --noheap.

Function pointers

Covered in Functions: op: &(int, int) -> int = somma, callable as op(3, 4); a bare function name coerces to str when passed to C or to thread_spawn, and to ref when stored in a container (adict_set_ref(d, "define", handle_define), read back with adict_get_ref(d, "define") as &(str, int) -> str).

What is unsafe here

Keep pointer code inside small, well-tested functions (the way libstd wraps every syscall) and let the rest of the program use str, arrays, classes, ref and containers.