Documentation
Classes
Classes
Fields start with their names and accept inline declaration modifiers. Methods
keep fn name(...), with an optional group after ->:
fn calculate(value: i32) -> public static :: i32:. The group modifies the
method declaration, not the return type. Parameter var/const modifiers
remain independent.
Class Syntax
class Counter(BaseCounter, Audited):
version: public static const :: int32 = 1
value: int32 = 0
internal: private :: int32 = 1
fn get(self) -> int32:
return self.value
fn process(self, x: int32) -> protected :: int32:
return x + 1
Optional class-level annotations use the same surface form:
@[public, abstract]
class Shape:
fn area(self) -> public abstract :: float64
Template methods retain @<...> prefixes on their own lines before fn. Method
modifiers move into the return tail:
class Math:
@<T: i32 | f64>
fn identity(value: T) -> public static :: T:
return value
Modifier Rules
Field modifiers are whitespace-separated in name: modifiers :: type; method
modifiers use fn name(...) -> modifiers :: type. Only classes retain
comma-separated @[...] annotation lists. Method modifier annotations were
removed rather than retained as a second spelling. Empty, duplicate,
conflicting, floating, and invalid-target modifiers are rejected.
Visibility is public, private, or protected. Fields support static and
var/const; methods retain static, abstract, and extern. Neither var
nor const modifies a method name. Parameters use name: [var|const ::] type
inside the existing method signature. The implicit self receiver is unchanged.
Class const fields require declaration-site initialization, not deferred
assignment in __init__.
override, virtual, final, sealed, readonly, and inline remain
unsupported. See the
declaration contract for binding
stability, inference, and removed annotation spellings.
Defaults
Defaults are applied during parsing and normalization, not written back as implicit modifier groups.
- Fields default to
publicvisibility andvarbinding policy. - Methods default to
publicvisibility. - Only explicitly written modifiers are preserved as explicit metadata on the emitted IRx/ASTx nodes.
For example, these declarations are equivalent semantically:
value: int32 = 0
fn get(self) -> int32:
return self.value
value: public var :: int32 = 0
fn get(self) -> public :: int32:
return self.value
Construction And Typed Class Values
Declared classes can be used in type annotations and construction expressions.
Counter() remains valid when no required initializer parameters are declared.
An optional __init__ hook adds positional arguments, constructor keywords, and
literal defaults; an optional __del__ hook runs at final release.
class Counter:
version: public static const :: int32 = 3
fn get(self) -> int32:
return 1
class CounterFactory:
fn make() -> public static :: Counter:
return Counter()
fn take_counter(counter: Counter) -> int32:
return counter.get()
fn main() -> int32:
counter: Counter = CounterFactory.make()
return take_counter(counter) + Counter.version
This surface syntax maps directly onto IRx-owned class nodes:
Counterin annotations becomesastx.ClassTypeCounter(...)becomesastx.ClassConstructwith ordered arguments/keywordsCounter.versionbecomesastx.StaticFieldAccessCounterFactory.make()becomesastx.StaticMethodCall
Lifecycle Hooks
class Counter:
value: i32 = 0
fn __init__(self, value: i32 = 1) -> none:
self.value = value
return none
fn __del__(self) -> none:
print(self.value)
return none
fn main() -> i32:
counter: Counter = Counter(value=7)
alias: Counter = counter
counter = Counter(3)
assert alias.value == 7
return 0
The two variables initially refer to the same object; copying a reference does
not copy fields. Reassignment releases only the replaced reference. Locals,
discarded temporaries, loop-body locals, and early returns release their
references on ordinary lexical exits. Final release calls __del__ exactly
once, then drops owned fields and frees storage. Returns preserve object
identity and can outlive the creating function. Calls borrow objects; evaluated
class arguments and receivers are pinned before later arguments can replace
fields. Rebinding a class parameter replaces its independent local reference,
not the caller's binding.
Hook rules:
- Double-underscore (dunder) method names are reserved for language protocols.
The supported lifecycle names are
__init__and__del__; unknown names such as__inti__or__str__are semantic errors, including on static methods. Lifecycle hooks cannot be declared as fields. Plaininitanddeinitare ordinary method names, not compatibility aliases.withuses ordinary__enter__(self)calls (including defaults) and__exit__(self, success: bool) -> none. The Boolean reports body completion, not Python exception arguments; exit cannot suppress failures. See checked resource scopes and the IRx contract. - Dunders identify language-defined behavior, not private visibility or inheritance from a universal builtin superclass. Implementations are written by users; normal visibility annotations still apply.
__init__(self, ...) -> noneand__del__(self) -> noneare compiler entry points, not ordinary callable methods. Explicit calls are rejected.- Lifecycle hooks cannot be static, abstract, external, overloaded, templated, or variadic. Constructor defaults are existing scalar/string literals, not resource values.
- Constructor arguments bind by parameter name, excluding
self. Unknown, duplicate, missing, excessive, and incompatible arguments are errors. Supplied expressions evaluate once in source order, including keywords. - A class without its own
__init__has a zero-argument constructor. Base hooks run with their defaults; a base requiring arguments is rejected when constructing the derived class. Explicit base-argument forwarding is deferred. - Shared ancestors initialize once in canonical base-first storage order. Each
phase initializes its declared fields before calling its own
__init__. Final release reverses those phases, calling each__del__before dropping its fields in reverse declaration order. This also works through a base-typed reference; non-prefix multiple-inheritance views locate concrete storage. - Inside lifecycle hooks,
selfis only a field-access receiver: it cannot be aliased, returned, passed elsewhere, or used to invoke an ordinary self method. This prevents escape during construction and resurrection during destruction.
These names are familiar from Python, but Arx keeps its own lifecycle contract:
normal final-reference release synchronously runs cleanup, base phases chain
automatically, and direct hook calls and resurrection are forbidden. This does
not add Python's garbage collector, super() chaining, __new__, or unwinding
after fatal errors. Ordinary operations such as close() remain callable and
are separate from object destruction.
Ordinary instance and static methods also accept named arguments. An instance receiver is implicit; it cannot be supplied as a keyword. Keywords bind against the statically selected declaration, including through inheritance and dynamic dispatch. Values evaluate in source order, then omitted defaults in declaration order. See Functions. Direct lifecycle-hook calls remain forbidden.
Iteration Protocol
An iterable class implements a public instance method __iter__(self) that
returns a cursor class. The cursor implements __next__(self) -> T, where T
is the concrete item type. An iterator that owns its current position usually
returns self from its own __iter__. A reusable collection can return a fresh
cursor on every call.
```
title: Countdown iterator
```
class Countdown:
remaining: i32 = 3
fn __iter__(self) -> Countdown:
return self
fn __next__(self) -> i32:
if self.remaining == 0:
raise StopIteration()
self.remaining = self.remaining - 1
return self.remaining
fn sum_countdown() -> i32:
total: i32 = 0
for value in Countdown():
total = total + value
return total
for acquires the cursor once. It stops when advancement raises the builtin
StopIteration or a subclass. A yielded null is an item. Other exceptions from
advancement, and exceptions from acquisition or the loop body, propagate. A loop
releases its cursor on every exit. Breaking out of a loop leaves a cursor held
by the caller at its current position.
Use iter(value) and next(cursor) to call the corresponding hooks explicitly.
next exposes StopIteration to the caller. Both methods take only self. To
copy numeric items into a list, call list(value, max_items=N).
Use iterable[T] and iterator[T] as structural template bounds when a
function accepts multiple concrete implementations. Item types match exactly.
iterable[T] accepts class iterables and builtin values such as integer ranges
and lists. iterator[T] also requires the value itself to implement
advancement. Template calls specialize on the concrete type.
@<I: iterable[i32]>
fn sum_items(values: I) -> i32:
total: i32 = 0
for value in values:
total = total + value
return total
Copying Instances
Import copy from stdlib.memory to ask a class to duplicate itself. A copy
hook is an instance method __copy__(self) that returns its declaring class and
takes no additional arguments. The method chooses which fields to duplicate or
share. Normal visibility and method dispatch apply.
A subclass can override the hook with its own return type. A call through a base-typed reference dispatches to the override and keeps the base static result type. Copying a subclass-typed value requires a hook that returns that subclass. A missing hook is a compile-time error.
Weak References
Import weak, downgrade, and upgrade from stdlib.memory. A weak[T]
handle can be stored in a class field, copied, passed, or returned. It keeps the
lifetime record available while the last strong reference destroys the payload.
A weak field can close a back-reference without forming a strong ownership
cycle. Weak handles are thread-confined.
import (weak, downgrade, upgrade) from stdlib.memory
class Counter:
value: i32 = 42
fn read(observer: weak[Counter]) -> i32:
current: Counter | none = upgrade(observer)
if is_null(current):
return 0
return cast(current, Counter).value
fn main() -> i32:
counter: Counter = Counter()
observer: weak[Counter] = downgrade(counter)
assert read(observer) == 42
return 0
An empty or expired weak handle upgrades to none. A successful upgrade holds a
strong reference until replaced or released. Use is_null to check the optional
result. cast(current, Counter) checks that the result is live and raises
RuntimeError for none.
Owned Fields And Boundaries
Scalar fields keep their existing behavior. Instance strings own independent
heap copies (or move fresh owned results); replacing a string field safely
releases its previous allocation. String-field reads produce owned snapshots, so
evaluated arguments, local copies, and returns survive later replacement of that
field. Acyclic class-reference fields hold strong references and default to
empty; dereferencing an empty class value reports a checked runtime error rather
than using a null pointer. Field declarations may refer to already initialized
fields through self.
A named receiver's const numeric or Boolean instance field can be borrowed
with &. Use a local alias or pass the borrow to a read-only scalar parameter.
The receiver remains live for the loan. Assigning to its binding requires ending
or retargeting the local alias first. Other strong handles can share the
instance and read its immutable fields.
class Tag:
code: const :: i32 = 7
fn read(code: &i32) -> i32:
return code
fn example() -> i32:
tag: Tag = Tag()
return read(&tag.code)
A public File (or lowercase file) field holds an ordinary class reference.
It may be initialized with File(...), open(...), or another File reference,
and may be replaced or shared. Empty fields use the normal checked class
reference behavior. The builtin File class itself owns one private native handle
initialized once by its compiler-provided constructor; users cannot extract or
replace that handle. Final File release invokes normal owned-field cleanup. See
the
owned-file example
and file API. File subclassing and reopening are deferred.
This reference-counted subset is synchronous and non-atomic. Cyclic field-type graphs are rejected conservatively, including edges through assignable subtypes, even if a particular program would not create a cycle. Class values in containers/unions/struct fields, owned globals/statics, generator capture, list/Arrow/resource aggregate fields, and an external class ownership ABI are not supported. There is no garbage collector, weak reference, resurrection, explicit deletion, or thread-safe reference counting.
Allocation and empty-reference failures use ARX-RUNTIME-CLASS-001. Checked
compiler-local construction failures release initialized fields, run only
completed base-phase destructors, and free partial storage. Native field-release
errors preserve the first error while continuing remaining field releases and
freeing the object. Generated calls propagate exceptions through those cleanup
edges; an implicit destructor failure preserves an existing primary exception.
Unrecoverable native failures do not promise cleanup. See the
exception boundary.
IRx Alignment
Arx now emits IRx/ASTx nodes directly instead of maintaining a separate Arx class AST layer. This is a hard repository boundary: new AST node types or new lowering behavior for class features belong in IRx/ASTx, not in Arx.
classdeclarations lower intoastx.ClassDefStmt.- Base classes become
astx.ClassTypeentries. - Fields become
astx.VariableDeclarationwith visibility and mutability set directly, plusis_staticwhen present. - Methods become
astx.FunctionDefplusastx.FunctionPrototype, with visibility set directly andis_static,is_abstract, oris_externattached to the prototype when written. - Instance member syntax like
self.valuelowers intoastx.FieldAccess.
This keeps Arx syntax aligned with the IRx semantic boundary while preserving explicit modifier intent on the same nodes that later lowering consumes.
A runtime-schema dataframe[...] method parameter also accepts a statically
typed DataFrame, without converting its data. An exact static-schema overload
wins if present. This permits CSVStream.write(frame) and
ParquetStream.write(frame) for both kinds of frame; it does not permit
implicit narrowing or general numeric conversion-ranked overloads.
Method overloads can share value parameters when their template bounds differ. A call with explicit type arguments considers only template overloads whose bounds accept those types. Calls without type arguments infer template types from the value arguments and prefer an ordinary method when equally good matches exist. Multiple eligible overloads of the same rank are ambiguous.