# Operators -- Complete Reference

This page summarizes common operators, their source syntax and numeric behavior.
Contract names in tables describe the conventional operation family; a user
type needs an applicable operator callable. See [operator methods](operators.md)
for complete examples.

## Arithmetic Operators

| Operator       | Syntax  | Contract | Description                                 |
| -------------- | ------- | -------- | ------------------------------------------- |
| Addition       | `a + b` | `Add`   | Element-wise or numeric addition            |
| Subtraction    | `a - b` | `Sub`   | Element-wise or numeric subtraction         |
| Multiplication | `a * b` | `Mul`   | Element-wise or numeric multiplication      |
| Division       | `a / b` | `Div`   | Element-wise or numeric division            |
| Modulo         | `a % b` | `Mod`   | Remainder (integers) or element-wise modulo |
| Negation       | `-a`    | `Neg`   | Unary minus                                 |

```vex
let sum = 10 + 5          // 15
let diff = 10 - 5         // 5
let prod = 10 * 5         // 50
let quot = 10 / 3         // 3 (integer division)
let rem = 10 % 3          // 1
let neg = -42             // -42

// Floating point
let f_div = 10.0 / 3.0    // 3.333...
```

### Scalar numeric operands and borrows

A primitive numeric borrow participates through its referent's value type:
comparing an `&i64` with zero is a signed numeric comparison, not an address
comparison. Numeric widening preserves the source's signedness. Arithmetic
uses its inferred result type; comparisons select a common numeric operand
type before producing `bool`.

Mixed integer operands need a lossless implicit conversion to one operand's
type. Integer/float operations use the existing numeric promotion to the
selected float type. Required compile-time evaluation follows these same
rules; this does not introduce an implicit float-to-integer conversion.

For `a >> b`, the value type of `a` determines arithmetic versus logical
right shift. An unsigned shift count does not turn a signed value unsigned.
Raw pointers are not implicitly loaded by these numeric rules.

### Compound Assignment

| Operator | Equivalent  |
| -------- | ----------- |
| `a += b` | `a = a + b` |
| `a -= b` | `a = a - b` |
| `a *= b` | `a = a * b` |
| `a /= b` | `a = a / b` |
| `a %= b` | `a = a % b` |

```vex
let! x = 10
x += 5    // x = 15
x -= 3    // x = 12
x *= 2    // x = 24
x /= 4    // x = 6
x %= 4    // x = 2
```

## Bitwise Operators

| Operator    | Syntax   | Contract  | Description                |
| ----------- | -------- | --------- | -------------------------- |
| AND         | `a & b`  | `BitAnd` | Bitwise AND                |
| OR          | `a \| b` | `BitOr`  | Bitwise OR                 |
| XOR         | `a ^ b`  | `BitXor` | Bitwise XOR                |
| NOT         | `~a`     | `BitNot` | Bitwise complement (unary) |
| Left Shift  | `a << b` | `Shl`    | Shift left by b bits       |
| Right Shift | `a >> b` | `Shr`    | Shift right by b bits      |

```vex
let a: u8 = 0b1100_1010
let b: u8 = 0b1010_0110

let and_val = a & b     // 0b1000_0010
let or_val = a | b      // 0b1110_1110
let xor_val = a ^ b     // 0b0110_1100
let not_a = ~a          // 0b0011_0101

let shifted = a << 2    // 0b0010_1000 (left shift)
let right = a >> 3      // 0b0001_1001 (right shift)
```

### Compound Bitwise Assignment

| Operator  | Equivalent   |
| --------- | ------------ |
| `a &= b`  | `a = a & b`  |
| `a \|= b` | `a = a \| b` |
| `a ^= b`  | `a = a ^ b`  |
| `a <<= b` | `a = a << b` |
| `a >>= b` | `a = a >> b` |

## Comparison Operators

| Operator         | Syntax   | Contract | Description                  |
| ---------------- | -------- | -------- | ---------------------------- |
| Equal            | `a == b` | `Eq`    | Returns true if equal        |
| Not Equal        | `a != b` | `Eq`    | Returns true if not equal    |
| Less Than        | `a < b`  | `Ord`   | Returns true if a is less    |
| Greater Than     | `a > b`  | `Ord`   | Returns true if a is greater |
| Less or Equal    | `a <= b` | `Ord`   | Returns true if a <= b       |
| Greater or Equal | `a >= b` | `Ord`   | Returns true if a >= b       |

```vex
let same = (5 == 5)       // true
let diff = (5 != 3)       // true
let less = (3 < 5)        // true
let greater = (10 > 5)    // true
let le = (5 <= 5)         // true
let ge = (10 >= 5)        // true
```

