Built-in Attributes
A built-in attribute is one the compiler handles itself, with no macro @name definition behind it. Each is written @name or @name(args) before the declaration, statement or expression it applies to, and an attribute that is not on this page is an error (see Unknown and misplaced attributes). For defining your own attributes, see Attributes.
Summary
| Attribute | Applies to | Arguments | Effect |
|---|---|---|---|
@packed | class, struct, union | none | Remove padding between members |
@align(N) | class, struct, union, field, variable | N: a power of two | Raise the minimum alignment to N bytes |
@relocatable | class, struct, union | none | Pass and return the record in registers where its layout allows |
@likely | if, or the else after a branch | none | The branch is expected to run |
@unlikely | if, or the else after a branch | none | The branch is expected not to run |
@unpredictable | if | none | The condition follows no learnable pattern |
@assume(cond) | a statement of its own | cond: a bool | The optimizer may take cond as true |
@unreachable | a branch | none | Reserved: rejected with SC116E |
@deprecated | any declaration | none, or one string | A warning at every use |
@no_warn(CODE, ...) | any declaration | one or more warning codes | Drop those warnings inside the declaration |
@unwind | function, method | none | Let a C++ exception pass through |
@no_unwind | function, method | none | Keep the function non-unwinding, even under -funwind |
@hot_path | function, method | none | Optimize for speed |
@cold_path | function, method | none | Optimize for size, keep out of the way |
@pure | function, method | none | The result depends only on inputs and readable memory |
@no_inline | function, method | none | Never inline |
@preserve_most | priv function, method | none | The callee saves nearly every general-purpose register |
@preserve_all | priv function, method | none | As @preserve_most, plus floating-point and vector registers |
@preserve_none | priv function, method | none | The callee saves nothing |
@open | plain enum | none | The enum may hold any value of its underlying type |
@implicit | fn op as | none | The conversion applies without as |
@copy | constructor | none | The copy constructor |
@move | constructor, parameter | none | The move constructor; on a parameter, take the argument by move |
@inout | parameter | none | The parameter is the caller's object, written back |
@create, @try_create | expression | in: A | Allocate and construct a T |
@destroy | expression | in: A | Destroy and free what a pointer points at |
@alloc, @alloc_zeroed | expression | count:, size:, align:, in: A | Allocate storage without constructing |
@free, @resize, @resize_in_place, @try_resize_in_place | expression | size:, new_size:, align:, in: A | Free or resize a block |
@set_scoped_allocator(A) | function, block, class, struct | A: an allocator type | Allocations in the body (or the object) come from A |
@cxx::new, @cxx::delete | expression | none | C++'s own new and delete |
@set_global_allocator(A) | a line of its own at file scope | A: an allocator type | The program's global allocator is A |
An attribute written where it does not apply is an error that says where it does, with a fix-it that removes it. An attribute that takes no arguments rejects one (SC144E).
Layout
@packed and @align
| Attribute | Description | Applies to |
|---|---|---|
@packed | Remove padding between members | Classes, structs, unions |
@align(N) | Set minimum alignment to N bytes | Classes, structs, unions, fields, variables |
@packed lays the members out back to back at alignment 1, with no padding between them or at the end, as C's __attribute__((packed)) does. @align(N) raises the alignment to N (it never lowers it below the natural alignment), and the size rounds up to a multiple of it. N is an integer literal, a power of two, at most 2^28; anything else is SC144E. On a field or a variable, @align(N) raises that member's or variable's alignment the same way. Together on one record, @packed @align(N) packs the members and aligns the whole to N, like __attribute__((packed, aligned(N))).
@packed struct P { var a: u8; var b: u32 } // sizeof 5, alignof 1
@align(16) struct Q { var a: u8 } // sizeof 16, alignof 16
@packed @align(4) struct PA { var a: u8; var b: u32 } // sizeof 8, alignof 4
struct F { var a: u8; @align(8) var b: u8 } // b at offset 8; sizeof 16
@align(32) var g: i32 = 1 // a variable
A misplaced use is SC143E ('@packed' applies only to a class, struct or union; '@align' applies only to a class, struct, union, field or variable).
The layout the compiler computes for sizeof and alignof in a declaration-scope eval if is the same one the compiled code has, so a branch chosen on a record's size matches the size at run time. A heap allocation of an @align(N) type through create is N-aligned: it asks the allocator for alignof T.
See Classes and Structures for layout details.
@relocatable
@relocatable says the record may be moved by copying its bytes, so a record with a destructor or a @move / @copy constructor is passed and returned the way a plain struct of the same layout is: in registers when it is small enough, where it would otherwise go through memory. A by-value parameter of such a type is destroyed by the function that receives it, not by the caller. In LLVM IR a small such record is passed as an integer register value, not through a pointer.
@relocatable
class Handle {
pub var fd: i32
pub fn Handle(self, fd: i32) { self.fd = fd }
@move pub fn Handle(self, other: Self) { self.fd = other.fd; other.fd = -1 }
pub fn op finally(self) { }
}
fn take(h: Handle) -> i32 { return h.fd } // h arrives in a register
fn main() -> i32 { return take(Handle(7)) }
Use it only on a type that holds no pointer into itself. The attribute takes no arguments, and it applies only to a class, struct or union (SC143E). It is an error (SC356E) on a record that is polymorphic, whose transfer constructors are deleted, or that holds a base or field that is not relocatable. A type is relocatable when it is one of these:
- a number,
bool,char, any pointer, a plain enum, anunsafe fnpointer, or a slice; - a record marked
@relocatable; - a record with no destructor and no
@copyor@moveconstructor of its own, no virtual function, and only relocatable bases and fields; - a fixed array or a tuple of relocatable types;
- an enum with payloads, or a
T?that is not a pointer, only when every payload is trivially copyable and trivially destroyed; - a C++ type whose copy and move constructors and destructor are trivial for calls, or one marked
[[clang::trivial_abi]].
A by-value @relocatable parameter is destroyed by the function that receives it, so such a function is never inferred const or @pure, and a hand-written const fn or @pure function that takes one is SC200E. The attribute changes the calling convention on the Itanium ABI targets (Linux, macOS, the BSDs). On the windows-msvc targets the calling convention is unchanged; the record is still relocatable to __builtin_is_trivially_relocatable. A record's layout and size are the same with and without it.
Branch hints
@likely, @unlikely and @unpredictable
| Attribute | Description | Applies to |
|---|---|---|
@likely | Condition is expected to be true | if statements |
@unlikely | Condition is expected to be false | if statements |
@likely / @unlikely before else | Hint for the else or else if branch that follows | else, else if |
@unpredictable | Condition follows no pattern a branch predictor can learn: the optimizer may compute both sides and select, with no jump | if statements |
@likely and @unlikely also go between a branch's closing } and the else after it; each hint is for the branch it precedes.
fn pick(a: bool, b: bool) -> i32 {
@likely if a {
return 1
} @unlikely else if b {
return 2
} @unlikely else {
return 3
}
}
@unpredictable if c { ... } is the attribute form of the intrinsic __builtin_unpredictable(c), which returns its bool argument. The intrinsic carries the hint only when its call is an if's whole condition; written anywhere else (negated, inside &&, stored in a variable), the hint is lost. A const or @pure function may call it.
fn pick(c: bool) -> i32 {
@unpredictable if c { return 10 }
return 20
}
On any other statement (@likely while false { }) or on a declaration, the error is SC143E: '@likely' applies only to an 'if' statement.
See Control Flow for branch prediction hints.
@assume
@assume(cond) tells the optimizer to take cond as true from here on; it is undefined behaviour if cond is false. It is not an attribute on anything: it is a statement on its own line.
fn half(n: i32) -> i32 {
@assume(n > 0)
return n / 2
}
Outside an unsafe block, @assume and __builtin_unreachable() are a warning (SC362W) from -O1 up, where the assert is stripped and a false condition is undefined behavior. At -O0 the condition is asserted and there is no warning. Wrapping the statement in unsafe acknowledges the risk:
fn f(n: i32) -> i32 {
@assume(n > 0) // warning at -O1 and above
unsafe { @assume(n > 1) } // acknowledged: no warning
return n
}
@unreachable
@unreachable is reserved for a branch that never executes. It is not implemented: it is rejected with SC116E.
fn body(x: i32) -> i32 {
@unreachable if x == 0 { return 0 } // error: '@unreachable' is not yet supported
return 3
}
Diagnostics
@deprecated
@deprecated (with no argument) or @deprecated("message") makes every use of the declaration a warning (SC146W) that names it and the message, with a note at the attribute. It applies to any declaration: a function, a type, a variable, a field. The declaration itself is not reported, and neither is a use inside it. Any argument other than one string literal is SC144E.
@deprecated("use read_all instead")
fn read() -> i32 { return 0 }
fn main() -> i32 { return read() } // warning: 'read' is deprecated: use read_all instead
On a @copy constructor, @deprecated also reports every implicit copy (SC354W): a variable initialized from another, a by-value argument, a field initializer, an assignment, a returned field, a tuple or container literal, a loop binder, a closure capture. A copy of a struct, tuple, nullable or container that holds such a value is reported too, and the warning names the part. When the type has a copy() method, the warning carries a fix-it that appends .copy().
class Text {
pub var n: i32
pub fn Text(self, n: i32) { self.n = n }
@deprecated("copy with .copy()")
@copy pub fn Text(self, const other: Self) { self.n = other.n }
pub fn copy(const self) -> Text { return Text(self.n) }
}
fn take(t: Text) -> i32 { return t.n }
fn main() -> i32 {
var a = Text(1)
var b = a // warning: implicit copy of a 'Text'
var c = a.copy() // no warning
return take(a) + b.n + c.n // warning: take() takes its Text by value
}
Not reported: a returned local or by-value parameter (it is moved), a const parameter (nothing is copied), a copy inside a generic function's body, and a copy made inside C++ code the value is passed to by reference (cxx::std::vector<Text>::push_back(a)).
@no_warn
@no_warn(CODE, ...) drops those warnings wherever they are reported inside the declaration, by any stage of the compiler. Each code must be a warning code (SC031W): an unknown code is an error, and so is an error code, since an error cannot be suppressed. With no code the attribute is an error too (SC144E).
@no_warn(SC031W)
fn f() -> i32 { var y: i32 = 1 as i32; return y } // no redundant-cast warning
fn g() -> i32 { var y: i32 = 1 as i32; return y } // warning: redundant cast
@no_warn also covers warnings the parser reports inside the declaration, such as S055W. Lexer and preprocessor warnings, such as S025W, are not covered.
Unwinding
@unwind and @no_unwind
| Attribute | Description | Applies to |
|---|---|---|
@unwind | Let a C++ exception pass through this function | Functions, methods |
@no_unwind | Keep the function non-unwinding, even under -funwind | Functions, methods |
Every Kairo function is nounwind in LLVM IR: a C++ exception that reaches a Kairo frame terminates the program (std::terminate). @unwind removes nounwind from one function, so a C++ exception thrown by a C++ callee unwinds through it to the next frame up. The -funwind flag removes it from every Kairo function, closures included; @no_unwind keeps it on one function even then. Marking one function both is an error (SC267E), and @no_unwind wins.
fn add(a: i32, b: i32) -> i32 { return a + b }
@unwind fn relay(x: i32) -> i32 { return x }
@no_unwind fn keep(x: i32) -> i32 { return x }
Writing @unwind or @no_unwind on any one declaration of a function covers all of them: a forward declaration, the declaration inside a class, or the out-of-line definition.
class Counter {
var n: i32
@unwind fn get(const self) -> i32 // declared here...
}
fn Counter::get(const self) -> i32 { return self.n } // ...so this definition is not noexcept either
A closure cannot carry @unwind yet: written before a closure, it is an expression attribute, which is not supported. A closure follows -funwind. On anything but a function the error is SC143E.
See Exceptions for how C++ exceptions move through Kairo code.
Function hints
@hot_path and @cold_path
| Attribute | Description | LLVM IR | Applies to |
|---|---|---|---|
@hot_path | The function runs often: optimize it for speed and keep it close to other hot code | hot | Functions, methods |
@cold_path | The function runs rarely (error handling, setup): optimize it for size and keep it out of the way | cold | Functions, methods |
@hot_path fn next(state: *u64) -> u64 { *state = *state * 6364136223846793005 + 1; return *state }
@cold_path fn report_failure(code: i32) { }
@hot_path together with @cold_path on one function is an error (SC147E), and either on something that is not a function ('@hot_path' applies only to a function) is SC143E with a fix-it that removes it.
@pure
| Attribute | Description | LLVM IR | Applies to |
|---|---|---|---|
@pure | The function's result depends only on its inputs and memory it can read, and it writes nothing else | memory(read) | Functions, methods |
struct Vec3 { var x: f64; var y: f64; var z: f64 }
@pure fn length_sq(v: *Vec3) -> f64 { return v->x * v->x + v->y * v->y + v->z * v->z }
Each hint on this page is a promise to the optimizer, written on the function and checked where the compiler can. @pure is checked. The function must return a value, must not be -> !, @unwind, virtual or an interface requirement (an override would not be held to the promise), and its result type must not own memory. In its body the compiler reports (SC200E):
- a write to a global or
staticvariable; - an assignment through a pointer (
*p = x,p->field = x,p[i] = x), to a field ofself, or to an@inoutparameter; - a call to anything that is not a const function, another
@purefunction, aneval fnor a side-effect-free compiler intrinsic; a user operator is a call too, and a call through a function value or an interface requirement is always an error. The bit intrinsics (__builtin_ctz,__builtin_clz,__builtin_popcount,__builtin_bswap,__builtin_rotl,__builtin_rotr) are side-effect free.__builtin_copyis allowed when its destination is the function's own local: its address, an element of a local array, or a field of a local reached by.; any other destination is an error; - making a value that owns memory (a
string, an f-string, a vector, a local of such a type, a by-value copy of one); assert,unwrap!, an asserting downcast,delete, inline C++,spawn,threadandawait;- a
for ... inloop over anything but a range (0..n) or a fixed-size array.
static counter: i32 = 0
@pure fn bump() -> i32 { counter += 1; return counter } // error: 'bump' is @pure, so it cannot write the global 'counter'
@pure fn nothing() { } // error: 'nothing' is @pure but returns no value
Reading globals and reading through pointers is allowed; that is the difference between @pure and a const function, which may read only its own inputs. A @pure function whose result changes between calls with the same arguments because something else wrote the memory it reads is fine: the optimizer only merges calls when no write could have happened in between.
By default the compiler also finds the functions that keep the const or @pure promise without saying so, by the same rules, and gives them the same attribute, on their declaration in every file that imports them. -fno-infer-purity turns this off.
A named predicate the compiler proves has no effect, cannot stop the program, has no loop and reads through no pointer but its arguments may also be run by std::iter on elements past the one that ends a scan. find, position, any, all, skip_while and take_while(p).count() over a slice of numbers (or its rev()) test 32 elements at a time with such a predicate. The answer is the same as a loop over the items gives. Two things differ: a thread that writes those later elements during the scan races with it, and the predicate runs up to 32 times more often. A predicate that must see only the elements up to the deciding one should be a closure, or contain a loop or an effect.
@no_inline
| Attribute | Description | LLVM IR | Applies to |
|---|---|---|---|
@no_inline | Never inline the function: it keeps its own symbol and its own code, as for a benchmark kernel or a rarely taken path kept out of its caller | noinline | Functions, methods |
@no_inline fn k(a: i32, b: i32) -> i32 { return a + b }
Calling conventions
| Attribute | Description | LLVM IR | Applies to |
|---|---|---|---|
@preserve_most | The callee saves nearly every general-purpose register: for a rarely taken slow path called from hot integer code | preserve_mostcc | priv functions and methods |
@preserve_all | As @preserve_most, and the callee also saves the floating-point and vector registers | preserve_allcc | priv functions and methods |
@preserve_none | The callee saves nothing: for tail-call-heavy dispatch, such as an interpreter's opcode handlers | preserve_nonecc | priv functions and methods |
@preserve_most
priv fn slow(n: usize) -> usize { return n + 1 }
@preserve_all
priv fn slow_fp(x: f64) -> f64 { return x + 1.0 }
@preserve_none
priv fn dispatch(n: usize) -> usize { return n + 2 }
At most one per function (two are SC133E), never on a function C or C++ can see, and only on x86-64 and AArch64 (SC137E elsewhere). On anything but a function the error is SC143E. See Calling conventions for the rules and the register table.
Enums
@open
| Attribute | Description | Applies to |
|---|---|---|
@open | The enum may hold any value of its underlying type: no checked as, no niche | Plain enums |
A plain enum is closed by default; see Closed and open enums.
@open enum Signal derives u8 {
Hup = 1,
Int = 2,
Kill = 9,
}
fn main() -> i32 {
var s = 15 as Signal // fine: Signal is open, 15 is a value it may hold
return (s as u8) as i32
}
Without @open, 15 as Signal is SC252E, with a fix-it that adds @open. @open on anything but a plain enum is SC143E (only a plain enum can be open).
Conversions
@implicit
| Attribute | Description | Applies to |
|---|---|---|
@implicit | Lets a conversion operator apply without as | fn op as in a type's body or an extension |
struct Name {
var first: string
var last: string
@implicit fn op as (const self) -> string {
return f"{self.first} {self.last}"
}
}
fn greet(who: string) -> usize { return who.size() }
fn main() -> i32 {
var n = Name { first: "Ada", last: "Lovelace" }
return greet(n) as i32 // n as string, applied implicitly
}
On any other function the error is SC115E: '@implicit' applies only to a conversion operator. See Implicit op as for the rules.
Ownership and lifecycle
@copy and @move
| Attribute | Description | Applies to |
|---|---|---|
@copy | The constructor that copies: @copy fn T(self, const other: Self) | Constructors |
@move | The constructor that moves: @move fn T(self, other: Self) | Constructors |
@move x: T | On a parameter: the argument is taken by move | Parameters |
@copy or @move on a function that is not a constructor (no self, or a free function) is an error (SC143E). A @move constructor of a class with a destructor must leave its source empty; one that only reads other warns (SC001W), since C++ containers destroy the moved-from source.
class Buffer {
pub var n: i32
pub fn Buffer(self, n: i32) { self.n = n }
@copy
pub fn Buffer(self, const other: Self) { self.n = other.n }
}
class UniqueFile {
pub var fd: i32
pub fn UniqueFile(self, fd: i32) { self.fd = fd }
@move
pub fn UniqueFile(self, other: Self) { self.fd = other.fd; other.fd = -1 }
}
fn main() -> i32 {
var a = Buffer(3)
var b = a // copies
var f = UniqueFile(4)
var g = f // moves
return a.n + b.n + g.fd
}
On a type the error is SC143E ('@copy' applies only to a copy or move constructor). The transfer constructor's rules, and the parameter form of @move, are in Classes: lifecycle and Parameter modes.
@inout
| Attribute | Description | Applies to |
|---|---|---|
@inout x: T | The parameter is the caller's object, written back | Parameters |
@inout and @move on a parameter are passing modes, not attributes of the declaration: they are written before the parameter name and are allowed only on the parameter of a function or closure.
class Buffer {
pub var n: i32
pub fn Buffer(self, n: i32) { self.n = n }
@move pub fn Buffer(self, other: Self) { self.n = other.n }
}
fn bump(@inout x: i32) { x += 1 }
fn consume(@move b: Buffer) -> i32 { return b.n }
fn main() -> i32 {
var n: i32 = 5
bump(&n) // an @inout argument is written &n
var b = Buffer(10)
return n + consume(b) // a @move argument is written bare
}
Anywhere else (var y: @inout i32, var @inout z: i32) is S069E; before a function it is SC143E ('@inout' is a parameter passing mode). See Parameter passing modes.
The allocation attributes
Each allocation attribute is an expression attribute that stands for a call of a function in the builtin allocation library, which needs no import. Every form takes in: A to name the allocator; without it the allocator in effect is used (the innermost open scoped allocator, else the global one).
| Attribute | Without in: | With in: A |
|---|---|---|
@create Box(1), @create P { x: 1 } | create<T>(...) | create_in<T, A>(...) |
@try_create Box(1): *Box, raises AllocError | try_create<T>(...) | try_create_in<T, A>(...) |
@destroy p, @destroy(p) | destroy(p) | destroy_with<A>(p) |
@alloc Box: Uninitialized<Box>? | alloc_storage<T>() | alloc_in<T, A>() |
@alloc(count: n) Box | create_slice<T>(n) | create_slice_in<T, A>(n) |
@alloc(size: n, align: 8) | alloc_raw(n, 8) | alloc_bytes<A>(n, 8) |
@alloc_zeroed(size: n, align: 8) | alloc_raw_zeroed(n, 8) | alloc_zeroed<A>(n, 8) |
@free p | free_storage(p) | free_storage_with<A>(p) |
@free(size: n, align: 8) p | free_raw(p, n, 8) | free_bytes<A>(p, n, 8) |
@resize(size: old, new_size: n, align: 8) p | resize_raw(...) | resize_bytes<A>(...) |
@resize_in_place(size: old, new_size: n, align: 8) p: bool | resize_raw_in_place(...) | resize_in_place<A>(...) |
@try_resize_in_place(size: old, new_size: n, align: 8) p: raises AllocError | try_resize_raw_in_place(...) | try_resize_in_place<A>(...) |
@free p takes a *T, an Uninitialized<T> or an UninitializedSlice<T>. size: and align: describe the block as it is; new_size: is the size asked for.
The operand follows on the same line. @create and @try_create take a construction, a call of the type or an initializer; @alloc takes a type; @destroy and @free take one pointer. @create with no operand is S052E. A pointer, array or tuple type is not a name, so it is given one with type first (@create [T](...) is SC364E); a primitive is accepted (@alloc(count: n) u8).
An attribute takes no generic arguments. @create<T>(args) is S001E ('@create' takes no generic arguments) with a fix-it to @create T(args), and @destroy<T>(p) is S001E with a fix-it to @destroy(p). A type argument belongs to the type: @create Box<i32>(1). An operand the form cannot take is SC364E, and an argument list it does not take is SC365E (a missing, unknown or repeated keyword, a positional argument, a combination no form has, an in: that is not a type).
class Config {
pub var port: i32
pub fn Config(self, port: i32) { self.port = port }
}
fn main() -> i32 {
var *cfg = @create Config(8080)
var p = cfg->port
@destroy cfg
return p - 8000
}
An explicit allocator:
var *a = @create(in: A) Box(1)
var *b = try @try_create(in: A) Box(2) catch e: AllocError => a // A is out of memory
@destroy(in: A) a
@create is fatal when memory runs out. @try_create follows the X and try_X rule: it returns the object, or raises AllocError with nothing constructed. AllocError is a builtin name and carries the request: size(), align(), and the message allocation failed: N bytes at alignment A.
@resize_in_place resizes a block without moving it and gives true on success. @try_resize_in_place raises AllocError (the size asked for) where that gives false, and leaves the block as it was.
import std::io
import std::mem::try_create
class Box {
pub var v: i32
pub fn Box(self, v: i32) { self.v = v }
}
fn main() -> i32 {
var *a = @create Box(1)
try {
var *c = try_create<Box>(3)
io::println(f"{c->v}")
@destroy c
} catch e: AllocError {
io::println(f"{e.size()} {e.align()}")
}
var unsafe *p = @alloc(size: 64, align: 8)
var shrunk = @resize_in_place(size: 64, new_size: 32, align: 8) p
try {
@try_resize_in_place(size: 32, new_size: 1 << 40, align: 8) p
} catch e: AllocError {
io::println(f"{shrunk} {e.size()} {e.align()}")
}
@free(size: 32, align: 8) p
@destroy a
return 0
}
Changed in 0.3.0. @resize_in_place is the bool form that was @try_resize, and @try_create raises AllocError where it returned null.
See Heap Allocation and Allocators.
@set_scoped_allocator
@set_scoped_allocator(A) takes one argument, the allocator type, and goes on a function, a block, a class or a struct.
On a function or a block, an AllocatorScope<A> opens at the start and closes on every exit (a return, the end of the block, a break or continue out of it, a panic). Everything allocated in the body through the allocator in effect comes from A. A must be a ScopedFullAllocator: the five static allocator functions plus enter, leave and range. Several attributes on one node open one scope each; the last one written is the innermost.
@set_scoped_allocator(ArenaA)
fn build() -> i64 {
var *n = @create Node(1i64) // from ArenaA
...
}
fn work() {
@set_scoped_allocator(ArenaB) {
var *n = @create Node(2i64) // from ArenaB
@destroy n
} // the scope closes here
}
An expression-bodied function needs a written return type (fn size() -> usize = 4), because the scope opens in a block body and a block body does not infer the return type.
On a class or struct, each object owns an arena of A, and every method of the type allocates from it: the constructors, the destructor's body, operators, const, generic and out-of-line methods, and the methods of an extend of the type. A static method does not. The arena is freed when the object is destroyed. A must implement ArenaAllocator (see Allocators).
@set_scoped_allocator(Arenas)
class Log {
pub var text: string
pub var items: [i32]
fn add(self, n: i32) {
self.items.push(n) // grows inside this object's arena
}
}
- The object holds two hidden fields (16 bytes).
- The type is move-only unless it writes a
@copyconstructor; a copy gets an arena of its own. - A class that derives from it does not inherit the attribute.
- One attribute per type. On an
extendit is SC366E: put it on the type.
Errors: SC366E for an attribute with no argument, several arguments, a keyword argument or a non-type argument, for a function with no body, for an expression body with no written return type (a method of an arena type included), for an extend, and for a second attribute on one type. SC367E for a yield inside a scoped function or block, or in a generator method of an arena type. SC143E where the attribute does not apply at all. An extend method of an arena type whose A is the type's own generic parameter is SC116E.
A value that owns arena memory and leaves its object (returning a copy of a field, moving a field out of the object) outlives the arena: this is the scoped-allocator escape, undefined behaviour with no diagnostic. A pointer from a function or block scope that visibly outlives it is SC225W.
Interop
@cxx::new and @cxx::delete
C++'s own new and delete, for memory that belongs to C++. They are expression attributes with a scope: @cxx:: must be followed by new or delete (S046E otherwise), and @cxx alone is an unknown attribute.
fn main() -> i32 {
var n: i32 = 4
var unsafe *p = @cxx::new [i32; n] // C++: new int[n]
var s: i32 = 0
for var i: i32 = 0; i < n; ++i {
unsafe { p[i] = (i + 1) * 10 }
}
for var i: i32 = 0; i < n; ++i {
unsafe { s += p[i] }
}
@cxx::delete [] p // C++: delete[] p
return s
}
@cxx::new T(args) and @cxx::new [T; n] give an unsafe *T; @cxx::delete p and @cxx::delete [] p free it. See C++ memory for the pairing rules.
Other
@set_global_allocator
@set_global_allocator(A) makes A the program's global allocator. It is not an attribute of a declaration: it stands on a line of its own at file scope. Written before a declaration, or inside a function, it is SC139E; a second one in the same file is SC138E.
import builtin::base::alloc::*
static n: i32 = 0
class Counting {
pub static fn alloc(size: usize, align: usize) -> unsafe *u8 { n += 1; return System::alloc(size, align) }
pub static fn free(ptr: unsafe *u8, size: usize, align: usize) { System::free(ptr, size, align) }
static fn resize(ptr: unsafe *u8, o: usize, nn: usize, align: usize) -> bool { return nn <= o }
static fn realloc(ptr: unsafe *u8, o: usize, nn: usize, align: usize) -> unsafe *u8 { return realloc_by_copy<Counting>(ptr, o, nn, align) }
static fn alloc_zeroed(size: usize, align: usize) -> unsafe *u8 { return System::alloc_zeroed(size, align) }
}
@set_global_allocator(Counting)
fn main() -> i32 {
var *p = create<i64>(1i64)
destroy<i64>(p)
return n // 1: the allocation went through Counting
}
See Global allocator for the allocator interface and the one-per-program rule.