Contracts
Contracts define shared behavior in Vex. They are the language mechanism behind reusable capabilities such as display, cloning, dropping, iterators, and operator overloading.
Core syntax
Vex uses contract, not trait or interface.
contract Describe {
describe(): string;
}
contract Cursor {
type Item;
next()!: Option<Self.Item>;
}Current repo examples most commonly use this signature style inside contracts: method declarations without a receiver body.
Implementing a contract
Attach the contract to the type with colon syntax and then define normal receiver methods.
contract Describe {
describe(): string;
}
struct Point: Describe {
public:
x: i32,
y: i32,
}
fn (self: &Point) describe(): string {
return "Point(" + self.x.toString() + "," + self.y.toString() + ")";
}Rust-style impl Contract for Type is not Vex syntax.
Implicit Receivers and Mutability
An instance requirement has an implicit receiver; do not add self: &Self as an ordinary parameter. A static fn requirement has no receiver, as shown below.
convert(val: T): U;defines a method taking an Immutable Reference (self: &Self).convert(val: T)!: U;defines a method taking a Mutable Reference (self: &Self!). The!indicates state mutation.
contract Incrementable {
// Immutable read method
count(): i32;
// Mutable write method (note the '!' after parameters)
increment()!;
}If you accidentally write self: &Self inside a contract (e.g. convert(self: &Self)), the compiler will emit a warning correcting this habit.
Generic contracts and defaults
Contracts can take type parameters, including defaults such as Self.
contract Combine<Rhs = Self> {
combine(other: Rhs): Self;
}The default makes Combine mean Combine<Self>. This custom contract is separate from the prelude arithmetic contracts.
Static requirements and generic type designators
Use static fn when the operation belongs to the implementing type rather than a borrowed instance. A generic bound may invoke the requirement through its type parameter; the compiler resolves the exact binder and contract member at compile time.
contract From<T> {
static fn fromValue(value: T): Self;
}
fn convert<T, U: From<T>>(value: T): U {
return U.fromValue(value);
}This dispatch is monomorphized. It does not create a runtime contract object or perform method-name lookup.
A static requirement may also provide a default body. The body is compiled once per exact implementing type and contract specialization. Self denotes that type, but no instance receiver or vtable is introduced.
Associated types
Contracts can expose associated types. This complete example declares conformance on Counter, provides a mutable receiver implementation, and calls it through the generic bound T: NextInt:
contract NextInt {
type Item;
next()!: Option<Self.Item>;
}
struct Counter: NextInt {
type Item = i32;
value: i32,
}
fn (self: &Counter!) next(): Option<i32> {
self.value = self.value + 1;
return Some(self.value);
}
fn advance<T: NextInt>(item: &T!): Option<T.Item> {
return item.next();
}
fn main(): i32 {
let! counter = Counter { value: 0 };
$println(advance(&counter) ?? -1);
$println(advance(&counter) ?? -1);
return 0;
}vex run contract-counter.vx prints 1 and 2 on separate lines. The associated type T.Item is resolved through the bound. Each implementation must provide the required methods with matching parameter and result types. Declare receiver mutability consistently in the requirement and implementation: this counter advances its state, so next!() requires mutable access.
A domain contract describes behavior; a compiler-recognized marker such as Copy can carry additional language semantics; policies describe field metadata and are a separate mechanism. A user-defined same-named contract does not automatically gain a built-in marker's compiler role.
Builtin contracts
Many important contracts live in the prelude and are available without an import. $ prefixes runtime intrinsics such as $println; it is not part of a contract name.
Copy
Copy values copy on assignment instead of moving.
let x = 42;
let y = x;
$println(x);Typical Copy values include primitive numbers, bool, char, str, and raw pointer-like values.
Clone
Clone provides explicit duplication.
struct Config: Clone {
public:
name: string,
value: i32,
}
fn (self: &Config) clone(): Config {
return Config { name: self.name.clone(), value: self.value };
}Drop
Drop runs cleanup when a value leaves scope.
struct Trace: Drop {
public:
label: string,
}
fn (self: &Trace!) drop() {
$println("leaving " + self.label);
}This example logs destruction. A real resource owner must also release its resource using the owning API; printing a message does not close a file.
Display and Debug
These support human-readable and debug-oriented text conversion.
struct Color: Display, Debug {
public:
r: u8,
g: u8,
b: u8,
}
fn (self: &Color) toString(): string {
return "rgb(" + self.r.toString() + "," + self.g.toString() + "," + self.b.toString() + ")";
}
fn (self: &Color) debug(): string {
return "Color{r:" + self.r.toString() + ",g:" + self.g.toString() + ",b:" + self.b.toString() + "}";
}These contracts integrate directly with formatting:
let color = Color { r: 32, g: 64, b: 255 };
$println("color={} details={:?}", color, color);
let label = $format("selected: {}", color);{} selects the exact Display.toString implementation. {:?} and {:#?} select the exact Debug.debug implementation. Resolution is based on the trusted contract/member identity, not a type or method name, so an unrelated same-spelled contract cannot intercept formatting. Both methods are borrowed receiver calls and must return string; their temporary result is released after formatting consumes it.
Operator contracts
Operator behavior is expressed with contracts and op... methods.
contract Add {
op+(other: Self): Self;
}
struct Vec2: Add {
public:
x: i32,
y: i32,
}
fn (self: &Vec2) op+(other: Vec2): Vec2 {
return Vec2 { x: self.x + other.x, y: self.y + other.y };
}The prelude arithmetic Add contract takes Self as its right operand. Indexing uses Index<Idx> with an associated Output type, while mutable indexing has its own IndexMut<Idx, Val> contract. Consult the contract reference for the exact signatures.
Guidance
- Use plain contracts for domain behavior.
- Use
Drop,Clone, andDisplaywhen you want standard language integration. - Prefer simple method contracts first; add associated types or generic defaults when the API really needs them.
- Keep examples aligned with real syntax from the repo:
struct Type: Contract {}plus receiver methods.