Docs · Language
Operators
Every operator in Vyi except &&, ||, and ! is a method call: a + b calls
a.@add(b), and xs[i] calls xs.@index(i). The compiler provides these
methods for the primitive types, and you write them as ordinary methods for your
own types. This page lists the precedence levels, the method each operator
calls, compound assignment, and what the built-in operators do. Guide
13, Operators and overloading
introduces them.
Precedence
From loosest to tightest. Binary operators of one level group from the left.
| Level | Operators |
|---|---|
| 1 | .. ... (ranges) |
| 2 | || |
| 3 | && |
| 4 | | |
| 5 | ^ |
| 6 | & |
| 7 | == != |
| 8 | < > <= >= |
| 9 | << >> |
| 10 | + - +% -% |
| 11 | * / % *% |
| 12 | prefix - ! * (dereference) & (address of) |
| 13 | .field, [index], (call) |
10 - 2 - 3is(10 - 2) - 3.- A binary operator stays on the line of its left operand: a newline before the operator ends the expression (lexical).
- Ranges don't chain:
1..2..3is a parse error. - Comparisons don't chain:
a < b < ccompares aboolwithc, a type error. try,known,catch, andshapeofare covered in expressions.
import { println } from "@fmt"
fn main() !u8 {
println(2 + 3 * 4) // prints 14
println((2 + 3) * 4) // prints 20
println(10 - 2 - 3) // prints 5
println(1 << 2 + 1) // prints 8
return Ok(0)
}&, ^, and | bind more loosely than == and !=, as in C. A mask test
needs parentheses; without them the comparison runs first:
fn main() !u8 {
con flags = 6
con hasFour = flags & 4 != 0 // error: this operand of `&` has type bool, where i32 is expected
return Ok(0)
}Write (flags & 4) != 0.
Binary operators and their methods
The left operand is the receiver and the right operand is the one argument.
| Operator | Method | Operator | Method |
|---|---|---|---|
+ | @add | == | @eq |
- | @sub | != | @eq, result negated |
* | @mul | < | @lt |
/ | @div | > | @lt, operands swapped |
% | @rem | <= | @le |
+% | @addWrap | >= | @le, operands swapped |
-% | @subWrap | & | @band |
*% | @mulWrap | | | @bor |
<< | @shl | ^ | @bxor |
>> | @shr |
a != bis!a.@eq(b),a > bisb.@lt(a), anda >= bisb.@le(a). There is no@neq,@gt, or@ge.&&and||are not methods. They takebooloperands and evaluate the right one only when the left doesn't decide the result.- Prefix
&takes an address and infix&calls@band. In a type,|builds a union.
The operator call is typed exactly as the written call a.@op(b): the right
operand is checked against the method's parameter. So the operands may have
different types when the method's parameter says so:
import { println } from "@fmt"
struct Money { cents: i32 }
fn (m: Money) @mul(count: i32) Money {
return Money{ cents: m.cents * count }
}
fn main() !u8 {
con ticket = Money{ cents: 1200 }
println((ticket * 3).cents) // prints 3600
println(ticket.@mul(3).cents) // prints 3600
return Ok(0)
}The built-in operators on the number types take an operand of the receiver's own type, so two different number types never meet in an operator. Convert one side:
fn main() !u8 {
con count: i32 = 3
con total: i64 = 1000
con sum = count + total // error: this operand of `+` has type i64, where i32 is expected
return Ok(0)
}An operator with no method is a compile error, never a default:
struct Point { x: i32, y: i32 }
fn main() !u8 {
con a = Point{ x: 1, y: 2 }
con b = a + a // error: operator `+` is not implemented for type Point
return Ok(0)
}The message goes on to name the method that would make it work.
Unary operators
| Operator | Meaning | Operand |
|---|---|---|
-x | negation | built in for the integer and float types; x.@neg() for any other type |
!x | boolean not | bool only; not a method |
&x | address of | a place; gives *mut T or *con T (memory model) |
*p | dereference | a pointer |
@neg takes no argument and may return any type. A type without one has no
-. ! takes only a bool, so !1 is an error
(`this operand of ! has type i32, where bool is expected`).
Prefix operators bind more tightly than every binary operator and more loosely
than the postfix chain: -p.x is -(p.x), and *p + 1 is (*p) + 1.
Indexing and slicing
| Written | Calls |
|---|---|
xs[i] | xs.@index(i) |
xs[i] = v | xs.@setIndex(i, v) |
xs[a..b], xs[a...b] | xs.@slice(r), with r the Range a..b or a...b |
xs[..b], xs[a..], xs[..] | xs.@slice(r), with the missing start 0 and the missing end xs.length() |
- A subscript is typed exactly as the written call. The index, and the value in
xs[i] = v, are checked against the method's parameters, and a literal takes the parameter's type:xs[3000000000]is fine when@indextakes ani64. - With several
@indexoverloads, the index's type picks one, as it does forxs.@index(i). @setIndexchanges the value, so it takes a*mutreceiver.xs[i] += vreads through@indexand writes through@setIndex.- Fixed arrays, array pointers, and C pointers have built-in indexing and slicing, with an
i32index (expressions, indexing).
import { println } from "@fmt"
struct Scores { points: [4]i32 }
fn (s: Scores) @index(player: i32) i32 { return s.points[player] }
fn (s: *mut Scores) @setIndex(player: i32, score: i32) {
s.points[player] = score
}
fn main() !u8 {
mut board = Scores{ points: [4]i32[] }
board[2] = 10
board[2] += 5
println(board[2]) // prints 15
return Ok(0)
}Vec and String in @core define their subscripts with these same methods,
in ordinary Vyi.
Iteration methods
for x in v calls @-methods too (statements):
| Method | Called | Returns |
|---|---|---|
v.@iter() | once, before the first iteration | an iterator: a value with @next() |
it.@next() | each iteration, on the loop's iterator | ?T: Some(x) is the next element, None ends the loop |
v.@index(i), v.length() | when v has no @iter() | the element at i; the number of elements |
Range operators
a..b and a...b build a Range, an ordinary struct from @core with the
fields start, end, and inclusive. a..b excludes b and a...b
includes it; inclusive records which, so a range means the same thing written
in place or stored in a binding.
| Use | a..b | a...b |
|---|---|---|
for x in a..b | a up to b - 1 | a up to b |
xs[a..b] | elements a to b - 1 | elements a to b |
| value | Range{ start: a, end: b, inclusive: false } | Range{ start: a, end: b, inclusive: true } |
- Ranges bind most loosely of all, so
1..n + 1is1..(n + 1). foriterates a range written in place. A range stored in a binding is not iterable; writefor x in r.start..r.end.- A range with a missing end,
..b,a.., or.., is written only in a subscript.
import { println } from "@fmt"
fn main() !u8 {
con word = "hello"
println(word[1..3]) // prints el
println(word[1...3]) // prints ell
con r = 1...3
println(word[r]) // prints ell
return Ok(0)
}Compound assignment
Every arithmetic and bitwise operator has a compound form. Each one calls its in-place method when the type has one, and otherwise calls the plain operator and stores the result:
| Compound | Method | Fallback | Compound | Method | Fallback |
|---|---|---|---|---|---|
+= | @compAdd | @add | &= | @compBand | @band |
-= | @compSub | @sub | |= | @compBor | @bor |
*= | @compMul | @mul | ^= | @compBxor | @bxor |
/= | @compDiv | @div | <<= | @compShl | @shl |
%= | @compMod | @rem | >>= | @compShr | @shr |
+%= | @compAddWrap | @addWrap | -%= | @compSubWrap | @subWrap |
*%= | @compMulWrap | @mulWrap |
The method for %= is @compMod, while % itself calls @rem.
- With the in-place method,
place OP= valueis the callplace.@compOP(value). The method takes a*mutreceiver, changes the value through it, and returns().valueis checked against its parameter, which may be any type; the plain operator plays no part. - Without it,
place OP= valueisplace = place OP value, with the place evaluated once. - In a generic function, the choice is made for each instance, by the place's type there.
- Assignment is a statement and produces no value, so
con y = (x += 1)is a parse error.
import { println } from "@fmt"
struct Tally { votes: i32 }
fn (t: *mut Tally) @compAdd(count: i32) {
t.votes += count
}
fn main() !u8 {
mut tally = Tally{ votes: 0 }
tally += 3
tally += 2
println(tally.votes) // prints 5
return Ok(0)
}Tally has no @add, so tally + 3 is an error. When a type has both, +=
calls @compAdd and + calls @add, and each method's parameter decides what
its operand may be.
The place is evaluated once, so a place that contains a call would have to run the call twice. The compiler rejects it:
fn nextSlot() i32 { return 0 }
fn main() !u8 {
mut counts = [2]i32[0, 0]
counts[nextSlot()] += 1 // error: compound assignment would evaluate this place twice
return Ok(0)
}Bind the index first: con slot = nextSlot(), then counts[slot] += 1.
Where an operator's method comes from
An operator method is found like any method call written at the same spot
(guide 04):
first in scope where the operator is written, then in the pocket of the left
operand's type (methods and dispatch). The compiler
provides the methods for primitives, and @core writes the ones for its types
in ordinary Vyi.
| Operand type | Built-in operators |
|---|---|
| integers | arithmetic, %, wrapping, bitwise, shifts, comparisons, equality |
| floats | + - * /, comparisons, equality |
bool | == != && || ! |
char | == != < > <= >= |
| pointers | == !=, by address |
singleton unions (1 | 2, "a" | "b") | == !=, by value |
unions (i32 | bool) | == !=, through the members' == (types) |
| enums without payloads | == !=, by variant |
| enums whose payload types all compare | == !=: the same variant with equal payloads, compared with the payload type's == |
[*con]u8, [*mut]u8 | == !=, by content; indexing and slicing |
String, Vec(T) | the methods @core writes for them |
| structs | none; each operator comes from an @-method you write |
A struct never gets == on its own, because comparing every field isn't always
the equality you want. An enum's built-in == never calls a payload type's
@eq; an enum with such a payload needs an @eq of its own (guide
13).
@hash backs no operator. HashMap finds a key with key.@hash() and confirms
it with @eq, and @core provides @hash for the integer types, char, and
String. Values that are @eq-equal must have the same @hash.
Built-in numeric semantics
| Operation | Rule |
|---|---|
integer / | rounds toward zero: -7 / 2 is -3 |
integer % | the result takes the dividend's sign: -7 % 2 is -1 |
>> | copies the sign bit on signed types, shifts in zeros on unsigned ones |
integer + - *, unary - | the exact result when it fits the type; otherwise a debug build panics with integer overflow and a release build wraps at the type's width |
integer +% -% *% | wrap at the type's width in every build mode |
signed MIN / -1 | overflows: a debug build panics, a release build gives MIN; MIN % -1 is 0 |
integer / 0, % 0 | panics with division by zero in every build mode |
| shift count | must be from 0 to the operand's width minus one (0 to 7 for a u8); outside that a debug build panics with shift count out of range and a release build takes the count modulo the width. Bits shifted out are dropped and never count as overflow |
| float arithmetic | IEEE 754: 1.0 / 0.0 is infinity and 0.0 / 0.0 is NaN, never a panic |
C integer types (c.int, c.size_t) | follow C in every build mode: + - *, unary -, and MIN / -1 wrap, and a shift takes its count modulo the width, never a panic. / 0 and % 0 still panic with division by zero. See @c |
float %, bitwise operators, shifts, and wrapping operators on floats | not built in; an error unless a method provides them |
An integer never holds a value outside its type, on any target or in any build
mode: a u8 sum is always 0 to 255. The build mode is chosen with --mode
(CLI) and can be read as targetBuildMode
(targets). Integer arithmetic the compiler does
follows the same rules, except that a result that doesn't fit is a compile
error in both modes (known values).
import { println } from "@fmt"
fn main() !u8 {
mut level: u8 = 250
println(level +% 10) // prints 4
level *%= 2
println(level) // prints 244
return Ok(0)
}@-methods and member access
The @ is part of the method's name. a.add(b) never finds @add. The written
call a.@add(b) is always available and resolves like any method call; on a
primitive it is the built-in operator, so 5.@add(3) is 8. Declaring an
@-method is the only way to give a type an operator.
See also expressions for the rest of the expression grammar and methods and dispatch for how a method is found.