Classes
A class is a record of typed fields, allocated with new and accessed with dot notation. There is no inheritance. A class can declare methods, resolved at compile time, and callbacks, function pointers stored in each object.
Declaring and using
#include <libstd/stdio>
class Persona:
eta int
attiva bool
iniziale char
nome str
p = new Persona
p.eta = 30
p.nome = "Mario"
p.iniziale = 'M'
print(p.nome, " ", p.eta, "\n")
Mario 30
- A field line is
name type, one per line. Fields start zeroed (0,'\0', empty pointer). new Personaandnew Persona()are equivalent. The variable holds a pointer to the object; assigning it to another variable or passing it to a function shares the same object.- Class names should start with an upper-case letter (the compiler warns otherwise). Declaring the same name twice is an error.
Functions on objects
def make_point(px: int, py: int) -> Point:
p = new Point
p.x = px
p.y = py
return p
def sum_point(p: Point) -> int:
return p.x + p.y
def bump(c: Counter) -> None:
c.n++ // modifies the caller's object
Returning an object created inside a function is safe: the arena promotes it to the caller's scope (see The arena).
Nested classes: embedded by value
A field of class type is stored inline inside the object, not as a separate allocation. Its fields are reached with a chain of dots.
class Point:
x int
y int
class Rect:
top_left Point
bottom_right Point
r = new Rect
r.top_left.x = 0
r.bottom_right.x = 10
r.bottom_right.y = 20
Self-referential classes: pointers
A field whose type is the class being declared (or that would otherwise recurse) is a pointer, which makes linked structures possible. The null pointer is written 0 as ptr Node and tested with node.next != 0.
class Node:
value int
next Node
n3 = new Node
n3.value = 30
n3.next = 0 as ptr Node
n2 = new Node
n2.value = 20
n2.next = n3
n1 = new Node
n1.value = 10
n1.next = n2
cur = n1
total = 0
count = 0
while count < 3:
total = total + cur.value
cur = cur.next
count++
print(total, "\n") // 60
Reading a field through a null pointer crashes with the SIGSEGV report; there is no null check in the language yet (see Memory safety).
Array fields and arrays of objects
#define QUANTI 5
class Serie:
nome str
valori int[QUANTI] // inline, bounds-checked like any array
quanti int
class Poligono:
vertici Point[3] // three Point instances stored by value
lati int
poly = new Poligono
poly.vertici[2].x = 2
poly.vertici[2].y = 4
array = new Serie[10] // an array of ten Serie, by value
print(array[1].quanti, "\n")
The length of an array field must be known at compile time; a #define constant works because the precompiler substitutes it first.
Layout and --no-padding
By default fields are aligned to their natural size, as a C compiler would, so the object can be handed to C code that expects the same struct. --no-padding packs the fields back to back; use it for wire protocols and hardware registers that need exact byte offsets.
class PersonaCompatta --no-padding:
eta int
attiva bool
nome str
A struct shared with a C library is declared field by field with the C types mapped to int/long/short/str, adding explicit _pad fields where C would insert padding; libstd/vulkan and libstd/file (Stat) are examples.
Methods
A line name &function declares a method. obj.name(args) calls function, passing obj as the first argument when the function's first parameter has the class type. The compiler picks the function from the type of obj, which is always known at compile time, so this is a direct call: a method takes no space in the object, costs nothing in new, and can be inlined like any other call.
class Man:
age int
set_age &Man_set_age
get_age &Man_get_age
def Man_set_age(self: Man, new_age: int) -> None:
self.age = new_age
def Man_get_age(self: Man) -> int:
return self.age
instance_man = new Man()
instance_man.set_age(22)
print(instance_man.get_age(), "\n") // 22
- A method belongs to the class, not to the object:
obj.get_age = other_fnandf = obj.get_ageare compile errors. The function stays an ordinary function:Man_get_age(m)calls it, andMan_get_agealone is its address. - A function whose first parameter is not the class is called with the arguments as written (
h.calc(1, 2, 3)). - Methods work on embedded objects and on arrays of objects (
r.top_left.move(1),points[i].move(1)). A method and a field cannot share a name.
libstd/re (compile_pattern), libstd/dict (Sdict), libstd/string (Joiner, Reader) and libstd/argparse (ArgParser) give their objects methods this way.
Callbacks
When each object needs its own function, declare a callback: a field that holds a function pointer, written with the signature only. It starts at zero; assign it any function with that signature. Calling it follows the same rule for the first argument.
class Button:
label str
on_click &(Button, int) -> None
def save(b: Button, times: int) -> None:
print("saving ", b.label, "\n")
def close(b: Button, times: int) -> None:
print("closing ", b.label, "\n")
ok = new Button()
ok.label = "ok"
ok.on_click = save
cancel = new Button()
cancel.label = "cancel"
cancel.on_click = close
ok.on_click(1) // saving ok
cancel.on_click(1) // closing cancel
A callback is an 8-byte field and an indirect call. Calling one that was never assigned crashes with the SIGSEGV report at address 0. The signature can name the class itself or a class declared further down.
Opaque handles from C
extern class Name declares a type whose layout is unknown (a C struct only ever handled through a pointer). Variables of that type are declared with =: and passed by address:
libextern <libsqlite3.so>
extern class sqlite3
extern def sqlite3_open(filename: str, ppDb: &sqlite3) -> int
db =: sqlite3
rc = sqlite3_open("./test.db", &db)
Objects and the arena
An object created with new belongs to the scope that created it. A field of another object, a global or a container that stores it holds a counted reference: the object outlives its scope while one of them holds it and is freed when the last one lets go. A str or an array stored in a field is counted the same way. A field of type ref holds any object, counted like the others (obj.payload = p, read back as obj.payload as Point, checked). Two objects that hold each other are never freed (a cycle). What is not tracked is a pointer hidden in a long inside unsafe:, which pins the allocation for the rest of the program: see The arena.