Joyeer Language Specification
Chapters
On this page (9 sections)

§3 Declarations

3.1 Bindings: let / var

binding         ::= ( 'let' | 'var' ) pattern [ ':' type ] [ '=' expression ]
let pi = 3.14159
var count: Int = 0
let (x, y) = somePair        // tuple destructuring

3.1.1 Top-level constants

A top-level let declares a compile-time constant:

public let polynomial: UInt32 = 0xEDB8_8320
let table: [UInt32] = [0, 0x7707_3096, 0xEE0E_612C]

3.2 Function declarations

func_decl       ::= attribute* [ visibility ] [ method_effect ] 'func' identifier
                    '(' [ param , ... ] ')'
                    [ ':' type ]
                    [ block ]

method_effect   ::= 'borrowing' | 'mutating' | 'consuming'   // self access; 'borrowing' is default
param           ::= label [ identifier ] ':' [ access_effect ] type [ '=' expression ]
label           ::= identifier
access_effect   ::= 'borrowing' | 'inout' | 'consuming' | 'initializing'   // 'borrowing' is default
block           ::= '{' statement* '}'

attribute is defined in §11 and Appendix C. The optional body in this production is constrained semantically: only a @c_extern declaration may omit it, and that declaration must omit it. All other functions, including @c_export, require a body. The restricted C binding rules, including authorization and explicit result types, are specified in §19, not implied by the grammar alone.

Implementation status: bodyless @c_extern imports are accepted in authorized units; ordinary functions still require bodies. Coverage is recorded in the implementation boundary.

method_effect is only meaningful for functions that have a receiver (methods declared inside a struct, enum, or extension). Free functions may not carry it. See §3.2.4.

Implementation status: methods and extensions are implemented as described in methods. The borrowing keyword before func is accepted as an explicit spelling of the default receiver effect.

3.2.1 Parameters: labels

Argument labels are mandatory at every call by name; there is no positional / unlabeled form for one. Every parameter has a label and the caller must always write it. (A call through a function value is positional, §5.6.1.)

func add(a: Int, b: Int): Int { a + b }
func transfer(from src: Account, to dst: Account, amount: Int) { ... }

add(a: 1, b: 2)
transfer(from: alice, to: bob, amount: 100)

3.2.2 Return type

A Void return may be written as : () or omitted entirely. A block's trailing expression is its value: when the last item of a function body (or any block, including if / match arms) is an expression of the return type, the return keyword may be omitted for it. return is still required for early exits.

C binding declarations must write their result type explicitly, including Void or (); see §19.2.

func sq(x: Int): Int { x * x }

A return value carries ownership of the result out of the function: the ownership-escape semantics, the consuming / initializing interplay, why no reference may be returned, and Result / Optional / Never results are specified in §4.10.

3.2.3 Generics & constraints