## Logical Operators

| Operator | Syntax     | Contract | Description               |
| -------- | ---------- | -------- | ------------------------- |
| AND      | `a && b`   | —        | Short-circuit logical AND |
| OR       | `a \|\| b` | —        | Short-circuit logical OR  |
| NOT      | `!a`       | `Not`   | Logical negation          |

```vex
let t = true
let f = false

let and_val = t && f       // false (short-circuit: f not evaluated if t were false)
let or_val = t || f        // true
let not_val = !t           // false

// With &&, the right-hand expression is evaluated only if the left is true.
```

Short-circuit evaluation does not make raw pointer access safe: a non-null address may still be dangling, misaligned, uninitialized, or out of bounds. Raw reads need an unsafe context and a valid live pointee. See [Memory Safety](../memory/safety.md).

`&&` and `||` also accept `&bool` operands: they read the referenced boolean,
not whether its address is non-null. Mixing `bool` and `&bool` preserves the
same left-to-right, once-only evaluation and short-circuit rules, including
inside `#const`:

```vex
const fn both(left: &bool, right: &bool): bool {
    return left && right;
}

let enabled = false;
let ready = true;
let result = both(&enabled, &ready); // false
```

Binary operators automatically dereference one reference layer. For nested
references, dereference the outer layer explicitly (for example, `*left &&
*right` for `& &bool` parameters). This does not grant logical operators an
implicit raw-pointer dereference or change unary `!` rules; use `!*reference`
to negate a referenced boolean.

## Indexing Operator

| Operator | Syntax | Contract | Description             |
| -------- | ------ | -------- | ----------------------- |
| Index    | `a[i]` | `Index` | Element access by index |

```vex
let arr = [10, 20, 30]
let second = arr[1]       // 20

let map = Map.new<string, i32>()
map["key"] = 42           // indexed assignment; distinct from a read
let val = map["key"]      // 42
```

## Range Operators

| Operator        | Syntax  | Description                         |
| --------------- | ------- | ----------------------------------- |
| Exclusive Range | `a..b`  | From a (inclusive) to b (exclusive) |
| Inclusive Range | `a..=b` | From a (inclusive) to b (inclusive) |
| From            | `a..`   | From a to infinity                  |
| To Exclusive    | `..b`   | From start to b (exclusive)         |
| To Inclusive    | `..=b`  | From start to b (inclusive)         |
| Full Range      | `..`    | Everything                          |

```vex
for i in 0..5 { }          // 0, 1, 2, 3, 4
for i in 0..=5 { }         // 0, 1, 2, 3, 4, 5

let slice = data[1..4]     // elements at indices 1, 2, 3
let with_end = data[1..=4] // elements at indices 1, 2, 3, 4
let from_start = data[..3] // elements at indices 0, 1, 2
let to_end = data[2..]     // elements from index 2 to end
```

## Reference and Pointer Operators

| Operator         | Syntax   | Description                                    |
| ---------------- | -------- | ---------------------------------------------- |
| Immutable Borrow | `&expr`  | Creates an immutable reference                 |
| Mutable Borrow   | `&expr!` | Creates a mutable reference                    |
| Dereference      | `*expr`  | Dereferences a reference or pointer; raw-pointer access requires an unsafe context |

```vex [references.vx]
fn observe(counter: &i32!): bool {
    *counter = *counter + 1;
    return true;
}
fn main(): i32 {
    let x = 42;
    let ref_x: &i32 = &x;
    let! y = 10;
    let mut_ref: &i32! = &y!;
    *mut_ref = *mut_ref + 5;
    let! calls = 0;
    let result = false && observe(&calls!);
    if result || calls != 0 { return 1; }
    $println(*ref_x);
    $println(y);
    $println(calls);
    return 0;
}
```

Expected output is `42`, `15`, and `0`, followed by exit status 0. The zero demonstrates that the right side of `false && ...` was not called.

## Error Handling Operators

| Operator      | Syntax             | Description                                                                                |
| ------------- | ------------------ | ------------------------------------------------------------------------------------------ |
| Null-coalesce | `expr ?? fallback` | If `expr` is `None`/`Err`, evaluates and returns `fallback`; otherwise returns the contained value |
| Rescue        | `expr !> fallback` | If `expr` is `None`/`Err`, returns `fallback` (lazy with `\|\|`, error-aware with `\|e\|`) |
| Try           | `expr?`            | Propagates `None`/`Err` from the enclosing function                                        |

### Null-Coalescing Operator (`??`)

