Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sharing places

In the giving chapter, we saw how → transfers ownership. Sometimes you want to read a value while leaving it in its original place. A bare place expression, such as foo, shares that place. You can write the same operation explicitly as foo.share.

Sharing a place and sharing a value

Both operations create shared values, but they record different dependencies:

ExpressionOperationResulting permission
foo or foo.shareShare the place fooshared[foo]
foo→.shareGive the value from foo, then share that valueshared[]
new Foo().shareShare a newly created valueshared[]

shared[], also written shared, introduces no place dependency. Sharing a place preserves its origin in the permission. Permissions in the underlying type can introduce further dependencies; composing permissions does not erase those restrictions. See Sharing values.

A simple example

This program creates a Foo, shares its place, and then uses both the original and the shared result:

simple_borrow [src]
crate::assert_ok!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let foo = new Foo(new Data());
                let bar = foo.share;
                let i = foo.i.share;
                bar→;
                ();
            }
        }
    "#
);

After foo.share, we can still read foo.i. Reading shared data does not prevent other reads. Let’s walk through how the checker handles this.

Typing foo.share

The checker uses the share place rule:

type_expr::share place [src]
(access_permitted(env, live_after, Access::SharePlace, place) => env)

(let ty_place = env.place_ty(place)?)
(let ty = Ty::apply_perm(Perm::share_from(set![place]), ty_place.strip_perm()))
----------------------------------- ("share place")
(type_expr(env, live_after, PlaceExpr { access: Access::SharePlace, place }) => (env, ty))

First, access_permitted(env, ..., Access::SharePlace, place) checks the liens of live variables for conflicting accesses. Then env.place_ty(place) finds the place’s type. The result applies shared[foo] to the underlying type, with the outer permission stripped: shared[foo] Foo.

The corresponding access_ty rule constructs the same type:

access_ty::share [src]
(let perm = Perm::share_from(set![place]))
----------------------------------- ("share")
(access_ty(_env, Access::SharePlace, place, ty) => Ty::apply_perm(perm, ty.strip_perm()))

The permission records which place was shared. While the resulting value is live, the checker restricts changes to foo that would invalidate it.

How access control works

When the checker reaches foo.i.share, the environment contains:

VariableType
selfgiven Main
fooFoo
barshared[foo] Foo

Sharing foo.i must be compatible with every live variable’s type. The judgment env_permits_access performs these checks:

env_permits_access::env_permits_access [src]
(let live_var_tys: Vec<Ty> = live_after.vars().iter().map(|var| env.var_ty(var).unwrap()).cloned().collect())
(parameters_permit_access(env, live_var_tys, access, place) => env)
(accessed_place_permits_access(env, live_after, access, place) => env)
-------------------------------- ("env_permits_access")
(env_permits_access(env, live_after, access, place) => env)

Here bar is live because bar→ appears later, so the checker includes its shared[foo] Foo type.

Liens

A lien is an access constraint embedded in a type:

Lien [src]
#[term]
pub enum Lien {
    Share(Place),
    Mt(Place),
}

Lien::Share(place) records that the place is shared. Lien::Mt(place) records a mutable borrow of the place. The liens judgment extracts these constraints from permissions:

liens::perm-shared [src]
----------------------------------- ("perm-shared")
(liens(_env, Perm::Shared) => ())

For Perm::SharedFrom(places), it creates a Lien::Share for each origin, as well as the dependencies inherited from that origin’s type. For example, shared[foo] Foo yields Lien::Share(foo). Independent shared[] introduces no origin lien.

What sharing permits

The shared rule checks a sharing lien against an access:

lien_permit_access::shared [src]
(shared_place_permits_access(place, access, accessed_place) => ())
-------------------------------- ("shared")
(lien_permit_access(env, Lien::Share(place), access, accessed_place) => env)

It delegates to:

shared_place_permits_access [src]
shared_place_permits_access(shared_place: Place, access: Access, accessed_place: Place,) => ()

