On this page (10 sections)
- 4.1 Value semantics is the only semantics
- 4.2 Access effects on parameters
- 4.3 Call-site markers & and consume
- 4.4 The Law of Exclusivity
- 4.5 Subscripts & projection
- 4.6 Copy elision
- 4.7 Deinitialization & destruction order
- 4.8 No reference types
- 4.9 Raw memory (FFI)
- 4.10 Return values & ownership escape
§4 Memory Model ★ CORE ★
Joyeer combines mutable value semantics with deterministic destruction (RAII). The rules below define ownership, temporary access, and cleanup independently of a particular physical representation.
Design rationale. Values remain independently owned; access projections allow temporary observation or mutation without introducing shared ownership. This avoids GC scheduling and retain/release accounting while keeping resource lifetimes explicit. Omitting first-class references narrows the lifetime surface, but does not remove the need for initialization, consumption, exclusivity, and control-flow analysis.
4.1 Value semantics is the only semantics
Every binding holds a value. Assignment is conceptually a copy:
var a = [1, 2, 3]
var b = a // semantically: b is an independent copy of a
&b[0] = 99
print(value: a) // [1, 2, 3]
print(value: b) // [99, 2, 3]
Ordinary initialization or assignment from an existing binding is a copy operation. The source remains initialized and usable afterward. For the v0.1 heap-backed types (String, Array, Dict, and aggregates containing them), copying recursively clones the owned storage. The source and destination never share mutable storage, and the implementation does not use copy-on-write or reference counting.
An already-owned temporary may instead be transferred directly into its destination because no independently usable source binding exists. The compiler may also elide a materialized copy under the as-if rule in §4.6, but that optimization never changes whether a source binding is initialized. Only a consuming operation has that source-visible effect (§4.2.3).
Cost note. A semantic copy is not necessarily a constant-time operation. Recursive copying can allocate and scales with the data copied. Explicit consumption distinguishes ownership transfer from copying without making source correctness depend on whether an optimizer happens to elide a copy.
There are no reference types in Joyeer. No &T, no pointers, no Box/Rc/Arc. The closest equivalents are access effects on parameters (§4.2) and projections via subscripts (§4.5), neither of which is a first-class value.
4.1.1 Copyability
A type is copyable when an ordinary copy can produce an independent value with its own destruction obligation:
- scalar built-ins are trivially copyable;
- function types (§2.3.1) are trivially copyable and never linear, whatever their parameter and result types are:
(consuming TcpConnection): ()is copyable. Copyability and linearity do not look inside a function type, and a struct holding one has no recursive layout (struct S { var f: (S): S }); String,Array, andDict, and the role-bound enumsOptionalandResult(§2.4, §2.5), are copyable when their contained types are copyable; heap-backed storage is cloned recursively;- a
structorenumis copyable when all of its stored fields or payloads are copyable and it does not declare a customdeinit. - a type parameter of a generic function or type (§20.4, §20.12) is copyable exactly when its constraint lists
Copyable(§20.5), and is never linear except for closed compiler-prelude transfer parameters (§20.12.3/.5); - a generic
structorenuminstanceBox<X>is copyable when the type declares nodeinitand every field or payload, with the parameters replaced byX, is copyable. A parameter that appears in no field does not affect copyability. A type that ownsTvalues through anIntaddress has noTfield, so it must declaredeinit(§20.12.4); the compiler cannot detect the omission. User generic declarations may not take a linear type argument (§20.12.3); the compiler-prelude task declarations use its closed must-transfer exception, and the role-bound enumsOptionalandResultaccept one because their linearity follows their payload.
A struct bound by the role array_type (§20.12.5, 0025) is the exception: it declares deinit yet is copyable exactly when its owned type parameter is, copied element by element, and is linear exactly when that parameter is.
A type that declares deinit is noncopyable by default. Ordinary initialization or assignment from a binding of that type is rejected rather than synthesizing a fieldwise copy that could release the same resource twice. Noncopyability propagates: a struct or enum with a noncopyable field or payload, and an Array, Dict, Optional or Result whose element, key, value, payload or error type is noncopyable, is itself noncopyable, so Result<TcpConnection, NetworkError> cannot be copied. A noncopyable type does not satisfy the Copyable constraint of §20.5. The implicit copy that lowering performs when a borrowed value is needed as an owned one (§4.1) is a compile-time error for such a type, reported at the copy site (provisional; see decision 0015). A value that is discarded is not needed as an owned one, so naming a noncopyable place there copies nothing: an expression statement, the trailing expression of a block whose value is unused (a Void or Never function body, a while body, the branch of an if without else), the branches of an if or match whose own value is discarded, and the inside of a discarded parenthesized expression. As a statement, if flag { handle } else { Handle(fd: 3) } only reads handle; as a binding initializer or a call argument it copies handle and is rejected. A discarded owned temporary is still destroyed when its enclosing block or match arm ends, and a discarded linear value is an error (§4.7.1). Such a value may still be passed through a consuming boundary or produced as an owned temporary. A future explicit copy-initializer design may let a type opt back into copying; it is not part of v0.1.
Linear types (provisional)
A linear type is a noncopyable type whose value must be explicitly ended: it is never destroyed implicitly. The source-library JoinHandle<R> (§2.6, with the concurrency design in decision 0013) is the only linear type of the first implementation. A struct or enum that holds a linear field or payload, and an Array, Optional or Result whose element, payload or error type is linear, is itself linear; a Dict key or value may not be. A linear type is noncopyable, so it does not satisfy Copyable (§20.5), and it may not declare deinit; a type with deinit may not hold a linear field. A linear type may not be a type argument of a generic function (type-checking.linear-type-argument, §20.4.1): ordinary generic code may drop a T. The compiler-prelude transfer exception checks owning values as potentially linear instead (§20.12.5). The role-bound enums Optional and Result (§2.4, §2.5) are the other exception: they hold their payload but never drop it, and a Some(_), Ok(_) or Err(_) pattern on a moved linear instance is checked against the substituted payload type, so it is still linear-result-dropped.
A linear binding must not be live at any exit of its scope (§4.7.1). Implementation status: the checks are implemented for a struct declared linear in a toolchain-authorized source, and for JoinHandle<R> (§21, decision 0015 "Linear types (P2c)").
4.1.2 Ownership state vs. access effect (two axes)
Two orthogonal classifications govern every binding. Keeping them apart removes a common confusion: owned is a state (who must destroy the value), whereas consuming is an effect (how a parameter acquires that state across a call).
Axis 1 — ownership state.
- An owning binding is responsible for the value's destruction: its
deinitruns when the binding goes out of scope, is overwritten, or is consumed (§4.7). Locallet/varbindings, storedstruct/enumfields, andconsumingparameters (includingconsuming self) are owning bindings. - A projecting (borrowing) binding is a temporary view that never destroys the value; an owner elsewhere stays responsible.
borrowingandinoutparameters and subscriptyieldprojections (§4.5) are projecting bindings.
Axis 2 — mutability. Independently of Axis 1, a binding is immutable (let, borrowing) or mutable (var, inout, owning consuming).
The four parameter access effects (§4.2) are points in this space — they describe how a parameter relates to the caller's storage, not a separate kind of thing from ownership:
| Binding | Owns? (runs deinit) | Mutable? | Caller's value |
|---|---|---|---|
let x (local) | ✅ | ❌ | — (no call boundary) |
var x (local) | ✅ | ✅ | — |
borrowing param (default) | ❌ | ❌ | caller keeps |
inout param | ❌ | ✅ (exclusive) | caller keeps |
consuming param / self | ✅ | ✅ | transferred to callee |
initializing param | writes caller's uninit. storage | ✅ (write) | caller keeps |
consuming is the only access effect that transfers ownership; borrowing / inout / initializing are projections that leave ownership with the caller. "owned" names the resulting state; consuming names the effect that produces it. A local var is owned without being consuming; a consuming parameter is owned because the caller relinquished it (the caller's binding becomes uninitialized, §4.2.3). Every consuming binding is owned, but not every owned binding is consuming.
A consuming parameter (and consuming self) is an owning, var-like (mutable) binding. Any owning mutable binding may be mutated in place by its owner; a let local is owning but immutable. In-place mutation is marked with & at the mutation site (§4.3). Both mutating and consuming receivers may mutate self: mutating exclusively borrows the receiver and returns it to the caller, while consuming transfers ownership to the callee (§3.2.4).
4.2 Access effects on parameters
A function parameter declares how the function will access the argument's storage. The effect is part of the function signature; callers must match it explicitly at the call site (§4.3).
Design rationale. An unqualified value: T parameter is a read-only borrowing projection, not an implicit deep copy or consume. The absence of & in the type does not determine whether the machine ABI passes bits or an address. Source-level access and physical calling conventions are distinct; materializing an owned value from borrowed storage follows the copy rules in §4.1 and §4.10.
| Effect | Meaning | Caller obligation | In-body usage |
|---|---|---|---|
borrowing (default) | Read-only projection. Multiple borrowing projections of the same value may coexist. | Pass without marker (may write borrowing x for emphasis). | Use as immutable value. |
inout | Exclusive mutable projection. While held, the original storage is inaccessible to anyone else. | Mark with &x at call site. | Use and mutate like a local var. |
consuming | Consume the argument. Moving out of a named place leaves it uninitialized after the call. | Write consume x for a place expression; omit consume for an rvalue temporary (§4.3). Caller must own the value. | Owned outright — a var-like, mutable binding (§4.1.2); may be mutated in place, moved into the return value, passed to another consuming parameter, or destroyed. |
initializing | Write-only into uninitialized storage. | Mark with &x at call site, where x is uninitialized or has been consumed. | Must initialize before the body ends. |
4.2.1 borrowing (default)
func max(a: Int, b: Int): Int { if a > b { a } else { b } }
var x = 10
var y = 20
let m = max(a: x, b: y) // both x and y are borrow-projected; safe to coexist
print(value: x) // ✅ x still accessible
The default may be written explicitly for emphasis: func max(a: borrowing Int, b: borrowing Int): Int.
4.2.2 inout
func increment(n: inout Int) { &n += 1 }
var k = 5
increment(n: &k)
print(value: k) // 6
While increment holds an inout projection of k, no other access to k is permitted — checked at compile time by the law of exclusivity (§4.4).
4.2.3 consuming
func store(s: consuming String) { /* s is mine: mutable, printable, destroyable, returnable */ }
var greeting = "hello"
store(s: consume greeting)
// print(value: greeting) // ❌ error: use of consumed value 'greeting'
After the call, greeting is in an uninitialized state. The compiler rejects any subsequent read. A subsequent assignment (greeting = "world") re-initializes the storage and re-enables reads.
Inside store, s is an owning, var-like binding (§4.1.2): the body may mutate s in place (e.g. &s.append(s: "!")) as well as move or destroy it. Ownership — not a mutating keyword — is what grants in-body mutation.
4.2.4 initializing
func produceLargeBuffer(out: initializing [UInt8]) {
&out = makeBuffer(size: 1_000_000)
}
var buf: [UInt8] // declared but uninitialized
produceLargeBuffer(out: &buf) // 'initializing' writes without destructing prior contents
initializing is the emplace pattern: the callee promises to initialize the storage; the caller promises the storage was uninitialized. This avoids a destruct-then-construct round-trip for large objects.
4.3 Call-site markers & and consume
The call-site marker for inout and initializing arguments (and mutating method receivers) is &; the marker for consuming arguments (and consuming method receivers) is consume (decision 0047).
swap(a: &a, b: &b) // both args are inout
produceLargeBuffer(out: &buf) // 'initializing' is also marked &
store(s: consume s) // 'consuming' place argument: 'consume' required
store(s: "hello") // 'consuming' rvalue temporary: omit 'consume'
plain(x: x, y: y) // no marker → both are borrowing (read-only)
&is mandatory on everyinoutandinitializingargument and everymutatingmethod receiver.consumeis mandatory on every place expression passed to aconsumingparameter or used as the receiver of aconsumingmethod, except in the closed library owned-argument context below. A place expression (looking through parentheses) is a variable, parameter, pattern binding, or top-levelletconstant (x,Mod.CONST), a stored struct field (e.field), or a subscript (e[i]). Every destructive move out of named storage is therefore visible at the call site by simple scanning (§0.1 principle 2).- Rvalue temporaries omit
consume. Any non-place expression — literals,(), string interpolations, enum case constructors (Color.Red,.Ok(x)), struct constructors (Point(x: 1, y: 2)), function values (square,Mod.square), function or method calls (including parenthesized consuming or mutating calls such as(consume b.step())and(&a.removeLast())), operators (+,as,as?,&as,??), optional chaining (?.), postfix?and!, array/dictionary literals,if/matchexpressions, andNeverexpressions — produces a fresh owned temporary with no named storage to invalidate. Passing an rvalue temporary to aconsumingparameter or as the receiver of aconsumingmethod requires noconsumemarker (except for stored-receiver library methods such asJoinHandle.join(),ChannelSender.close(),ChannelReceiver.close(), andArray.consumeEmpty(), which reject temporary receivers altogether). Writingconsumeon an rvalue temporary remains accepted for compatibility except where explicitly forbidden (such as default parameter expressions, §3.2.5), but omitting it is the canonical style. - Projections of temporaries. A field access (
makeStruct().field) or subscript (makeArray()[0]) is a place/projection expression even when its base is a temporary, and cannot be consumed in place; bind the temporary or copy the projected value into a local first.
A consuming parameter of an array_type method declared with exactly the role's owned type parameter is an owned argument context (§20.12.5). Unlike an ordinary consuming parameter, an owned argument context accepts an unmarked copyable place (copying it without uninitializing it), in addition to unmarked rvalue temporaries and explicitly consumed owning places (append(element:)). & is invalid. The exception is classified before generic substitution, applies to neither receivers nor other parameters, and does not relax exclusivity or the must-transfer rule inside the library body.
Last-use optimization still applies to plain borrowing bindings (§4.6); consume specifies semantic ownership transfer, not the optimization.
4.4 The Law of Exclusivity
At any program point, for any storage location: either any number of
borrowingprojections coexist, or exactly oneinout/consuming/initializingprojection exists. The two regimes never overlap in time or in storage.
Checked statically by the compiler. Examples:
var x = 10
let a = x // independent value copy, not an outstanding borrow
let b = x // another independent copy
increment(n: &x) // allowed: a and b do not alias x
var x = 10
increment(n: &x) // ✅ inout for the duration of the call
let a = x // inout ended; copying x is allowed
func add(dst: inout Int, src: Int) { &dst = dst + src }
var n = 5
add(dst: &n, src: n) // ❌ error: 'n' has overlapping inout + borrowing projections
In a call through a function value (§5.6.1), the callee is evaluated first to a copy and holds no projection, so (s.f)(&s) and (handlers[0])(&handlers) take only the argument projections.
4.4.1 Field-level disjointness
The compiler analyzes access paths. For struct fields, distinct paths are treated as disjoint storage:
struct Point { var x: Int; var y: Int }
var p = Point(x: 1, y: 2)
&p.x += p.y // ✅ &p.x is inout, p.y is let — disjoint paths
4.4.2 Index-level conservatism
The compiler does not prove that two array indices are different. Two projections that are held at the same time, such as the arguments of one call, conflict when their paths differ only at [index] steps:
var a = [1, 2, 3]
swap(first: &a[0], second: &a[1]) // ❌ error: cannot prove a[0] and a[1] are disjoint
Workaround: copy one side into a let snapshot, or use a standard-library subscript that takes both indices:
let tmp = a[1]
update(dst: &a[0], src: tmp) // ✅
&a.bumpAt(0, by: a[1]) // hypothetical: API takes care of disjointness
A subscript on an array_type struct (§20.12.5) is a wildcard path step exactly as above. Its access is made through the type's array_element addressor, which is not itself an access subject to this analysis: the surrounding a[i] carries it. Index operands are evaluated first, then any right-hand side, then the addressor (and its bounds trap), then the access. consume a[i] of a linear element is rejected.
4.4.3 Assignment
An assignment &target = value or &target op= value is not a held pair of projections. Its right-hand side produces a value, and the inout access to target begins only after that value exists:
- Index operands in
targetare evaluated, left to right. - The right-hand side is evaluated.
- The
inoutaccess totargetbegins: bounds are checked, the old value is read forop=, and the result is stored.
So the right-hand side may read the destination or call anything that borrows or mutates the same root, and the store still lands in the storage that exists at step 3:
var a = [1, 2, 3]
&a[0] += a[1] // ✅ a[1] is read as a value before a[0] is accessed
&a[0] = a[0] + a[2] // ✅
&a[0] += grow(a: &a) // ✅ grow may reallocate; a[0] is accessed afterwards
Only the right-hand side's own calls are checked for exclusivity (§4.4), not against the assignment target. A right-hand side that consumes the target's root, or the part of it the target projects through, is rejected (use-after-consume): nothing is left to assign into at step 3.
&d["b"] = take(d: consume d) // ❌ error: 'd' is consumed before the element is assigned
d = pass(d: consume d) // ✅ the whole binding is reinitialized
For the same reason a right-hand side may initialize the target's root, on every path, before step 3 assigns into it; the element it replaces is destroyed once:
var d: [String: Res]
&d["k"] = fill(out: &d) // ✅ fill initializes d; then d["k"] is replaced
4.5 Subscripts & projection
4.5.1 Accessor blocks
A subscript may expose any combination of borrowing, inout, initializing, consuming accessors (§3.6). Which accessor runs is decided by the usage context:
| Call-site form | Accessor invoked |
|---|---|
let v = a[i] | borrowing |
&a[i] = expr or &a[i] += ... or &f(&a[i]) | inout |
&a[i] = expr (uninitialized storage) | initializing (rare; usually via init helpers) |
consume a[i] | consuming |
4.5.2 yield
yield (and its yield & variant for inout) hands control back to the caller with a projection of the named storage. When the caller's use-site ends (end of the enclosing statement), control returns to the accessor and the storage is "ungiven."
extension Buffer {
public subscript(i: Int): UInt8 {
borrowing {
assert(condition: i >= 0 && i < count, message: "index out of range")
yield data[i]
}
inout {
assert(condition: i >= 0 && i < count, message: "index out of range")
yield &data[i]
}
}
}
4.5.3 Lexical lifetime of projections
The lifetime of a yielded projection equals the smallest enclosing statement (not expression). No flow analysis (no NLL-style refinement) — this is a deliberate simplicity choice for AI tooling.
swap(first: &a[0], second: &a[1]) // both projections established at the call
// → conflict detected here
Assignments are the exception: the inout access to the target starts after the right-hand side has been evaluated (§4.4.3).
4.5.4 Disjoint paths
Paths are sequences of .field and [index] steps. Two paths are disjoint when they differ at a .field step. They are potentially overlapping when they only differ at [index] steps (the compiler does not solve index equality in v0.1).
4.6 Copy elision
Copy elision is an implementation optimization, not a source-level ownership operation. An ordinary copy keeps its value-semantics contract even when the compiler proves that transferring storage produces the same observable behavior. In particular, ordinary assignment never places the source in the uninitialized state tracked for consume (§4.2.3).
The v0.1 implementation transfers already-owned temporaries and materializes copies from borrowed heap-backed storage. A future liveness optimization may transfer storage for a provably dead source when doing so cannot change program behavior:
var src = makeBigArray()
var dst = src // semantically a copy; storage transfer may be elided
print(value: dst.count)
Adding any later read of src requires an independent value and therefore prevents the transfer. Code that must semantically relinquish a caller-owned value uses the explicit consume marker at a consuming boundary; optimization must never infer that source-level state transition.
4.7 Deinitialization & destruction order
A value's deinit runs when:
- The owning binding goes out of scope.
- The binding is overwritten by a new value (the previous value's
deinitfires before the new value is stored). - The value is consumed by a
consumingparameter and the receiver finishes with it.
Order within a scope is reverse declaration order, for stored fields of a struct as well. Order is fully deterministic; no finalizer queue, no GC.
A value of a type with a deinit is destroyed whole: its deinit body runs first, and then its stored fields are destroyed in reverse declaration order. For that reason a stored field of such a value cannot be moved out of it (§3.7.1), and a consuming function that is given one destroys it, running its deinit, at the end of the call unless the function passes it on. A deinit may run on a different thread from the one that created the value when ownership has moved between threads (provisional; the concurrency design in decision 0013).
For an overwrite, the right-hand side is evaluated and converted into an owned replacement before the previous value is destroyed. The old value is then destroyed and the replacement is stored. This ordering makes self-assignment and assignments whose right-hand side reads the destination well-defined: the old storage remains valid until the replacement is ready.
public struct FileHandle {
var fd: Int32
public init(path: String) {
precondition(condition: path.notEmpty(), message: "empty path")
fd = sys.open(path: path)
}
deinit() {
sys.close(fd: fd)
}
}
public func work() {
var f = FileHandle(path: "a.txt")
// ...
} // f.deinit() runs exactly here
4.7.1 Linear values (provisional)
Rule 1 of §4.7 does not apply to a linear value (§4.1.1): leaving the scope of a binding that may still hold one is a compile-time error, semantic-analysis.linear-not-consumed, reported at the exit. A binding is live at a point if some path to it has initialised it and not consumed it; an aggregate is live while any of its linear field paths is possibly unconsumed. An exit is the end of a block, an early return, a ? propagation, a break or continue out of the loop body that contains the binding, and the end of a match arm for a binding the arm introduced. A call that cannot return, and a trap, are not exits.
- Ending. A linear value is consumed by moving it (
consume, aconsumingargument, a return, an initializer, an enum payload, anappend, a binding): the receiver takes on the obligation. It ends through its consuming implementation (joinfor aJoinHandle;consumeEmpty()for an array, which traps before any effect if the array is not empty). A linear aggregate ends by consuming every linear field path; its remaining fields are destroyed as usual. - Overwrite. Assigning to a place that is live (a local or a field path) is
semantic-analysis.linear-overwrite; assigning to an ended or uninitialised place reinitialises it. An array element of linear type cannot be overwritten. - Commit. A
consumein an argument or aggregate list takes effect when the call or construction commits, so a later operand that exits (?,return) leaves the value live. In an array literal or enum construction, a move from a named linear place reserves that place until the last operand succeeds. Later operands must not access overlapping storage. An exit that abandons the construction cancels the reservation without consuming the place; the usual rule for ending any linear binding whose scope is exited still applies. - Temporaries. An owned linear temporary must be moved at once: as a binding initialiser, the right-hand side of an assignment to an ended place, a
returnvalue, a consuming argument, an aggregate or enum component, anappend, or amatchscrutinee. Any other use, including a statement whose value is dropped, issemantic-analysis.linear-result-dropped. - Matching. A pattern over a linear scrutinee must bind every linear payload (§7.1.2).
?and!consume an owned linear operand;??and?.are rejected on one.
A function that only borrows, or takes inout, a linear value has no owning binding to end, so the rule does not apply to it. defer remains reserved. Implementation status: the exits, overwrite, statement-result, borrowed-temporary, match, and ??-rejection (§5.12) rules are implemented, as is committing named moves in array literals and enum payloads. The commit order of ordinary call arguments and struct initializers, and ?/!/?. on a linear operand, are not yet implemented.
4.8 No reference types
There is no syntax in Joyeer to express "a value that aliases another value" outside of subscript yields. The following do not exist:
&Tas a value type- Pointers (
*T) Box<T>,Rc<T>,Arc<T>- Weak references
indirect enum cases (§3.4.1) enable recursive value structure, not shared ownership cycles. Graphs and cycles can be represented with explicit collection indices; the owned storage remains acyclic.
Design note. Bounds checks and exclusivity do not establish an index's container identity or generation. A stale or cross-container index can select the wrong live element while remaining in bounds. A checked handle or arena abstraction would need a separate design; neither is a current language API. Likewise, the lexical projection rules do not authorize a borrow to escape to another thread. Cross-thread sharing requires a separately specified lifetime and concurrency model.
4.9 Raw memory (FFI)
The restricted C boundary specifies scalar native imports and exports, restricted buffer imports and bare byte pointers for an explicitly authorized compilation context. By-value scalar ABI adaptation does not introduce references, aliasing values, or a way for native code to mutate the caller's scalar storage. Implementation coverage is recorded in C interop.
Raw memory remains outside the accepted surface of ordinary source. This revision adds no address type, address-taking or dereference syntax, nullable address representation, or public pointer API. unsafe remains reserved (Appendix A); a future block or pointer spelling is not selected here.
Runtime units are the one exception. Units the toolchain authorizes for native bindings may use the compiler intrinsics of §19.4.5, which treat an Int as an address and load and store through it. They exist so that the runtime and the standard library's host code can be written in Joyeer (decision 0005). Such a unit takes on the obligations of C for that code; the language checks nothing about the addresses, and none of it is reachable from ordinary programs.
The scoped native-memory contract limits byte extents, read/write access, nullability, retention, and ownership to explicit adapters in authorized units. It does not expose a memory region or an address that ordinary code can store. Ordinary access effects, Optional, and managed layouts do not imply C representations. Importing a module whose units are authorized does not grant the importer native privileges.
4.10 Return values & ownership escape
A function communicates a result to its caller only through its return value. Because Joyeer has no reference types (§4.8), the return value is the single mechanism by which a value's ownership may escape the frame that produced it.
A function returns ownership of its result to the caller. After the return, the callee does not retain, alias, or deinit the returned value; the destruction obligation (§4.7) transfers to the caller.
An already-owned result temporary transfers directly to the caller. Returning a borrowed value first produces an owned copy. Copy elision may replace that copy with a storage transfer under §4.6; either lowering leaves exactly one destruction obligation for each owned value that remains alive:
func greeting(): String {
let value = "hello"
value // owned result; the caller receives an independent value
}
func use() {
let text = greeting() // caller now owns the result
// ...
} // text is destroyed here — exactly once
4.10.1 Returning through consuming
A consuming parameter or consuming self (§4.2.3, §3.2.4) owns its argument outright. Because an owning binding is mutable in place (§4.1.2), the body may mutate self directly and then move it into the return value — no rebinding to a local var is needed. Ownership flows in at the call site (marked consume, §4.3) and back out through the result:
struct PathBuilder { var buf: String }
extension PathBuilder {
consuming func join(part: String): PathBuilder {
&self.buf.append(s: "/") // self is owned in-body → mutable in place (§4.1.2)
&self.buf.append(s: part)
self // move out: ownership returns to the caller
}
}
var p = PathBuilder(buf: "usr")
let full = consume p.join(part: "local").join(part: "bin")
Each link consumes its receiver, mutates the owned self, and moves it out as a freshly-owned result; at every point there is exactly one owner (§4.4), and the transfer is visible at the call site.
4.10.2 In-place result via initializing
Returning a large value by result would, at an overwrite site, require the prior value to be destroyed before the new one is stored (§4.7 rule 2). To avoid that destruct-then-construct round-trip, a function may instead write its result directly into caller-provided uninitialized storage through an initializing parameter (§4.2.4) — the emplace alternative to a return value:
// by-result form
func makeBuffer(size: Int): [UInt8] { ... }
// emplace form — constructs in the caller's storage, no intermediate value
func produceLargeBuffer(out: initializing [UInt8]) {
&out = makeBuffer(size: 1_000_000)
}
var buf: [UInt8] // declared, uninitialized
produceLargeBuffer(out: &buf) // '&' marks the initializing argument (§4.3)
The two forms are observationally equivalent; the initializing form exists for cases where eliding the temporary is required (very large or non-movable payloads).
4.10.3 No reference or projection may be returned
A function result is always an owned value. The following are not expressible:
- returning a reference (
&Tis not a type, §4.8); - returning a
borrowing/inoutprojection of a parameter or local; - returning the address of a local.
When a caller needs in-place access to storage owned by a callee, the callee exposes a subscript whose accessor yields a projection (§4.5.2) instead of returning it. The projection's lifetime is the enclosing statement (§4.5.3); it is not a value and cannot be stored:
extension Buffer {
subscript(i: Int): UInt8 {
borrowing { yield data[i] } // in-place read projection
inout { yield &data[i] } // in-place mutable projection
}
}
&buf[3] += 1 // projection established and released within this one statement
4.10.4 Result, Optional, and diverging returns
Fallible functions return the failure as a value — there is no out-of-band return channel (no exceptions, §8.1). Absence is Optional<T> (§2.4); recoverable failure is Result<T, E> (§8.2); both compose with ? (§8.3) and ?? (§8.5):
func parseInt(s: String): Result<Int, ParseError> {
if s.isEmpty() { return .Err(.Empty) }
// ...
.Ok(n) // implicit return of the trailing expression
}
A function that never returns normally has result type Never (§2.9); a Never-typed expression (return …, fatalError(…)) satisfies any expected result type and may stand on the right of ?? as an early-exit guard (§8.5).