The right-hand expression is evaluated only if the left side is `None` or
`Err`. A normal `.or(fallback())` method call evaluates its argument before
calling the method; `.orElse` takes a callback instead.

```vex
let opt: Option<i32> = None
let val = opt ?? 0                     // 0

let res: Result<i32, string> = Err("fail")
let val = res ?? 42                    // 42

// expensiveFunction() runs only if opt is None:
let val = opt ?? expensiveFunction()
```

For a Result fallback that needs the error value, use the error-aware `!>`
closure or `orElse`; `??` discards the error.

### Rescue Operator (`!>`)

The `!>` operator extracts a value from `Option<T>` or `Result<T,E>`, providing a fallback on failure. The error value is passed to the fallback closure when recovering from `Err`.

#### Three Forms

```vex
// 1. Direct value fallback (error DISCARDED):
let val = result !> 0

// 2. Lazy closure, error DISCARDED:
let val = result !> || computeDefault()

// 3. Lazy closure, error PASSED to closure:
let val = result !> |err| {
    $eprintln(f"Recovering from: {err}")
    fallbackFromError(err)
}
```

#### On `Result<T,E>`

```vex
let res: Result<i32, i32> = Err(404)

// Error passed to closure -- |e| receives the 404
let val = res !> |err_code| {
    $println(f"Failed with code: {err_code}")
    err_code  // use error as fallback value
}
// val = 404

// Ok values pass through without calling closure
let ok: Result<i32, i32> = Ok(42)
let val = ok !> |e| {
    $println("Never called")
    0
}
// val = 42, closure not evaluated
```

#### On `Option<T>`

```vex
let opt: Option<i32> = None

// Option uses || form (no error value to pass):
let val = opt !> || {
    $println("Was None, computing default")
    99
}
// val = 99
```

The fallback is **only evaluated when the value is `None`/`Err`**. This is the idiomatic Vex alternative to `.unwrap()` (which does not exist in Vex).

### Try Operator (`?`)

Propagates errors from `Option` or `Result`:

```vex
fn process(): Result<Data, Error> {
    let file = File.open("data.txt")?   // propagates Err
    let parsed = parse(file.readAll()?)?  // propagates Err
    return Ok(parsed)
}
```

## Channel Operators

| Operator | Syntax        | Description                            |
| -------- | ------------- | -------------------------------------- |
| Send     | `ch <- value` | Moves a value into the channel; blocks while full |
| Receive  | `<-ch`        | Blocks for `T`; returns zero `T` when closed and drained |

```vex
let! ch = Channel.new<i32>(10)

ch <- 42                      // send value
let received = <-ch            // receive value (blocking)

// Select-like pattern with try operations
if let Some(val) = ch.tryRecv() {
    process(val)
}
```

Use `recv()`, `recvResult()`, or `tryRecv()` instead of `<-ch` when the program must distinguish a closed or not-ready channel from a valid zero value.

## Ternary Operator

| Operator | Syntax         | Description                       |
| -------- | -------------- | --------------------------------- |
| Ternary  | `cond ? a : b` | Returns a if cond is true, else b |

```vex
let max = a > b ? a : b
let status = code == 200 ? "OK" : "ERROR"

// Nested ternaries (use sparingly for readability)
let category = score >= 90 ? "A" :
               score >= 80 ? "B" :
               score >= 70 ? "C" : "F"
```

## Type Operators

| Operator  | Syntax         | Description                     |
| --------- | -------------- | ------------------------------- |
| Type Cast | `expr as Type` | Safe or unsafe type conversion  |
| Type Test | (not in Vex)   | Use `match` or `if let` instead |

```vex
let x: i32 = 42
let y: f64 = x as f64      // safe: widening cast 42.0
let z: u8 = 300 as u8       // safe: truncating cast (wraps)

let ptr_val: Ptr<Opaque> = Ptr.null<Opaque>()
let addr: usize = ptr_val.addr()  // address-sized integer
```

## SIMD-Specific Operators

Availability depends on element type, shape and lowering path. Fixed arrays
have dedicated lowering; they do not all become owned tensors. See
[SIMD operations](../simd/simd-operations.md) for numerical and backend limits.

### SIMD Arithmetic

| Operator            | Syntax    | Description                                  |
| ------------------- | --------- | -------------------------------------------- |
| Saturating Add      | `a +\| b` | Addition with saturation (clamp on overflow) |
| Saturating Sub      | `a -\| b` | Subtraction with saturation                  |
| Saturating Mul      | `a *\| b` | Multiplication with saturation               |
| Min                 | `a <? b`  | Element-wise minimum                         |
| Max                 | `a >? b`  | Element-wise maximum                         |
| Multiply-add token | `a *+ b` | Parser token; not a complete three-operand FMA recipe |
| Carry-less Multiply | `a *^ b`  | CLMUL (cryptographic)                        |