The three rules permit different accesses:

  • share-share allows sharing any place. Reads are compatible with reads.
  • share-mutation allows mutable access or dropping only when the accessed place is disjoint from the shared place.
  • share-give allows giving a place that is disjoint from or a prefix of the shared place. Moving a prefix preserves dependencies at the destination.

These checks govern sharing a place. Sharing a value with expr.share instead checks the inner expression, proves its type shareable, and applies shared[]. For foo→.share, the inner foo→ must pass the giving checks first.

In our example, foo.i.share is checked against Lien::Share(foo). The share-share rule succeeds because sharing the whole object is compatible with sharing one of its fields.

Mutation through shared data is an error

Sharing a place grants read access. A mutable borrow of an overlapping field conflicts with a live shared use:

mutation_through_ref_is_error [src]
crate::assert_err!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let foo = new Foo(new Data());
                let bar = foo.share;
                let i = foo.i!;
                bar→;
                ();
            }
        }
    "#,
    expect_test::expect![[r#"
        the rule "share-mutation" at (accesses.rs) failed because
          condition evaluted to false: `place_disjoint_from(accessed_place, shared_place)`
            accessed_place = foo . i
            shared_place = foo"#]]
);

The share-mutation rule requires foo.i to be disjoint from the shared place foo. It is a sub-place of foo, so the check fails. While the shared use is live, the original data cannot be mutated through foo or its fields.

Giving a field of shared data is an error

Similarly, you cannot give away a field of a place with a live shared use:

giving_field_while_refd_is_error [src]
crate::assert_err!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let foo = new Foo(new Data());
                let bar = foo.share;
                let i = foo.i→;
                bar→;
                ();
            }
        }
    "#,
    expect_test::expect![[r#"
        the rule "share-give" at (accesses.rs) failed because
          condition evaluted to false: `place_disjoint_from_or_prefix_of(accessed_place, shared_place)`
            accessed_place = foo . i
            shared_place = foo"#]]
);

foo.i is neither disjoint from nor a prefix of foo, so share-give fails. Giving just that field would leave the original object partially moved while bar still depends on the whole object.

The prefix exception permits moving the whole object. After let moved = foo→, a live shared use of foo depends on moved, and a shared use of foo.i depends on moved.i. The checker updates dependent types to preserve those restrictions. The Moves preserve dependencies property documents this behavior and its tested scope.

Liveness cancels restrictions

Liens matter while the variable carrying them is live: later code might still use it. Once that variable has no further uses, its restrictions vanish:

liveness_cancels_restrictions [src]
crate::assert_ok!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let foo = new Foo(new Data());
                let bar = foo!;
                let i = foo.i.share;
                ();
            }
        }
    "#
);

Here bar mutably borrows foo, but the program then shares foo.i. A live mutable borrow would block this access. However, bar is never used after let i = ..., so its type ![foo] Foo is absent from the checker’s set of live types. Its lien no longer blocks sharing the field.

This resembles Rust’s non-lexical lifetimes: an access constraint can end at last use rather than at the end of the enclosing scope.

Mutable borrows are more restrictive

A mutable lien blocks all overlapping accesses, including sharing:

mut_place_permits_access [src]
mut_place_permits_access(leased_place: Place, access: Access, accessed_place: Place,) => ()
  • lease-mutation permits sharing, mutable access, or dropping only for places disjoint from the leased place.
  • lease-give permits giving places disjoint from or a prefix of the leased place, preserving dependencies when a prefix moves.

This example fails:

