Native allocators
Choose where objects live while retaining Xenon construction, cleanup and target ABI rules.
Storage policy is part of the language
A native allocator controls where a typed object or array obtains its storage. Xenon still owns construction, destruction, array layout and the call that returns storage to the original provider. The feature is available in Core and requires no standard-library interface.
Use an allocator for an arena, fixed-size pool, allocation accounting or another storage policy. Ordinary new T(...) keeps using the built-in native allocator. new(provider) T(...) selects an explicit provider for that allocation.
Download the complete runnable examples. Save the file in its own directory and run xenon run . or xenon run . --release. The program checks the examples and exits with code zero on success.
Declare an allocator and its operators
allocator HeapAllocator {
public int allocations;
public int releases;
public +HeapAllocator(nuint size, nuint alignment) {
allocations++;
return malloc(size, alignment);
}
public -HeapAllocator(void* block) {
releases++;
free(block);
}
}
allocator declares a nominal allocator type. It can have fields, ordinary methods, ordinary constructors, allocation context constructors and a destructor. The name is a keyword, so use names such as heap or provider for variables.
+HeapAllocator(nuint size, nuint alignment)implicitly returnsvoid*. It must provide at leastsizewritable bytes with the requested power-of-two alignment.-HeapAllocator(void* block)implicitly returnsvoid. It receives exactly the address returned by the matching allocation operator.- The operator name must match its declaring type. Do not write an explicit return type. A concrete allocator must declare or inherit both operations.
- These are special language operations, not ordinary callable methods. Invoke them through
new(provider)anddelete; direct calls are unavailable.
| Declaration | Purpose |
|---|---|
Type(...) | Ordinary constructor. |
@Type() | Context constructor for construction without an explicit allocator. |
@Type(Provider* parent) | Allocation context constructor in a struct or allocator. |
+Allocator(nuint size, nuint alignment) | Allocate raw storage for objects using this allocator. |
-Allocator(void* block) | Release storage previously supplied by this allocator. |
Both operations are instance operations and participate in virtual dispatch. Access control applies to both at the allocation site. The heap example forwards to malloc(size, alignment) and free(block) while counting requests.
Create allocator instances in the heap
HeapAllocator* heap = new HeapAllocator();
ArenaAllocator* arena = new(heap) ArenaAllocator(cast<nuint>(4096));
PoolAllocator* pool = new(arena) PoolAllocator();
// Delete every object using pool before deleting pool itself.
delete(pool);
delete(arena);
delete(heap);
An allocator value has ordinary value-versus-pointer syntax: HeapAllocator* is a pointer to a heap instance. A local HeapAllocator heap, an embedded allocator field, a by-value allocator parameter or return, and a stack array of allocator values are rejected. Wrapping the value in atomic or a lifetime modifier does not permit stack storage.
Allocator instances may themselves be created through another allocator. The same allocation metadata and lifetime rules apply at every level. Creating an arena object through heap does not automatically redirect allocations performed inside the arena's constructor; the arena example below obtains its backing buffer explicitly with malloc.
Allocate typed objects
HeapAllocator* heap = new HeapAllocator();
int* number = new(heap) int(42);
int[] values = new(heap) int[16];
delete(number);
delete(values);
delete(heap);
The provider expression must produce a mutable pointer to an allocator type. Its static type must expose an accessible allocation/deallocation pair, including when that type is abstract. A pointer to an ordinary struct or interface, a readonly provider pointer or an abstract allocator type with no operator contract cannot be used. An interface pointer does not guarantee the allocator category even when its concrete object is an allocator.
Xenon computes target size and alignment, calls the allocation operator, initializes the object and returns a typed pointer. A null provider, a null returned block, or an overflowing allocation size traps. An exception thrown by the allocation operator follows ordinary exception propagation.
Types without an allocation context constructor can use either ordinary or explicit-provider new. Ordinary structs retain their existing stack construction; allocator instances always require heap storage.
Initialize provider-dependent values with @Type
struct Packet {
public allocator HeapAllocator* provider;
public int value = 5;
public @Packet(HeapAllocator* heap) {
provider = heap;
}
public Packet(int extra) { value += extra; }
}Packet* packet = new(heap) Packet(7); // value is 12
Packet[] packets = new(heap) Packet[3]; // each value is 5
delete(packet);
delete(packets);
An allocator field stores a provider for use during ordinary initialization. Its type must be a direct, mutable pointer to a language-level allocator, such as HeapAllocator* or the abstract AllocatorBase*. Derived and generic allocator types qualify under the same rule. Primitive values, interface pointers, pointers to pointers, and ordinary structs (including wrappers around allocator pointers) are invalid.
The modifier applies only to instance fields. An allocator field retains its declared accessibility, cannot be static, const or readonly, and cannot have a declaration initializer. It starts at null and may remain unassigned.
Context constructors run from base to derived. After all succeed, ordinary field initializers and constructor bodies can read the stored pointers. Constructor delegation does not repeat the context phase.
Inside @Type, use parameters, locals, constants and control flow. Static methods and free functions may have side effects or throw. The only access to the object being constructed is a direct assignment to one of its own marked fields. These fields are write-only throughout the phase, even after assignment; repeated and conditional assignments are allowed. Instance properties, methods and ordinary fields are unavailable, and this cannot be passed or captured.
// Inside @Packet:
provider = heap; // valid
// Observe(provider); // invalid: reads provider
// value = 5; // invalid: ordinary field
// Observe(this); // invalid: exposes the incomplete object
Unlike a readonly field, an allocator field cannot be assigned by the ordinary constructor. Once the context phase ends, accessible code can read the field, and a mutable pointer stored in it can still be used to modify its target.
Every level that declares context constructors must have a compatible overload. Without an explicit provider, that overload is @Type(); with a provider, it must accept a compatible allocator pointer. Packet above has no parameterless context constructor, so new Packet(7) and stack construction Packet(7) are rejected. A type may overload @Type for different allocator types and for construction without a provider. Allocation context constructors are not virtual, abstract or directly callable.
Copying an already initialized value uses existing copy semantics and does not rerun @Type. An embedded field requiring allocation initialization must be initialized explicitly as a whole value; zero initialization or assigning one of its subfields cannot bypass that requirement. An outer provider is not silently forwarded to every embedded field.
Initialize an allocator with its parent provider
The ArenaAllocator example declares @ArenaAllocator(HeapAllocator* source) alongside its ordinary constructor and its + / - operators. The context constructor stores the parent in an explicitly declared field. For new(heap) ArenaAllocator(capacity), construction proceeds as follows:
heapallocates storage for the ArenaAllocator object.- Applicable base-to-derived context constructors run, including
@ArenaAllocator(heap). - Ordinary field initializers run, followed by
ArenaAllocator(capacity). - The expression returns the initialized
ArenaAllocator*.
The new arena's own allocation operator does not allocate the arena object. It is used for later allocations through new(arena). The PoolAllocator example receives that arena through @PoolAllocator(ArenaAllocator* source), producing a heap-to-arena-to-pool chain. There is no special nesting-depth limit.
Context constructors follow the same inheritance, overload selection and cleanup rules for structs and allocators. Ordinary new Allocator() selects parameterless context constructors at every level that declares a context requirement; new(parent) Allocator() selects compatible pointer overloads. An allocator without context constructors, such as HeapAllocator, retains ordinary construction. Allocator values still require heap storage. No implicit provider field, ownership or copying is introduced.
Allocator inheritance and abstract contracts
abstract allocator AllocatorBase {
public abstract +AllocatorBase(nuint size, nuint alignment);
public abstract -AllocatorBase(void* block);
}
allocator CountingHeap : AllocatorBase {
public int releases;
public +CountingHeap(nuint size, nuint alignment) {
return malloc(size, alignment);
}
public -CountingHeap(void* block) {
releases++;
free(block);
}
}
struct Buffer {
public allocator AllocatorBase* provider;
public @Buffer(AllocatorBase* source) { provider = source; }
}CountingHeap* concrete = new CountingHeap();
AllocatorBase* contract = concrete;
Buffer* buffer = new(contract) Buffer();
delete(buffer); // dispatches to CountingHeap's release operation
delete(concrete);
An allocator may inherit from an allocator. Ordinary structs and allocator types cannot be mixed in one inheritance chain. A derived allocator may inherit its operator pair unchanged or replace both operations. Replacing only one is rejected because allocation and release must remain a matched pair. Overrides are recognized implicitly when an inherited operation exists.
An abstract allocator can declare abstract operators. A concrete descendant must supply the missing implementations. An abstract base without an operator pair can organize types, but a pointer to that base cannot be the static provider of new.
Static constructor selection, dynamic storage dispatch
Context-constructor selection uses the static type of the provider expression. A constructor accepting a base allocator pointer is compatible with a derived allocator pointer. When several overloads apply, the nearest allocator ancestor wins. Every context-constructor requirement in the allocated object's base chain must be satisfied.
The allocation and release operators use the provider's dynamic type. Therefore a base allocator pointer may select @Buffer(AllocatorBase*) while storage comes from CountingHeap. Erasing a derived provider to a base pointer does not make a derived-only context-constructor overload available.
These compatibility rules are identical for structs and allocators. For example, @PoolAllocator(ArenaAllocator*) accepts an ArenaAllocator pointer or a pointer to its descendant. A HeapAllocator pointer, or a base pointer that no longer exposes ArenaAllocator statically, cannot satisfy that declaration.
Access to context constructors
A context constructor is private by default. It accepts the same access modifiers as an ordinary constructor, including protected and protected internal. At the construction site, the selected context constructor at each inheritance level, the ordinary constructor when invoked, and both operations of an explicit allocator must all be accessible.
public struct ScopedBuffer {
public allocator AllocatorBase* provider;
public @ScopedBuffer() {}
internal @ScopedBuffer(AllocatorBase* source) { provider = source; }
private @ScopedBuffer(CountingHeap* source) { provider = source; }
public static ScopedBuffer* Create(CountingHeap* source) {
return new(source) ScopedBuffer();
}
}
Any caller can use new ScopedBuffer(). Code in the same compilation can pass an AllocatorBase* to the internal overload. With a CountingHeap*, the private overload wins. Outside ScopedBuffer, use ScopedBuffer.Create(heap) to call it. Imported generic factories retain the access rights of their declaration.
Multiple context constructors
struct OverloadedBuffer {
public allocator AllocatorBase* baseSource;
public allocator CountingHeap* heapSource;
public allocator ArenaAllocator* arenaSource;
public int extra;
public @OverloadedBuffer(AllocatorBase* source) { baseSource = source; }
public @OverloadedBuffer(CountingHeap* source) { heapSource = source; }
public @OverloadedBuffer(ArenaAllocator* source) { arenaSource = source; }
public OverloadedBuffer(int extra) { this.extra = extra; }
}
For each level of the constructed type's inheritance chain that declares context constructors, Xenon selects exactly one overload. An exact allocator-pointer match wins; otherwise the nearest compatible allocator ancestor wins. Selected bodies run from base to derived, followed by ordinary construction. Other overloads at the same level do not run.
CountingHeap* concrete = new CountingHeap();
AllocatorBase* contract = concrete;
OverloadedBuffer* exactChoice = new(concrete) OverloadedBuffer(10); // heapSource == concrete
OverloadedBuffer* baseChoice = new(contract) OverloadedBuffer(10); // baseSource == contract
OverloadedBuffer[] variants = new(concrete) OverloadedBuffer[3]; // each heapSource == concrete
// Array elements have extra == 0.
delete(exactChoice);
delete(baseChoice);
delete(variants);
delete(concrete);
The two scalar allocations use the same provider object, but the static pointer types select different constructors. An ArenaAllocator pointer selects the independent third overload. Allocator declarations support the same overload sets:
allocator ChildHeap : CountingHeap {
public allocator AllocatorBase* baseParent;
public allocator CountingHeap* heapParent;
public @ChildHeap() {}
public @ChildHeap(AllocatorBase* source) { baseParent = source; }
public @ChildHeap(CountingHeap* source) { heapParent = source; }
}CountingHeap* concrete = new CountingHeap();
ChildHeap* child = new(concrete) ChildHeap(); // heapParent == concrete
OverloadedBuffer* nearest = new(child) OverloadedBuffer(10); // heapSource == child
// ChildHeap* converts to the nearest accepted ancestor, CountingHeap*.
delete(nearest);
delete(child);
delete(concrete);
A context constructor takes either no parameters or exactly one mutable allocator pointer. Extra arguments, arbitrary context objects and interface pointers are not supported. A level without a compatible overload is an error. An inaccessible best match is also an error: selection does not fall back to a less specific public overload or to @Type().
Duplicate signatures and ambiguous best matches are errors. Generic specialization applies the same checks: for example, overloads accepting Provider<T>* and Provider<int>* collide when T is int. Source-free XELIB imports and static or shared library builds preserve these rules.
Value arrays use the selected context-constructor chain for every element within one allocation. Pointer arrays run no context constructors. If a selected body throws, normal partial-construction cleanup applies; no other overload is tried.
Construct without an explicit allocator using @Type()
struct DefaultPacket {
private allocator HeapAllocator* provider;
public HeapAllocator* observed = provider;
public int extra;
public @DefaultPacket() {}
public @DefaultPacket(HeapAllocator* source) { provider = source; }
public DefaultPacket(int extra) { this.extra = extra; }
}DefaultPacket local = DefaultPacket(10); // observed == null
DefaultPacket* system = new DefaultPacket(10); // observed == null
DefaultPacket* custom = new(heap) DefaultPacket(10); // observed == heap
delete(system);
delete(custom);
@Type() is the context overload for creation without an explicitly supplied allocator. It receives no allocator instance, allocates no storage by itself and does not change where the object lives. Stack creation stays on the stack; ordinary new uses system heap storage. The selected context constructor runs before the ordinary constructor.
Selection is separate for each level of inheritance: a level with context constructors must provide an accessible @Type() for stack or system-heap creation. These bodies run once, base to derived, before any ordinary field initializer. Ordinary constructor delegation and copying an existing value do not repeat the context phase. Explicit construction into storage<T> and pin<T> follows the same rule at the final destination; merely reserving empty storage does not construct T.
DefaultPacket[] stackValues = DefaultPacket[2]; // each observed == null
DefaultPacket[] systemValues = new DefaultPacket[2]; // each observed == null
DefaultPacket[] customValues = new(heap) DefaultPacket[2]; // each observed == heap
delete(systemValues);
delete(customValues);
Value arrays run the selected context chain for every constructed element, without calling ordinary user constructors. Stack-array lifetime rules remain unchanged; pointer arrays do not construct pointed-to objects. Partial construction uses the same cleanup rules for parameterless and allocator-pointer overloads.
An explicit new(provider) never considers @Type(). For example, new(arena) DefaultPacket(10) is rejected when arena has the unrelated ArenaAllocator type, even though DefaultPacket has a parameterless context constructor. A type with context constructors but no suitable overload is an error; a type with no context requirement uses ordinary construction.
ChildHeap* systemHeap = new ChildHeap(); // both parent pointers are null
delete(systemHeap);
// ChildHeap local = ChildHeap(); // error: allocator instances require heap storage
The ChildHeap declaration above combines a parameterless context constructor with parent-provider overloads. Its parameterless overload enables ordinary heap creation and does not permit stack allocator values.
One allocation for an entire array
Packet[] packets = new(heap) Packet[3];
Packet*[] pointers = new(heap) Packet*[3];
int[,] matrix = new(heap) int[2, 3];
delete(packets);
delete(pointers);
delete(matrix);
The provider receives one request for the entire array, including its representation metadata. Xenon does not allocate each value element separately. Each constructed struct or allocator value element runs its applicable context-constructor chain before its ordinary field initializers.
Existing array semantics remain intact: array creation does not invoke ordinary user constructors for each element. Pointer elements are initialized as pointers; creating Packet*[] neither creates Packet objects nor invokes @Packet. Rectangular array elements share one contiguous allocation. A jagged array's separately created inner arrays have their own providers.
delete(array) destroys value elements in reverse linear order, then releases the whole block once. If construction fails partway through, only completed elements and initialized subobjects are cleaned up before storage release. Array ownership and bounds checking retain their existing behavior.
Destroy the object, then release its original storage
delete(pointer) runs ordinary object destruction, restores the saved provider and original block address, and invokes the matching release operation. The caller does not supply the allocator again. For ordinary new, the same typed cleanup path falls back to native storage release.
The metadata remains valid when a derived object is viewed through its offset-zero base subobject. Derived destruction through a base pointer still requires the existing virtual destructor contract; allocator metadata does not change that language rule.
delete(null) is a no-op. Do not delete interior pointers, stack addresses, unrelated external allocations or the same block twice. Existing unique and shared ownership cleanup uses the same allocator-aware release path.
{
unique<Packet> owned = new(heap) Packet(1);
} // destroys Packet and returns its block to heap
// heap must still be alive here
Construction failures and exceptions
If a context constructor throws, no ordinary initializer or constructor runs. Locals unwind normally and the original exception propagates. If any construction phase throws, Xenon destroys the initialized subobjects and invokes the captured release operation once. It does not run a complete destructor for an object whose construction never finished. This includes exceptions from @Allocator: cleanup returns the allocator object's storage to its parent, rather than using the incomplete allocator's own release operator. Fully constructed base subobjects retain their ordinary destruction rules.
During normal deletion, cleanup continues through remaining initialized fields or array elements before releasing storage when a destructor throws. Allocation, destructor and release exceptions participate in the existing exception model. A second exception during exception unwinding follows the language's termination rule.
The release callback is attempted once; it is responsible for completing its own storage policy. A callback that throws before releasing a block is not retried, and Xenon cannot substitute free for an arbitrary allocator. The compiler accounts for callback effects in async, readonly and cleanup analysis.
Raw memory and typed lifetime are separate
mallocandcallocobtain raw storage and do not construct objects.freereleases storage only, without destructors or allocator dispatch.newanddeletemanage typed construction, destruction and the matching storage provider.- Use
deletefor a custom allocation.freecannot recover its provider. Known custom-allocation aliases passed tofreeare diagnosed. - Known
malloc/callocallocations passed todeleteare diagnosed. Usefreeafter any required manual destruction.
For compatibility, built-in new storage can still be released by free after its live objects have been ended explicitly; trivial built-in arrays also retain storage-only release. This does not invoke destructors and is not valid for custom-provider blocks. Prefer delete for normal typed cleanup.
Allocation-origin diagnostics track known local origins and aliases. An arbitrary pointer received from an external function or opaque call does not prove a compatible allocation origin; the programmer remains responsible for pairing allocation and release correctly.
Provider lifetime and concurrency are your responsibility
The provider must outlive every block whose release callback refers to it. Destroy allocations first, then their provider, then any provider used to allocate that provider. This also applies when the allocated objects have compiler-managed ownership.
No allocator-specific lifetime checker, implicit ownership of the provider or automatic reference count is added. Resetting an arena, releasing a backing buffer or destroying a pool while its objects remain live invalidates those objects. A raw pointer does not extend a lifetime.
The built-in native allocator is thread-safe. User-defined allocator state is governed by ordinary memory-model rules. The arena, pool and accounting examples here require external synchronization if shared between threads.
Alignment, hidden metadata and ABI
Sizes and alignment are target-sized nuint values. Xenon requests at least pointer alignment and the allocated value's ABI alignment, checks size arithmetic for overflow, and aligns the returned user address. The callback's requested size includes service metadata and alignment padding; it is not simply sizeof(T). Array requests also include array metadata.
The current allocation header records the raw block address, provider pointer and matching release callback in three target-sized words outside the user object. The release callback receives the raw block address, not the aligned user address or a pointer to the header. Do not inspect or overwrite this compiler-owned metadata.
sizeof(T), user field offsets, array element stride and the C-compatible struct layout are unchanged by explicit allocator use. Existing virtual-layout requirements still apply independently.
Example: ArenaAllocator
allocator ArenaAllocator {
public allocator HeapAllocator* parent;
private byte* buffer;
private nuint capacity;
private nuint used;
public @ArenaAllocator(HeapAllocator* source) { parent = source; }
public ArenaAllocator(nuint capacity) {
this.capacity = capacity;
buffer = cast<byte*>(malloc(capacity, 64));
if (buffer == null) throw 1;
}
public +ArenaAllocator(nuint size, nuint alignment) {
if (alignment > cast<nuint>(64)) return null;
nuint padding = (alignment - used % alignment) % alignment;
if (padding > capacity - used) return null;
nuint start = used + padding;
if (size > capacity - start) return null;
used = start + size;
return cast<void*>(buffer + start);
}
public -ArenaAllocator(void* block) {
// Individual deletion ends object lifetime but retains arena storage.
}
public ~ArenaAllocator() { free(buffer); }
}ArenaAllocator* arena = new(heap) ArenaAllocator(cast<nuint>(4096));
int[] samples = new(arena) int[16];
samples[0] = 42;
delete(samples); // ends lifetimes; arena keeps the occupied bytes
delete(arena); // releases the backing buffer and then its own object
Its context constructor records the HeapAllocator parent before ordinary construction initializes the backing buffer. This bounded bump allocator supports alignment up to 64 bytes. It reserves padding before advancing its cursor and checks capacity without overflowing. Exhaustion or unsupported alignment returns null, which makes the surrounding typed new trap.
Individual releases do not reclaim capacity. Delete every allocated object to perform its cleanup before deleting the arena. This example intentionally has no reset operation: any reset would require all previous allocations to be dead first.
Example: PoolAllocator
allocator PoolAllocator {
public allocator ArenaAllocator* parent;
private byte* buffer;
private void* firstFree;
public int available;
public @PoolAllocator(ArenaAllocator* source) { parent = source; }
public PoolAllocator() {
buffer = cast<byte*>(malloc(32 * 256, 64));
if (buffer == null) throw 1;
for (int i = 0; i < 32; i++) {
void* slot = cast<void*>(buffer + i * 256);
*cast<void**>(slot) = firstFree;
firstFree = slot;
}
available = 32;
}
public +PoolAllocator(nuint size, nuint alignment) {
if (size > cast<nuint>(256) || alignment > cast<nuint>(64) || firstFree == null)
return null;
void* slot = firstFree;
firstFree = *cast<void**>(slot);
available--;
return slot;
}
public -PoolAllocator(void* block) {
*cast<void**>(block) = firstFree;
firstFree = block;
available++;
}
public ~PoolAllocator() { free(buffer); }
}ArenaAllocator* arena = new(heap) ArenaAllocator(cast<nuint>(4096));
PoolAllocator* pool = new(arena) PoolAllocator();
int* value = new(pool) int(9);
delete(value); // makes the slot available for reuse
delete(pool); // destroys the pool, then returns its object to arena
delete(arena); // heap must still be alive
The context constructor records the ArenaAllocator that supplies the pool object. Its ordinary constructor separately obtains the backing buffer with malloc. The pool owns 32 aligned slots of 256 bytes and links free slots through their first pointer-sized word. It supports callback alignments up to 64 bytes, reuses a slot after deletion, and returns null for exhaustion or an oversized request.
The 256-byte limit applies to the entire callback request, including Xenon's service metadata and padding. It is not a promise that a user object with sizeof(T) == 256 will fit. Pool destruction releases its backing buffer; all slot objects must have been destroyed first. Double deletion would corrupt the free list, so normal lifetime obligations still apply.
Constraints and diagnostics
XE0800: an invalid allocator declaration, operator signature, inheritance relationship or incomplete override pair.XE0801: an invalid provider expression or a static allocator type without the required operator contract.XE0802: an allocator value placed where a heap instance is required.XE0803: a missing or incompatible allocation context constructor, including required initialization of nested values.XE0804: invalid allocator field declaration or misplaced modifier.XE0805: access to the incomplete instance during the context phase.XE0806: an assignment to an allocator field outside its owning context constructor.XE0808: the field type must be a direct pointer to an allocator.- Existing access-control diagnostics apply to inaccessible operators and allocation context constructors;
XE2098covers incompatible known allocation/release families.
The compiler does not prove that a callback returned enough valid writable storage, that an arena reset is safe, or that a provider outlives unknown raw-pointer clients. The size, alignment, lifetime and concurrency contracts remain obligations of the allocator implementation and its caller.
Native allocators are available to ordinary code, generic specialization and source-free libraries. They do not introduce implicit provider propagation, placement-new syntax, direct operator invocation, or an automatic per-element ordinary constructor for arrays.