```vex
let a = [100u8, 200u8, 50u8]
let b = [100u8, 100u8, 200u8]

let sat_add = a +| b     // [200, 255, 250] -- 200+100=300 clamped to 255
let sat_sub = a -| b     // [0, 100, 0]      -- 50-200=0 (clamped)
let min_vals = a <? b    // [100, 100, 50]
let max_vals = a >? b    // [100, 200, 200]
```

### SIMD Rotation

| Operator     | Syntax    | Description                 |
| ------------ | --------- | --------------------------- |
| Rotate Left  | `a <<< b` | Circular left bit rotation  |
| Rotate Right | `a >>> b` | Circular right bit rotation |

```vex
let x: u8 = 0b1000_0001
let rot_left = x <<< 1   // 0b0000_0011 (bit 7 wraps to bit 0)
let rot_right = x >>> 1  // 0b1100_0000 (bit 0 wraps to bit 7)
```

### Horizontal Reductions (Prefix Operators)

Reductions collapse lanes to a scalar. Use the prefix reduction forms:

| Operator | Syntax | Description |
| --- | --- | --- |
| Sum | `<+ values` | Add lanes |
| Product | `<* values` | Multiply lanes |
| AND | `<& values` | Bitwise/logical AND |
| OR | `<\|> values` | Bitwise/logical OR |
| Minimum | `<?\| values` | Minimum lane |
| Maximum | `>?\| values` | Maximum lane |

```vex
let values: [i32; 4] = [1, 2, 3, 4];
let total = <+ values;   // 10
let product = <* values; // 24
```

Floating-point accumulation order, empty inputs and special values need the
operation's actual contract. A parallel reduction need not reproduce the low
bits of a sequential loop.

### Matrix Operations

| Operator | Syntax | Intended operation |
| --- | --- | --- |
| Matrix multiply | `a <*> b` | Multiply compatible matrix shapes |
| Matrix power | `a <^> n` | Repeated square-matrix multiplication |
| Linear solve | `a <\> b` | Solve a linear system on a supporting route |

A flat `[f64; 4]` does not declare a 2×2 matrix. The operation requires shape
information or an explicit overload that defines it. Parser recognition does
not prove support for arbitrary rank, dtype or backend. Use the
[shape and matrix guidance](../simd/simd-operations.md#matrix-operations)
before relying on these forms.

## Operator Precedence

The table follows the parser's infix binding powers, strongest first. Postfix
call/index/member access, prefix unary operations and casts are handled
separately; parenthesize mixed forms when the intended grouping is not obvious.

| Group | Operators |
| --- | --- |
| Cast | `as` |
| Powers | `**` (right-associative), then `<^>` |
| Multiplicative | `*`, `/`, `%`, `*\|`, `*^`, `*+` |
| Additive | `+`, `-`, `+\|`, `-\|` |
| Concatenation | `++` |
| Shift/rotate | `<<`, `>>`, `<<<`, `>>>` |
| Bitwise AND, XOR, OR | `&`, then `^`, then `\|` |
| Coalescing | `??` |
| Relational/min/max | `<`, `<=`, `>`, `>=`, `<?`, `>?` |
| Equality | `==`, `!=` |
| Logical AND, OR | `&&`, then `\|\|` |
| Matrix multiply/solve | `<*>`, `<\>` |
| Ranges | `..`, `..=` |
| Pipelines | `\|>`, `<\|` |
| Assignment/send | `=`, compound assignment, `<-` (right-associative) |
| Rescue | `!>` |
| Ternary | `condition ? yes : no` |

For example, `x & 1 == 1` groups as `(x & 1) == 1`, and `a ?? b + 1`
groups as `a ?? (b + 1)`. Prefix reduction operands should be parenthesized
when reducing an expression: `<+ (a * b)`.

## Best Practices

1. Use parentheses to clarify precedence in complex expressions, even when you know the rules.
2. Prefer `if`/`else` over nested ternary operators for readability.
3. Use compound assignment operators (`+=`, `*=`, etc.) for concise mutation.
4. For SIMD operations, inspect the emitted route when vectorization matters.
5. When overloading operators, define domain-appropriate laws; concatenation is a useful noncommutative `+`.
6. Implement `Eq` and `Ord` as a pair when your type has a natural ordering.
