Joyeer Language Specification
Chapters
On this page (15 sections)

§5 Expressions

5.1 Operator precedence

From highest (binds tightest) to lowest. Same-row operators have equal precedence; associativity is shown.

LevelOperatorsAssociativity
1. (...) [...] postfix ? postfix !left
2prefix ! prefix - prefix ~right
3as as? &as (numeric conversion, §5.2.1)left
4* / %left
5+ -left
6<< >>left
7& (bitwise)left
8^left
9|left
10..< ...none
11< <= > >=none
12== !=none
13&&left
14||left
15?? (nil / .Err coalescing)right
16assignment (= += …)right

(Postfix ? propagates Result/Optional failure; postfix ! forces an unwrap. Optional chaining is the separate ?. form; see §5.4 and §8.3.)

5.2 Arithmetic, comparison, logical, bitwise

Standard semantics. Integer overflow on signed types is a trap in all builds (debug and release alike) — the behavior never changes with the optimization level (§0.1 principles 4 & 5). Programmers may opt into two's-complement wrapping with &+, &-, &* (reserved syntax ⏳, deferred to v0.2).

Comparisons are non-chaining: 1 < x < 10 is a syntax error.

== and != are defined through the Equatable protocol (§20.13): they take two operands of one type that conforms, and != is the negation of ==. The builtin scalars, String and Void conform; a user structure or enumeration conforms only by declaring it, X?, Result<X, Y> and [X] conform when their components do, and function types and Dict never conform. Other operands are rejected with type-checking.invalid-operator-operands. Neither operand takes the enclosing expected type: an operand with no type of its own (nil, .Red, [], a literal) is typed by the other operand, on either side. The left operand is evaluated before the right; how each is accessed is in §20.13.2. x == nil and x != nil test an optional's presence whatever its payload (§20.13.4). Float and Double equality is IEEE 754 equality: a NaN is not equal to itself, and -0.0 == 0.0. Signed Int division (/) truncates toward zero. The remainder (%) is zero or has the sign of the dividend; when defined, a == (a / b) * b + a % b. Both operators trap when the divisor is zero. Both also trap for the minimum Int and divisor -1, including remainder even though its mathematical result would be zero. These checks apply in every optimization mode.

Bitwise &, |, ^ take two integers of the same type; prefix ~ takes one integer. << and >> take an integer on the left and an integer of any type as the shift count. A count that is negative or not less than the bit width of the left operand traps in every build. >> is arithmetic for signed types and logical for unsigned types; << discards bits shifted out and never traps for that reason.

Prefix ! takes a Bool and returns its negation. Logical && and || take Boolean operands and produce Bool.

Logical && evaluates its left operand first and evaluates the right operand only when the left is true. The skipped operand produces no side effects, traps, ownership transfers, or early returns. The result is false when the left operand is false, independently of optimization level.

Logical || evaluates its left operand first and evaluates the right operand only when the left is false. Its result is true when the left is true; the same skipped-side-effect and cleanup rules apply. && binds more tightly than ||. Prefix negation is not postfix force unwrap, which remains deferred.

5.2.1 Numeric conversion

The numeric types are the integer types (Int, UInt, Int8..Int64, UInt8..UInt64) and the floating-point types (Float, Double). Non-numeric types (Bool, Char, String, structs, enums, function types, type parameters, Void, and Never) are rejected on either side of a cast.

T is a plain type name. A cast binds tighter than binary operators and looser than prefix operators: a + b as UInt32 << 8 is (a + (b as UInt32)) << 8, and -x as T is (-x) as T.

Literal operands. With as (for any numeric T) and &as (for integer T), an integer literal (optionally negated or parenthesized) takes target type T. With as, a floating-point literal (optionally negated or parenthesized) takes target type T when T is Float or Double; an out-of-range or unrepresentable literal (such as 300 as UInt8 or 1e40 as Float) is a compile-time error. A floating-point literal cast to an integer type (1.9 as Int, -0.9 as UInt8, 300.0 as UInt8) stays Double and converts via truncation and range checking. With as?, integer literals stay Int and floating-point literals stay Double, so out-of-range literals evaluate to .Err(.OutOfRange) (300 as? UInt8, 300.0 as? UInt8, -1.0 as? UInt8).

5.3 Assignment

assignment      ::= [ '&' ] lvalue assign_op expression
assign_op       ::= '=' | '+=' | '-=' | '*=' | '/=' | '%='
                 |  '&=' | '|=' | '^=' | '<<=' | '>>='