A top-level func may declare type parameters with protocol constraints, func totalArea<S: Shape>(shapes: [S]): Int (§20.4). Methods, init, subscripts, protocol requirements and C bindings may not (type-checking.invalid-generic-declaration; a method's message names the deferred generic methods of §20.10), and there are no where clauses. A struct or enum may declare type parameters (§3.3, §3.4, §20.12), and its methods use them. The generic containers Array, Dict, Optional, and Result are role-bound library declarations (§2.4–§2.6, §20.12.5). Operator protocols such as Comparable are reserved (§20.10).

3.2.4 Method receiver effects

A method declares how it accesses self with a prefix method_effect keyword: mutating / consuming / borrowing (default). The same access effects as parameters apply to the implicit self receiver, with mutating in place of inout.

Receiver effectDeclarationself in bodyCall-site marker
borrowing (default)func peek(): UInt8read-onlynone: b.peek()
mutatingmutating func append(s: String)mutable, exclusive&: &b.append(s: s)
consumingconsuming func build(): Stringowned, mutable in place (§4.1.2); consumedconsume: consume b.build()
extension StringBuilder {
  func length(): Int { ... }                    // borrowing self (default)
  mutating func append(s: String) { ... }      // mutates self
  consuming func build(): String { ... }         // consumes self
}

var b = StringBuilder()
let n = b.length()           // borrowing: no marker
&b.append(s: "hi")              // mutating: '&' marks the receiver (§4.3)
let s = consume b.build()    // consuming: 'consume' marks the receiver (§4.3)
// b is now uninitialized

The call-site markers are the same ones used for parameters (§4.3): mutating reuses &, consuming reuses consume. The marker attaches to the receiver expression: &b.append(...) means "append exclusively borrows b"; consume b.build() means "build consumes b." initializing is not available as a method receiver effect (it only applies to init, which initializes self field-by-field, §3.7).

3.2.5 Default parameter values

(Decision 0045.) A borrowing or consuming parameter of a function, method, or init may declare a default expression with = expression (§3.2 grammar). Defaults are not permitted on inout or initializing parameters, subscript parameters, @c_extern or @c_export declarations (§19.2), protocol requirements (§20.2), or the root main entry point (§3.2.6). A borrowing parameter of linear type (§4.1.1) may not declare a default.

func connect(host: String, port: Int = 8080, timeout: Int = 30): Connection { ... }

connect(host: "localhost")                    // port = 8080, timeout = 30
connect(host: "localhost", port: 443)         // timeout = 30
connect(host: "localhost", timeout: 5)        // port = 8080

3.2.6 Executable entry point

A native executable has exactly one main function across the root module's explicit source-file set (the input file is the root unit in legacy single-file mode). The root module is a compilation unit, not a directory. Dependency functions named main are ordinary functions, not executable entries. The supported entry signatures are func main() (returning Void, whether written explicitly or omitted) and func main(args: [String]): Int. The latter's external parameter label is args, and its access effect is borrowing (the default); the internal parameter name may differ. Both forms cannot be declared together. The root module's main is not a function value (§5.6.1).

The argument-taking form receives the command-line arguments after the executable name, in their original order. Empty arguments and spaces within arguments are preserved. On POSIX, argument strings preserve the operating system's bytes without requiring UTF-8; on Windows, arguments are converted from UTF-16 to UTF-8, and invalid encoding is a runtime error. The runtime owns this array for the duration of main, and ordinary borrowing rules apply within the program.

The parameterless form returns exit status zero. The Int form returns a process exit status in 0..255 after normal scope and argument cleanup. Values outside that range cause an explicit runtime error and failure, not truncation. This limit applies to Joyeer's own entry point, not to exit statuses observed from other processes.

3.2.7 C binding declarations

@c_extern(symbol: "...") and @c_export(symbol: "...") attach native import/export semantics to the source function signature. Their complete rules, including body presence, scalar types, labels, symbol identity, visibility, diagnostics, and linking responsibilities, are specified in §19. They do not create ordinary bodyless prototypes, new parameter syntax, or a general user FFI.

3.2.8 Trailing collection parameters (@collect)

The final parameter of a top-level func (concrete or generic) or a method (borrowing, mutating, or consuming on a concrete or generic struct, enum, or extension) may carry the unparenthesized @collect annotation before its label (decision 0042) when:

@collect takes no parenthesized arguments (@collect(...), repeated @collect, or any other @name on a parameter is parser.unsupported-syntax). It is not permitted on non-final parameters, subscript parameters, @c_extern/@c_export declarations (§19.2), root main (§3.2.6), protocol requirements (§20.2, type-checking.invalid-protocol-member), struct stored fields, enum payloads, or function types (§2.3.1). A protocol conformance witness (§20.3) may declare @collect on its final [T] parameter; the annotation is ignored when called through a protocol constraint. @platform variants (§11.5) must agree on @collect (platform.signature-mismatch).

A @collect parameter may also declare a default value (§3.2.5), e.g. @collect children: [Element<A>] = []. @collect does not change the function's runtime ABI or its function-value type (§5.6.1): callers may still pass the argument explicitly by label (using consume when consuming, §4.3), or omit both label and block if a default is declared.

3.3 Struct declarations

Struct construction uses call syntax Point(x:1, y:2). The record-literal form Point { x:1, y:2 } is reserved (⏳).

struct_decl     ::= [ visibility ] 'struct' identifier [ generic_params ]
                    '{' struct_member* '}'

struct_member   ::= binding
                 |  init_decl
                 |  deinit_decl
                 |  func_decl
                 |  subscript_decl

Structs are value types with predictable layout. No vtables, no inheritance.

public struct Point {
  public var x: Double
  public var y: Double

  public init(x: Double, y: Double) {
    self.x = x; self.y = y
  }

  public func distance(to other: Point): Double {
    let dx = x - other.x
    let dy = y - other.y
    (dx * dx + dy * dy).sqrt()
  }
}

let p = Point(x: 1.0, y: 2.0)

If no init is declared, the compiler synthesizes a memberwise initializer exposing all fields in declaration order, labeled by field name. The synthesized initializer takes the least visible access of the struct's stored fields (a private field makes the memberwise init private), so synthesis never widens access to a field.

A struct may declare type parameters, struct Box<T> { var value: T }, with the constraints of §20.4 (§20.12). The memberwise initializer has the field types in terms of the parameters, and Self inside the struct means Box<T> (§3.9).

3.4 Enum declarations (ADT)

enum_decl       ::= [ visibility ] 'enum' identifier [ generic_params ]
                    '{' enum_case ( ',' enum_case )* ','? enum_member* '}'

enum_case       ::= [ 'indirect' ] identifier [ '(' assoc_type , ... ')' ]

assoc_type      ::= [ label ':' ] type

enum_member     ::= func_decl | subscript_decl

Cases are comma-separated; a trailing comma is permitted. There is exactly one case syntax (no case keyword) — one way to write each thing (§0.1 principle 4).

public enum Message {
  Quit,
  Text(String),
  Move(x: Int, y: Int),
  Batch([Message]),
}

let message: Message = .Move(x: 3, y: 4)
let batch: Message = .Batch([.Quit, .Text("ready")])

Construction uses Type.Case(args) or .Case(args) when the target type is inferable from context. An associated value declared without a label is positional; one declared with a label must use that label in construction and patterns (§5.8, §7):

enum DecodeError {
  Unexpected(UInt8, at: Int),
}

let error: DecodeError = .Unexpected(b'?', at: 12)
match error {
  .Unexpected(byte, at: position) => position,
}

This positional form is specific to unlabeled enum payloads. Ordinary function and struct-initializer arguments remain labeled (§3.2.1). A case without associated values is written without parentheses (.Quit, not .Quit()). Pattern-match with match (§5.9).

Enums are tagged unions. Size is discriminant + max(variant), stack-allocatable, no heap unless the user requests indirection (§3.4.1).

3.4.1 Indirect cases (for recursive enums)

public enum IntList {
  Empty,
  indirect Cons(Int, IntList),
}

indirect boxes the case payload on the heap; required for recursive enums (otherwise the layout has infinite size). Heap allocation is explicit and visible in the declaration — no hidden boxing.

3.5 Extension declarations

extension_decl  ::= 'extension' extended_type [ ':' protocol_ref , ... ]
                    '{' extension_member* '}'

extension_member ::= func_decl | subscript_decl

Extensions add methods (functions tied to a type) and subscripts to an existing type. They cannot add stored fields. An extension with a conformance list declares that the type conforms to protocols (§20.3).

The header of an extension of a generic type lists exactly the declaration's type parameters, once each, as fresh names bound to them in order: extension Box<T>: P { ... }. A concrete argument, a repeated name, the wrong count, or constraints on the names is type-checking.invalid-extension-header (§20.12).

extension Array<Int> {
  public func isEmpty(): Bool { count == 0 }
}

3.6 Subscript declarations

Subscripts are projection accessors — they are the only way to expose internal storage for in-place mutation without leaking reference types.

subscript_decl  ::= 'subscript' [ identifier ] '(' [ param , ... ] ')' ':' type
                    '{' accessor+ '}'

accessor        ::= 'borrowing'   block_with_yield
                 |  'inout'        block_with_yield
                 |  'initializing' block_with_yield
                 |  'consuming'    block

block_with_yield ::= '{' statement* 'yield' [ '&' ] expression statement* '}'

A subscript may declare any combination of borrowing, inout, initializing, consuming accessors. Only the accessor matching the call-site usage is invoked.

extension Array<Int> {
  public subscript(i: Int): Int {
    borrowing { yield  storage[i] }
    inout     { yield &storage[i] }
  }
}

var a = [1, 2, 3]
print(value: a[0])         // → let accessor
&a[0] += 10         // → inout accessor; a is exclusively borrowed during the += expression

Yielded storage has a lexical lifetime ending at the end of the enclosing statement (§4.5.3).

3.7 init / deinit

init_decl       ::= [ visibility ] 'init' '(' [ param , ... ] ')'
                    block

deinit_decl     ::= 'deinit' '(' ')' block

3.7.1 deinit rules (provisional)

Implementation status: implemented for structs (parser through the native backend; see supported features), including moving a noncopyable payload out of a match (§7.1.2) and removing one from an array with Array.removeLast() (§2.6.2). Not implemented: deinit on an enum and init declarations. These rules fix the first implementation (decision 0015): deinit for structs, so that a handle can close the resource it owns. init declarations stay unimplemented, and a struct with a deinit is constructed with its memberwise initializer.

3.8 Import declarations

import_decl     ::= 'import' import_path
import_path     ::= identifier ( '.' identifier )*
import System
import Foundation

Imports precede declarations and apply only to their source file. An import selects the exact complete logical name of an explicitly supplied compilation unit; it does not select a directory or imply parent/submodule relationships. Only public declarations are accessible from another module, through the qualified name. Import aliases (as), wildcard imports, and re-exports are not supported. See §12 for module rules.

3.9 self and Self

Implementation status: implemented for methods of concrete and generic structs and enums, and for their same-module extensions (§20.12, where Self means Name<A, B> with the header's parameters). Implicit-self field access is not implemented: write self.field. See methods.

self and Self are keywords (§1.4) and cannot be declared as identifiers. They name two different things:

WordMeaningNamespace
selfThe receiver value inside a method, init, or deinitvalue
SelfThe type of the enclosing declarationtype

self. The receiver's access is set by the method effect (§3.2.4) and follows the ordinary rules of §4. init initializes self field by field (§3.7). A free function has no receiver; self there is an error.

Self. Self is a type name, not a value. It is in scope only inside the body of a struct, enum, extension, or protocol declaration:

Self introduces no new type. Where it is an alias, it is the same type as the spelled name, and the two are interchangeable in every position. It can appear anywhere that name could appear in a type position, including parameter and result types, Self?, [Self], Result<Self, E>, and an indirect enum payload. It can also be used as a constructor or qualified base, with the same meaning as the spelled name:

struct Square {
    let side: Int
    func scaled(by factor: Int): Self {     // Self is Square
        Self(side: side * factor)           // same as Square(side: ...)
    }
}

enum Light {
    Red, Green
    func other(): Self { Self.Green }       // same as Light.Green
}

Self outside those bodies, including in a free function or a generic function (§20.4), is an error (name-resolution.self-outside-type). A bare Self used as a value, as in let x = Self, is also an error. The value is self.

Design rationale. An alias keeps signatures explicit and reviewable while making renames and protocol requirements (§20) easier to write. Because it is only an alias, it adds no subtyping, no dynamic type, and no runtime cost.