mut_borrow_blocks_read [src]
crate::assert_err!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let foo = new Foo(new Data());
                let bar = foo!;
                let i = foo.i.share;
                bar→;
                ();
            }
        }
    "#,
    expect_test::expect![[r#"
        the rule "lease-mutation" at (accesses.rs) failed because
          condition evaluted to false: `place_disjoint_from(accessed_place, leased_place)`
            accessed_place = foo . i
            leased_place = foo"#]]
);

bar is live because bar→ occurs later. Its Lien::Mt(foo) is active, and foo.i overlaps foo, so the attempt to share the field is rejected.

Disjoint access is fine

Sharing or mutably borrowing foo does not prevent accessing unrelated data:

disjoint_access_is_fine [src]
crate::assert_ok!(
    r#"
        struct Data { }

        struct Main {
            fn test(given self) {
                let foo = new Data();
                let other = new Data();
                let bar = foo.share;
                other→;
                bar→;
                ();
            }
        }
    "#
);

bar shares foo, creating Lien::Share(foo). Giving other is permitted because other and foo are disjoint variables.

Transitive restrictions

Sharing a place also preserves dependencies in that place’s type:

transitive_restrictions [src]
crate::assert_err!(
    r#"
        struct Data { }

        struct Foo {
            i: Data;
        }

        struct Main {
            fn test(given self) {
                let p = new Foo(new Data());
                let q = p!;
                let r = q.share;
                let i = p.i.share;
                r→;
                ();
            }
        }
    "#,
    expect_test::expect![[r#"
        the rule "lease-mutation" at (accesses.rs) failed because
          condition evaluted to false: `place_disjoint_from(accessed_place, leased_place)`
            accessed_place = p . i
            leased_place = p"#]]
);

Here q has type ![p] Foo and r has type shared[q] Foo. The liens of r include both Lien::Share(q) and the Lien::Mt(p) inherited from q. Consequently, p.i.share is rejected by lease-mutation: p.i overlaps p.

Although q has no further uses after let r, the live variable r still carries the transitive dependency on p.

Giving a value can preserve a mutable borrow, but only when all possible origins supply the required capability:

Giving from alternative origins: every origin must satisfy mut

The permission given[p1, ..., pn] satisfies the mut predicate only when every possible originating place has a type satisfying mut. For the ordinary class used here, this means that every alternative supplies a mutable borrow (a lease), rather than merely permitting some form of mutation.

A lease is different from a unique owner

The current mut predicate distinguishes mutable borrowing from unique ownership. A given Wrapper permits field assignment but does not satisfy mut. Therefore, testing x.value = 42 alone would not establish this property. The tests instead pass x to a method requiring P is mut, with P = given[d1, d2].

For struct Wrapper { value: Int; }:

Origin typesgiven[d1, d2] is mut?
![source1] Wrapper, ![source2] WrapperYes
![source1] Wrapper, given Wrapper (either order)No
![source1] Wrapper, shared[source2] Wrapper (either order)No
![source1] Wrapper, shared Wrapper (either order)No
Any pair with neither origin satisfying mutNo

Here d1 and d2 are the possible originating places; source1 and source2 are independent referents. Giving from an owner does not by itself turn the result into a lease. Likewise, failure to prove shared does not prove mut.

Projected origins

The obligation concerns the full type of each originating place, including d1.field and d1.inner.field. A field accessed through a mutable borrow can satisfy mut. A unique container may also store a mutable reference in a field; in that case the field’s type, not the container’s ownership, matters. A projected origin containing a shared reference cannot supply a mutable lease.

Candidate lemma and evidence

For a well-formed environment and a nonempty list of valid places, a derivation of given[p1, ..., pn] is mut entails a derivation that the type of each pi satisfies mut. Conversely, those premises suffice through the model’s mv mut rule. This is a candidate lemma, not a theorem proved by these tests.

Four groups cover all pairs of given, mut, shared, and share origins: direct places, fields, nested fields, and permission-parameterized fields stored in unique containers. Every test contains a complete Dada program calling a method with an explicit P is mut requirement. Only the mut/mut pair should compile with that requirement.

Each rejecting test first checks that the same program compiles with just where P is mut removed. This isolates the requirement from the validity of the signature, projected places, and argument passing. The error snapshot then records the rejection with the requirement present. Referents remain live through the call. These are end-to-end type-checking tests, with no direct calls to predicate-proving functions.

This property concerns static predicate classification, not general assignment permission, runtime alias safety, or arbitrary generic predicate assumptions.

Property source and tests

A shared borrow does not grant a mutable lease

Borrowing with share produces a shared view. It does not satisfy mut, even when the borrowed place itself holds a mutable lease. A caller cannot pass that view to a method requiring P is mut merely because the underlying owner or lease permits mutation.

For an ordinary non-shared Wrapper, these examples distinguish the view from the place it borrows:

ViewSatisfies shared?Satisfies mut?
shared[source], where source is uniquely ownedYesNo
shared[lease], where lease: ![source] WrapperYesNo
shared[lease.field], through a mutable container leaseYesNo
shared ![source], after cancelling a dead intermediate leaseYesNo

The lifetime of the intermediate lease does not upgrade the view. When the lease is dead, the view can be coerced to shared ![source]; the shared component remains. When the lease stays live, it can be passed to a method requiring mut after the view’s final use. Its predicate remains true throughout; the view temporarily restricts access to it.

Candidate lemma and evidence

For concrete permissions and an ordinary non-shared struct, adding a shared view by share does not derive the mut predicate from the underlying place’s mut predicate. Eliminating a dead intermediate place preserves that shared component. This is a candidate lemma about static permission classification, not a proved theorem about arbitrary generic assumptions or runtime aliases.

Each example constructs its view in a complete Dada program and passes it to a method requiring either shared (accepted) or mut (rejected). The cases cover a unique owner, a live lease, a dead lease, explicit cancellation, and a projected field. Each rejection has a control with only its mut requirement removed. The live-lease cases also pass the original lease to a method requiring mut after the view’s last use. Referents remain live throughout the calls.

Property source and tests

Giving preserves the origins’ borrowing dependencies

A value with permission given[p1, ..., pn] retains borrowing dependencies from every possible originating place’s type. Giving that value to another binding does not erase those dependencies. Duplicating it, when permitted, leaves each live duplicate subject to the same restrictions.

For example, if d1: shared[source1.field] Data and d2: shared[source2.field] Data, then a live value with permission given[d1, d2] protects both possible referents from mutation. Even after d1, d2, the original value, and one duplicate have their last uses, a surviving duplicate still protects both fields. For mut origins, the surviving value blocks reads as well as mutations of the referents.

The origins are d1 and d2; their referents are source1.field and source2.field. given inherits the origins’ dependencies rather than creating fresh borrows of the origin bindings. Those bindings need not stay live. Origins can also be projected places such as d1.field storing a place sharing.

Disjoint sibling fields remain accessible. Once the last dependent value has its final use, the borrowing restrictions cease. If the referent itself is moved to a new binding while a dependent value stays live, its restrictions follow the new place, as in the separate move-dependency property.

Candidate lemma and evidence

In a well-formed environment, the liens of the permission given[p1, ..., pn] are the union of the liens obtained from the types of those places. No additional lien on an origin is introduced by given itself. For a permitted transfer to a fresh binding, the resulting live value retains those referent obligations, accounting for any place substitutions. This is a candidate static preservation lemma, not a proved theorem.

Complete Dada programs check both alternative referents separately, projected origins with stored refs, disjoint siblings, and access after the surviving value’s final use. Initialized local examples transfer a mutable borrow through given after its origin’s last use; paired examples check the same restriction before and after relocating the referent. The duplication cases were extracted from given_from_duplication_requires_shared_origins.

These examples use ordinary non-shared structs. They concern static access restrictions, not runtime mutable-pointer relocation, scope-exit cleanup, or every permission composition and generic type.

Property source and tests

Access constraints

AccessPermissionLienPermits sharing the origin?Permits mutating the origin?
place or place.shareshared[place]Lien::Share(place)YesNo
place!![place]Lien::Mt(place)NoNo

The checker extracts liens from live types, compares the affected places for overlap, and uses liveness to release restrictions after the last use.