The & prefix is required whenever the assignment target is a mutable projection that the writer does not own outright — an inout / initializing parameter binding, or a projection through an inout / initializing subscript:

&a[0] = 10         // subscript inout projection — & required
&n += 1            // n is an `inout` parameter — & required
p.x = 10           // direct field on a local `var` binding — no & needed
count = count + 1  // direct local `var` — no & needed

Heuristic. Write & when the assignment targets an inout / initializing parameter or storage reached through a subscript. Omit & only when assigning directly to a local var or a direct field of a local var. (Reads never take &; the marker is about the write target.) The compiler reports the required form in any case.

5.4 Member access & methods

member_expr     ::= postfix_expr '.' identifier
optional_chain  ::= postfix_expr '?.' identifier

Methods declared in a struct, enum, or extension are called via member syntax: a.size(), point.distance(to: other).

a.f(args) always calls a method. When a has a type-parameter type (§20.4), the method is a requirement of a protocol in its constraint and the call reaches that requirement's witness (§20.5, §20.6). A stored field of function type is called with a parenthesized callee, (a.f)(args) (§5.6.1). A type may not have a stored field and a method with the same name (name-resolution.duplicate-declaration).

Optional chaining short-circuits to nil:

let lengths = optionalString?.count   // type: Int?

5.4.1 The ? / ! forms

The ? and ! forms, nil, and implicit wrapping bind to the declarations carrying the optional and result roles (§2.4, §2.5), never to a name that happens to be in scope.

FormMeaningSection
T?optional type (Optional<T>)§2.4
x?.fieldoptional chaining§5.4
expr?Result / Optional propagation (early return)§8.3
x ?? ycoalescing with fallback y§8.5
x!force-unwrap (traps on nil)§2.4 / §9.3

5.5 Subscript expressions

subscript_expr  ::= postfix_expr '[' expression , ... ']'

Resolves to the matching subscript declaration. The accessor invoked depends on the surrounding context (§4.5.1).

5.6 Function calls

call_expr       ::= callee '(' [ call_arg , ... ] ')'
callee          ::= identifier | member_expr | '(' expression ')'
call_arg        ::= [ label ':' ] [ '&' | 'consume' ] expression

Argument labels are mandatory at every call by name (§3.2.1); there is no positional / unlabeled form for one and no _ label. func f(a: Int, b: Int) must be called as f(a: 1, b: 2). Supplied arguments follow declaration order; a defaulted argument (§3.2.5) may be omitted but is never written without its label. Unlabeled arguments appear only in a call through a function value (§5.6.1) and in enum construction (§5.8).

5.6.1 Function values and calls through them

The layout intrinsics of §20.12.5 are compiler-known functions, not function values: they can only be called, and only in toolchain-authorized units.

The name of a function, used as an expression where it is not called, is a function value of its function type (§2.3.1, decision 0020):

func square(value: Int): Int { value * value }
func bump(count: inout Int) { count = count + 1 }

let f = square                    // f: (Int): Int
let g: (inout Int): () = bump
var n = f(3)                      // 9
g(&n)                             // n == 10

A module-qualified name works too. Only the name's visibility is checked (§12.2); a private function's value may be returned by a public function.

These are not function values (type-checking.not-a-function-value, which states the reason):

The prelude spawn and channel are generic source-library functions (§21), not builtin functions; the ordinary prohibition on generic function values (§20.4.1) still applies to them.

A function's default parameter values (§3.2.5) do not carry over: a call through the value supplies every argument.

Calls. A function value named by a plain identifier is called directly: f(a, &b, consume c). Any other callee is parenthesized: (s.handler)(x), (table[i])(x), (maybe!)(x); s.f(args) always names a method (§5.4).

5.6.2 Trailing collection block calls

A call whose callee is a function or method with a @collect final parameter (§3.2.8, decision 0042) may supply that parameter as a trailing_block { statement* } immediately on the same physical line after (...), or directly after the callee identifier or postfix_expr '.' identifier when every preceding parameter has a default value (or none exist). Trailing blocks are disallowed at the top level of if/while conditions, for sources (including range bounds), and match scrutinees unless enclosed in parentheses or another delimiter.

Passing a trailing block to any other callee (including function values, enum cases, and protocol-constrained method calls) is type-checking.unexpected-trailing-block. Supplying both the labeled final argument and a trailing block is type-checking.duplicate-collect-argument. A trailing block supplies no consume marker even when the parameter is consuming.

Generic inference (§20.4.1). A trailing @collect block carries no type of its own (ArgumentInformation::none, strength 0 in ==/!= §20.13.2): callee type parameters appearing in [T] must be determined by other arguments or the enclosing expected return type before checking the block. If the substituted element type T is concrete Void, the call is rejected (type-checking.invalid-collect-parameter).

Evaluation and exclusivity. Receiver, earlier arguments, omitted defaults (§3.2.5), and the trailing block evaluate left to right in declaration order. If an earlier argument or default diverges or exits, the block does not execute. Inside the block, exclusivity (§4.4) and consume commit (§4.7.1) apply exactly as for an explicit final argument expression.

Block semantics. The compiler initializes an empty local var $items: [T] = [] in the caller's frame and checks statements in the block recursively:

When the block completes normally, $items is passed as the final argument (borrowed if borrowing, then destroyed after the call; moved if consuming).

5.7 Struct construction

let p = Point(x: 1.0, y: 2.0)         // explicit init or synthesized
let q = Point(x: 0.0, y: p.y)

5.8 Enum construction

enum_ctor_expr     ::= [ type ] '.' identifier [ enum_payload_clause ]
enum_payload_clause
                   ::= '(' enum_arg , ... ')'
enum_arg           ::= [ label ':' ] expression
let command: Message = .Move(x: 3, y: 4)       // contextual: target type known
let text = Message.Text("ready")                // fully qualified
let error: DecodeError = .Unexpected(b'?', at: 12)

The declaration determines the payload arity and labels. A payload position declared without a label is positional; a labeled position must use exactly that label. Positional and labeled payloads may be mixed in declaration order. Besides calls through a function value (§5.6.1), this is the only unlabeled invocation form; calls by name and struct-initializer calls require labels (§3.2.1, §5.6). A payload-less case is written without an empty argument clause (.Quit, not .Quit()).

5.9 Match expression

match_expr      ::= 'match' expression '{' match_arm+ '}'
match_arm       ::= pattern ( ',' pattern )* [ 'where' expression ] '=>' (expression | block) ','?

match is an expression; every arm must produce a value of the same type (or all be Void). An arm may list several comma-separated alternative patterns and runs when any of them matches (§7.2):

enum Reading {
  Missing,
  Value(Int),
}

let label = match reading {
  .Missing                  => "missing",
  .Value(n) where n < 0     => "negative",
  .Value(_)                 => "non-negative",
}

Exhaustiveness is checked (§7.7).

Because return is a diverging expression (§2.9, §6.4), it may be an arm body:

let value = match result {
  .Ok(value) => value,
  .Err(error) => return .Err(error),
}

5.10 if as expression

if/match are expressions; while/for are statements.

let sign = if x > 0 { 1 } else if x < 0 { -1 } else { 0 }

Every branch must produce the same type. The whole if-else must be total (i.e., have an else arm) when used as an expression. An if or match whose value is unused, such as one in statement position, discards the value of the branch that runs; a branch that names a noncopyable place then does not copy it (§4.1.1).

5.10.1 Unit expressions

An empty pair of parentheses in expression position, (), is the unit value of type Void (§2.1.2), not a missing expression or a general tuple. Parenthesized expressions such as (value) keep their existing meaning. In .Ok(()), the outer parentheses contain one payload expression, (); .Ok() is not an alternative unit construction.

5.11 Closures

Closures are deferred to v0.2. A function value (§5.6.1) refers to a top-level function and captures nothing; higher-order code passes such values, or a struct together with a function value when it needs context.

5.12 Nil-coalescing ??

The coalescing operator ?? binds to the optional and result roles (§2.4, §2.5, §5.4.1) and supplies a fallback for an absent Optional or a failed Result (§8.5). It is right-associative at precedence level 15 (§5.1, looser than || and comparisons), so a ?? b ?? c parses as a ?? (b ?? c). The left operand a is evaluated once; b is evaluated only when a is .None or .Err (short-circuit), after any borrow of a has ended. When the error of a Result must be inspected rather than discarded, use match or ? (§8.3).

let port: Int = parseInt(s: s) ?? 8080                       // plain fallback value
let v = parseInt(s: s) ?? fatalError(message: "bad input")   // fallback diverges (Never, §2.9)
let c = peek(p: p) ?? return .Err(.UnexpectedEof)            // fallback returns from the caller

5.13 String interpolation

A string_interpolation expression (§1.7, decision 0046) always has static type String and produces an independent owned String value.